diff --git a/3d-bin-packing/3d-bin-packing-tests.ts b/3d-bin-packing/3d-bin-packing-tests.ts index 319624d597..8e394e46bb 100644 --- a/3d-bin-packing/3d-bin-packing-tests.ts +++ b/3d-bin-packing/3d-bin-packing-tests.ts @@ -1,5 +1,5 @@ import packer = require("3d-bin-packing"); -import samchon = require("samchon-framework"); +import samchon = require("samchon"); function main(): void { diff --git a/3d-bin-packing/index.d.ts b/3d-bin-packing/index.d.ts index 14228f3141..8165ea513e 100644 --- a/3d-bin-packing/index.d.ts +++ b/3d-bin-packing/index.d.ts @@ -1,20 +1,22 @@ -// Type definitions for 3d-bin-packing +// Type definitions for 3d-bin-packing v1.1.2 // Project: https://github.com/betterwaysystems/packer // Definitions by: Jeongho Nam // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 -/// -/// -/// -/// -/// +/// declare module "3d-bin-packing" { - export = bws.packer; + export = bws.packer; +} + +/// +/// +declare namespace bws.packer { + export import library = samchon.library; + export import protocol = samchon.protocol; + function _Test(): void; } -declare var ReactDataGrid: typeof AdazzleReactDataGrid.ReactDataGrid; declare namespace boxologic { /** *

An abstract instance of boxologic.

@@ -62,122 +64,6 @@ declare namespace boxologic { constructor(width: number, height: number, length: number); } } -declare namespace bws.packer { - /** - * @brief Packer, a solver of 3d bin packing with multiple wrappers. - * - * @details - *

Packer is a facade class supporting packing operations in user side. You can solve a packing problem - * by constructing Packer class with {@link WrapperArray wrappers} and {@link InstanceArray instances} to - * pack and executing {@link optimize Packer.optimize()} method.

- * - *

In background side, deducting packing solution, those algorithms are used.

- * - * - * @author Jeongho Nam - */ - class Packer extends samchon.protocol.Entity { - /** - * Candidate wrappers who can contain instances. - */ - protected wrapperArray: WrapperArray; - /** - * Instances trying to pack into the wrapper. - */ - protected instanceArray: InstanceArray; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from members. - * - * @param wrapperArray Candidate wrappers who can contain instances. - * @param instanceArray Instances to be packed into some wrappers. - */ - constructor(wrapperArray: WrapperArray, instanceArray: InstanceArray); - /** - * @inheritdoc - */ - construct(xml: samchon.library.XML): void; - /** - * Get wrapperArray. - */ - getWrapperArray(): WrapperArray; - /** - * Get instanceArray. - */ - getInstanceArray(): InstanceArray; - /** - *

Deduct - * - */ - optimize(): WrapperArray; - /** - * @brief Initialize sequence list (gene_array). - * - * @details - *

Deducts initial sequence list by such assumption:

- * - *
    - *
  • Cost of larger wrapper is less than smaller one, within framework of price per volume unit.
  • - *
      - *
    • Wrapper Larger: (price: $1,000, volume: 100cm^3 -> price per volume unit: $10 / cm^3)
    • - *
    • Wrapper Smaller: (price: $700, volume: 50cm^3 -> price per volume unit: $14 / cm^3)
    • - *
    • Larger's cost is less than Smaller, within framework of price per volume unit
    • - *
    - *
- * - *

Method {@link initGenes initGenes()} constructs {@link WrapperGroup WrapperGroups} corresponding - * with the {@link wrapperArray} and allocates {@link instanceArray instances} to a {@link WrapperGroup}, - * has the smallest cost between containbles.

- * - *

After executing packing solution by {@link WrapperGroup.optimize WrapperGroup.optimize()}, trying to - * {@link repack re-pack} each {@link WrapperGroup} to another type of {@link Wrapper}, deducts the best - * solution between them. It's the initial sequence list of genetic algorithm.

- * - * @return Initial sequence list. - */ - protected initGenes(): GAWrapperArray; - /** - * Try to repack each wrappers to another type. - * - * @param $wrappers Wrappers to repack. - * @return Re-packed wrappers. - */ - protected repack($wrappers: WrapperArray): WrapperArray; - /** - * @inheritdoc - */ - TAG(): string; - /** - * @inheritdoc - */ - toXML(): samchon.library.XML; - } -} -declare namespace flex { - class TabNavigator extends React.Component { - render(): JSX.Element; - private handle_change(index, event); - } - class NavigatorContent extends React.Component { - render(): JSX.Element; - } - interface TabNavigatorProps extends React.Props { - selectedIndex?: number; - style?: React.CSSProperties; - } - interface NavigatorContentProps extends React.Props { - label: string; - } -} declare namespace boxologic { /** * A box, trying to pack into a {@link Pallet}. @@ -589,7 +475,7 @@ declare namespace bws.packer { * * @author Jeongho Nam */ - class PackerForm extends samchon.protocol.Entity { + class PackerForm extends protocol.Entity { /** * Form of Instances to pack. */ @@ -609,12 +495,12 @@ declare namespace bws.packer { * @param wrapperArray Type of Wrappers to be used. */ constructor(instanceFormArray: InstanceFormArray, wrapperArray: WrapperArray); - construct(xml: samchon.library.XML): void; + construct(xml: library.XML): void; optimize(): WrapperArray; getInstanceFormArray(): InstanceFormArray; getWrapperArray(): WrapperArray; TAG(): string; - toXML(): samchon.library.XML; + toXML(): library.XML; toPacker(): Packer; } /** @@ -622,12 +508,12 @@ declare namespace bws.packer { * * @author Jeongho Nam */ - class InstanceFormArray extends samchon.protocol.EntityArrayCollection { + class InstanceFormArray extends protocol.EntityArrayCollection { /** * Default Constructor. */ constructor(); - createChild(xml: samchon.library.XML): InstanceForm; + createChild(xml: library.XML): InstanceForm; TAG(): string; CHILD_TAG(): string; /** @@ -645,7 +531,7 @@ declare namespace bws.packer { * * @author Jeongho Nam */ - class InstanceForm extends samchon.protocol.Entity { + class InstanceForm extends protocol.Entity { /** * A duplicated Instance. */ @@ -661,7 +547,7 @@ declare namespace bws.packer { /** * @inheritdoc */ - construct(xml: samchon.library.XML): void; + construct(xml: library.XML): void; private createInstance(xml); key(): any; getInstance(): Instance; @@ -679,7 +565,7 @@ declare namespace bws.packer { /** * @inheritdoc */ - toXML(): samchon.library.XML; + toXML(): library.XML; /** *

Repeated {@link instance} to {@link InstanceArray}. * @@ -694,7 +580,7 @@ declare namespace bws.packer { } } declare namespace bws.packer { - class WrapperArray extends samchon.protocol.EntityArrayCollection { + class WrapperArray extends protocol.EntityArrayCollection { /** * Default Constructor. */ @@ -702,7 +588,7 @@ declare namespace bws.packer { /** * @inheritdoc */ - createChild(xml: samchon.library.XML): Wrapper; + createChild(xml: library.XML): Wrapper; /** * Get (calculate) price. */ @@ -756,7 +642,7 @@ declare namespace bws.packer { * * @author Jeongho Nam */ - interface Instance extends samchon.protocol.IEntity { + interface Instance extends protocol.IEntity { /** * Get name. */ @@ -813,7 +699,7 @@ declare namespace bws.packer { * * @author Jeongho Nam */ - class InstanceArray extends samchon.protocol.EntityArray { + class InstanceArray extends protocol.EntityArray { /** * Default Constructor. */ @@ -821,7 +707,7 @@ declare namespace bws.packer { /** * @inheritdoc */ - createChild(xml: samchon.library.XML): Instance; + createChild(xml: library.XML): Instance; /** * @inheritdoc */ @@ -832,13 +718,113 @@ declare namespace bws.packer { CHILD_TAG(): string; } } +declare namespace bws.packer { + /** + * @brief Packer, a solver of 3d bin packing with multiple wrappers. + * + * @details + *

Packer is a facade class supporting packing operations in user side. You can solve a packing problem + * by constructing Packer class with {@link WrapperArray wrappers} and {@link InstanceArray instances} to + * pack and executing {@link optimize Packer.optimize()} method.

+ * + *

In background side, deducting packing solution, those algorithms are used.

+ * + * + * @author Jeongho Nam + */ + class Packer extends protocol.Entity { + /** + * Candidate wrappers who can contain instances. + */ + protected wrapperArray: WrapperArray; + /** + * Instances trying to pack into the wrapper. + */ + protected instanceArray: InstanceArray; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from members. + * + * @param wrapperArray Candidate wrappers who can contain instances. + * @param instanceArray Instances to be packed into some wrappers. + */ + constructor(wrapperArray: WrapperArray, instanceArray: InstanceArray); + /** + * @inheritdoc + */ + construct(xml: library.XML): void; + /** + * Get wrapperArray. + */ + getWrapperArray(): WrapperArray; + /** + * Get instanceArray. + */ + getInstanceArray(): InstanceArray; + /** + *

Deduct + * + */ + optimize(): WrapperArray; + /** + * @brief Initialize sequence list (gene_array). + * + * @details + *

Deducts initial sequence list by such assumption:

+ * + *
    + *
  • Cost of larger wrapper is less than smaller one, within framework of price per volume unit.
  • + *
      + *
    • Wrapper Larger: (price: $1,000, volume: 100cm^3 -> price per volume unit: $10 / cm^3)
    • + *
    • Wrapper Smaller: (price: $700, volume: 50cm^3 -> price per volume unit: $14 / cm^3)
    • + *
    • Larger's cost is less than Smaller, within framework of price per volume unit
    • + *
    + *
+ * + *

Method {@link initGenes initGenes()} constructs {@link WrapperGroup WrapperGroups} corresponding + * with the {@link wrapperArray} and allocates {@link instanceArray instances} to a {@link WrapperGroup}, + * has the smallest cost between containbles.

+ * + *

After executing packing solution by {@link WrapperGroup.optimize WrapperGroup.optimize()}, trying to + * {@link repack re-pack} each {@link WrapperGroup} to another type of {@link Wrapper}, deducts the best + * solution between them. It's the initial sequence list of genetic algorithm.

+ * + * @return Initial sequence list. + */ + protected initGenes(): GAWrapperArray; + /** + * Try to repack each wrappers to another type. + * + * @param $wrappers Wrappers to repack. + * @return Re-packed wrappers. + */ + protected repack($wrappers: WrapperArray): WrapperArray; + /** + * @inheritdoc + */ + TAG(): string; + /** + * @inheritdoc + */ + toXML(): library.XML; + } +} declare namespace bws.packer { /** * A product. * * @author Jeongho Nam */ - class Product extends samchon.protocol.Entity implements Instance { + class Product extends protocol.Entity implements Instance { /** *

Name, key of the Product.

* @@ -921,7 +907,7 @@ declare namespace bws.packer { /** * @inheritdoc */ - toXML(): samchon.library.XML; + toXML(): library.XML; } } declare namespace bws.packer { @@ -937,7 +923,7 @@ declare namespace bws.packer { * * @author Jeongho Nam */ - class Wrap extends samchon.protocol.Entity { + class Wrap extends protocol.Entity { /** * A wrapper wrapping the {@link instance}. */ @@ -962,10 +948,6 @@ declare namespace bws.packer { * Placement orientation of wrapped {@link instance}. */ protected orientation: number; - /** - * - */ - protected color: number; /** * Construct from a Wrapper. * @@ -996,7 +978,7 @@ declare namespace bws.packer { /** * @inheritdoc */ - construct(xml: samchon.library.XML): void; + construct(xml: library.XML): void; /** * Factory method of wrapped Instance. * @@ -1058,11 +1040,11 @@ declare namespace bws.packer { /** * Get width. */ - getWidth(): number; + getLayoutWidth(): number; /** * Get height. */ - getHeight(): number; + getLayoutHeight(): number; /** * Get length. */ @@ -1071,9 +1053,9 @@ declare namespace bws.packer { * Get volume. */ getVolume(): number; - $instanceName: string; - $layoutScale: string; - $position: string; + readonly $instanceName: string; + readonly $layoutScale: string; + readonly $position: string; /** * @inheritdoc */ @@ -1081,19 +1063,7 @@ declare namespace bws.packer { /** * @inheritdoc */ - toXML(): samchon.library.XML; - /** - * Thickness of boundary lines of a shape represents the {@link instance}. - */ - private static BOUNDARY_THICKNESS; - /** - * - * - * @param geometry - * - * @return A shape and its boundary lines as 3D-objects. - */ - toDisplayObjects(geometry: THREE.Geometry): std.Vector; + toXML(): library.XML; } } declare namespace bws.packer { @@ -1102,7 +1072,7 @@ declare namespace bws.packer { * * @author Jeongho Nam */ - class Wrapper extends samchon.protocol.EntityDeque implements Instance { + class Wrapper extends protocol.EntityDeque implements Instance { /** *

Name, key of the Wrapper.

* @@ -1151,11 +1121,10 @@ declare namespace bws.packer { * @param thickness A thickness causes shrinkness on containable volume. */ constructor(name: string, price: number, width: number, height: number, length: number, thickness: number); - construct(xml: samchon.library.XML): void; /** * @inheritdoc */ - createChild(xml: samchon.library.XML): Wrap; + createChild(xml: library.XML): Wrap; /** * Key of a Wrapper is its name. */ @@ -1232,7 +1201,7 @@ declare namespace bws.packer { * @return utilization ratio. */ getUtilization(): number; - equal_to(obj: Wrapper): boolean; + equals(obj: Wrapper): boolean; /** *

Wrapper is enough greater?

* @@ -1272,8 +1241,8 @@ declare namespace bws.packer { $height: string; $length: string; $thickness: string; - $scale: string; - $spaceUtilization: string; + readonly $scale: string; + readonly $spaceUtilization: string; /** * @inheritdoc */ @@ -1289,25 +1258,7 @@ declare namespace bws.packer { /** * @inheritdoc */ - toXML(): samchon.library.XML; - private static scene; - private static renderer; - private static camera; - private static trackball; - private static mouse; - private static BOUNDARY_THICKNESS; - /** - *

Convert to a canvas containing 3D elements.

- * - * @param endIndex - * - * @return A 3D-canvans printing the Wrapper and its children {@link Wrap wrapped} - * {@link Instance instances} with those boundary lines. - */ - toCanvas(endIndex?: number): HTMLCanvasElement; - private static handleMouseMove(event); - private static animate(); - private static render(); + toXML(): library.XML; } } declare namespace bws.packer { @@ -1430,72 +1381,3 @@ declare namespace bws.packer { TAG(): string; } } -declare namespace bws.packer { - abstract class Editor extends React.Component<{ - dataProvider: samchon.protocol.EntityArrayCollection; - }, {}> { - private columns; - private selected_index; - /** - * Default Constructor. - */ - constructor(); - protected abstract createColumns(): AdazzleReactDataGrid.Column[]; - private get_row(index); - private insert_instance(event); - private erase_instances(event); - private handle_data_change(event); - private handle_row_change(event); - private handle_select(event); - render(): JSX.Element; - } -} -declare namespace bws.packer { - interface ItemEditorProps extends React.Props { - application: PackerApplication; - instances: InstanceFormArray; - wrappers: WrapperArray; - } - class ItemEditor extends React.Component { - private clear(event); - private open(event); - private save(event); - private pack(event); - render(): JSX.Element; - } - class InstanceEditor extends Editor { - protected createColumns(): AdazzleReactDataGrid.Column[]; - } - class WrapperEditor extends Editor { - protected createColumns(): AdazzleReactDataGrid.Column[]; - } -} -declare namespace bws.packer { - class PackerApplication extends React.Component<{}, {}> { - private instances; - private wrappers; - private result; - /** - * Default Constructor. - */ - constructor(); - pack(): void; - drawWrapper(wrapper: Wrapper, index?: number): void; - render(): JSX.Element; - static main(): void; - } -} -declare namespace bws.packer { - class ResultViewer extends React.Component { - drawWrapper(wrapper: Wrapper, index?: number): void; - private clear(event); - private open(event); - private save(event); - refresh(): void; - render(): JSX.Element; - } - interface WrapperViewerProps extends React.Props { - application: PackerApplication; - wrappers: WrapperArray; - } -} diff --git a/acorn/acorn-tests.ts b/acorn/acorn-tests.ts index fb79d23718..bda6844c84 100644 --- a/acorn/acorn-tests.ts +++ b/acorn/acorn-tests.ts @@ -67,3 +67,6 @@ acorn.getLineInfo('string', 56); acorn.plugins['test'] = function (p: acorn.Parser, config: any) { } + +acorn.tokenizer('console.log("hello world)', {locations: true}).getToken(); +acorn.tokenizer('console.log("hello world)', {locations: true})[Symbol.iterator]().next(); diff --git a/acorn/index.d.ts b/acorn/index.d.ts index 1944abc257..441deb29c3 100644 --- a/acorn/index.d.ts +++ b/acorn/index.d.ts @@ -238,9 +238,12 @@ declare namespace acorn { function parseExpressionAt(input: string, pos?: number, options?: Options): ESTree.Expression; - // todo: here the tokenizer function returns a Parser instance, that is targeting the detail of - // Parser prototype. Someone need this please reade README.md first. - // function tokenizer(options: Options, input: string): Parser; + interface ITokenizer { + getToken() : Token, + [Symbol.iterator](): Iterator + } + + function tokenizer(input: string, options: Options): ITokenizer; let parse_dammit: IParse | undefined; let LooseParser: ILooseParserClass | undefined; diff --git a/angular-dynamic-locale/index.d.ts b/angular-dynamic-locale/index.d.ts index 788c3ad87b..4ee0e6eb89 100644 --- a/angular-dynamic-locale/index.d.ts +++ b/angular-dynamic-locale/index.d.ts @@ -11,7 +11,7 @@ declare module 'angular' { export namespace dynamicLocale { interface tmhDynamicLocaleService { - set(locale: string): void; + set(locale: string): angular.IPromise; get(): string; } diff --git a/angular-oauth2/angular-oauth2-tests.ts b/angular-oauth2/angular-oauth2-tests.ts new file mode 100644 index 0000000000..2b2328d5ee --- /dev/null +++ b/angular-oauth2/angular-oauth2-tests.ts @@ -0,0 +1,10 @@ +import * as angular from 'angular'; + +angular.module('angular-oauth2-test', ['angular-oauth2']) + .config(['OAuthProvider', function(OAuthProvider:angular.oauth2.OAuthProvider){ + OAuthProvider.configure({ + baseUrl: 'https://api.website.com', + clientId: 'CLIENT_ID', + clientSecret: 'CLIENT_SECRET' // optional + }); + }]); \ No newline at end of file diff --git a/angular-oauth2/index.d.ts b/angular-oauth2/index.d.ts new file mode 100644 index 0000000000..e6b9592874 --- /dev/null +++ b/angular-oauth2/index.d.ts @@ -0,0 +1,49 @@ +// Type definitions for angular-oauth2 4.1 +// Project: https://github.com/oauthjs/angular-oauth2 +// Definitions by: Antério Vieira +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as angular from 'angular'; + +declare module 'angular' { + export namespace oauth2 { + interface OAuthConfig { + baseUrl: string; + clientId: string; + clientSecret?: string; + grantPath?: string; + revokePath?: string; + } + + interface OAuthProvider { + configure(params: OAuthConfig): OAuthConfig; + } + + interface Data { + username: string; + password: string; + } + + interface OAuth { + isAuthenticated(): boolean; + getAccessToken(data: Data, options?: any): angular.IPromise; + getRefreshToken(data?: Data, options?: any): angular.IPromise; + revokeToken(data?: Data, options?: any): angular.IPromise; + } + + interface OAuthTokenConfig { + name: string; + options: any; + } + + interface OAuthTokenOptions { + secure: boolean; + } + + interface OAuthTokenProvider { + configure(params: OAuthTokenConfig): OAuthTokenConfig; + } + + } +} + diff --git a/angular-oauth2/tsconfig.json b/angular-oauth2/tsconfig.json new file mode 100644 index 0000000000..717721bf79 --- /dev/null +++ b/angular-oauth2/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "angular-oauth2-tests.ts" + ] +} diff --git a/angular-oauth2/tslint.json b/angular-oauth2/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/angular-oauth2/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/antd/antd-tests.tsx b/antd/antd-tests.tsx deleted file mode 100644 index 1319455e91..0000000000 --- a/antd/antd-tests.tsx +++ /dev/null @@ -1,483 +0,0 @@ -/// - -/*import { - Affix, - Button, - Alert, - Badge, - Breadcrumb, - Calendar, - Carousel, - Cascader, - Checkbox, - Collapse, - DatePicker, - Dropdown, - Icon, - Form, - Input, - InputNumber, - Row, - Col, - Menu, - message, - Modal, - notification, - Pagination, - Popconfirm, - Popover, - Progress, - QueueAnim, - Radio, - Select, - Slider, - Spin, - Steps, - Switch, - Table, - Tabs, - Tag, - TimePicker, - Timeline, - Tooltip, - Transfer, - Tree, - TreeSelect, - Upload, - - - -} from 'antd';*/ - -import * as React from 'react' -import Affix from 'antd/lib/Affix' -import Button from 'antd/lib/Button' -import Alert from 'antd/lib/Alert' -import Badge from 'antd/lib/Badge' -import Breadcrumb from 'antd/lib/Breadcrumb' -import Calendar from 'antd/lib/Calendar' -import Carousel from 'antd/lib/Carousel' -import Cascader from 'antd/lib/Cascader' -import Checkbox from 'antd/lib/Checkbox' -import Collapse from 'antd/lib/Collapse' -import DatePicker from 'antd/lib/DatePicker' -import Dropdown from 'antd/lib/Dropdown' -import Icon from 'antd/lib/Icon' -import Form from 'antd/lib/Form' -import Input from 'antd/lib/Input' -import InputNumber from 'antd/lib/InputNumber' -import Row from 'antd/lib/Row' -import Col from 'antd/lib/Col' -import Menu from 'antd/lib/Menu' -import message from 'antd/lib/message' -import Modal from 'antd/lib/Modal' -import notification from 'antd/lib/notification' -import Pagination from 'antd/lib/Pagination' -import Popconfirm from 'antd/lib/Popconfirm' -import Popover from 'antd/lib/Popover' -import Progress from 'antd/lib/Progress' -import QueueAnim from 'antd/lib/QueueAnim' -import Radio from 'antd/lib/Radio' -import Select from 'antd/lib/Select' -import Slider from 'antd/lib/Slider' -import Spin from 'antd/lib/Spin' -import Steps from 'antd/lib/Steps' -import Switch from 'antd/lib/Switch' -import Table from 'antd/lib/Table' -import Tabs from 'antd/lib/Tabs' -import Tag from 'antd/lib/Tag' -import TimePicker from 'antd/lib/TimePicker' -import Timeline from 'antd/lib/Timeline' -import Tooltip from 'antd/lib/Tooltip' -import Transfer from 'antd/lib/Transfer' -import Tree from 'antd/lib/Tree' -import TreeSelect from 'antd/lib/TreeSelect' -import Upload from 'antd/lib/Upload' - -const ButtonGroup = Button.Group; -const CheckboxGroup = Checkbox.Group; -const Panel = Collapse.Panel; -const RangePicker = DatePicker.RangePicker; -const MonthPicker = DatePicker.MonthPicker; -const DropdownButton = Dropdown.Button; -const SubMenu = Menu.SubMenu; -const MenuItemGroup = Menu.ItemGroup; -const ProgressCircle = Progress.Circle; -const ProgressLine = Progress.Line; -const RadioGroup = Radio.Group; -const Option = Select.Option; -const OptGroup = Select.OptGroup; -const Step = Steps.Step; -const FormItem = Form.Item; -const TabPane = Tabs.TabPane; -const TreeNode = Tree.TreeNode; -const TreeSelectTreeNode = TreeSelect.TreeNode; - -const onChange = () => { } - -const options = [{ - value: 'zhejiang', - label: '浙江', - children: [{ - value: 'hangzhou', - label: '杭州', - children: [{ - value: 'xihu', - label: '西湖', - }], - }], -}, { - value: 'jiangsu', - label: '江苏', - children: [{ - value: 'nanjing', - label: '南京', - children: [{ - value: 'zhonghuamen', - label: '中华门', - }], - }], - }]; - -const columns = [{ - title: '姓名', - dataIndex: 'name', - key: 'name', - render(text: any) { - return {text}; - } -}, { - title: '年龄', - dataIndex: 'age', - key: 'age', - }, { - title: '住址', - dataIndex: 'address', - key: 'address', - }, { - title: '操作', - key: 'operation', - render(text: any, record: any) { - return ( - - 操作一{record.name} - - 操作二 - - - 更多 - - - ); - } - }]; -const data = [{ - key: '1', - name: '胡彦斌', - age: 32, - address: '西湖区湖底公园1号' -}, { - key: '2', - name: '胡彦祖', - age: 42, - address: '西湖区湖底公园1号' - }, { - key: '3', - name: '李大嘴', - age: 32, - address: '西湖区湖底公园1号' - }]; - -// tests -class AccountForm extends React.Component{ - render() { - const { getFieldProps } = this.props.form; - return ( -
- - - - - - - - - - -
- ); - } -} - -var Account = Form.create()(AccountForm); - -// app -class App extends React.Component{ - render() { - message.success('success') - message.config({ top: 100 }) - message.destroy() - message.info('info', 1000) - message.error('error', 3500) - - Modal.info({ title: 'hello' }); - Modal.success({ cancelText: 'No' }) - notification.success({ - message: 'hello', - description: 'test' - }) - const props = { - name: 'file', - action: '/upload.do', - onChange(info: any) { - if (info.file.status !== 'uploading') { - console.log(info.file, info.fileList); - } - if (info.file.status === 'done') { - message.success(`${info.file.name} 上传成功。`); - } else if (info.file.status === 'error') { - message.error(`${info.file.name} 上传失败。`); - } - } - }; - return
- Affix - - - test - - - - - - - - - - - - 首页 - 应用中心 - 应用列表 - 某应用 - - - - - -

1

-

2

-

3

-

4

-
- - - - - - -

test1

-
- -

test2

-
- -

test3

-
-
- - - - Hello Dp
}> - - 触发链接 - - - dpb

} type="primary"> - 某功能按钮 -
- - - - - - - 导航一 - - - 导航 - 子菜单}> - - 选项1 - 选项2 - - - 选项3 - 选项4 - - - - - - - - - - , - - - remove - - Overlay} title="title"> - - - - - - - - - - - - - - - - - - -
demo1
-
demo2
-
demo3
-
demo4
-
- - - A - B - C - D - - - - - - - - - - - - - - - - - - - - , - - - - 选项卡一内容 - 选项卡二内容 - 选项卡三内容 - - - 标签一 - 标签二 - { } }>标签三 - 标签四(链接) - - - - - - 创建服务现场 2015-09-01 - 初步排除网络异常 2015-09-01 - 技术测试异常 2015-09-01 - 网络异常正在修复 2015-09-01 - - - - - 鼠标移上来就会出现提示 - - - - - - - - - - - - - - - sss} key="0-0-1-0" /> - - - - - - - - - - - - - - - - - - - sss} key="random3" /> - - - - - - } -} diff --git a/antd/index.d.ts b/antd/index.d.ts deleted file mode 100644 index f262eda45f..0000000000 --- a/antd/index.d.ts +++ /dev/null @@ -1,2083 +0,0 @@ -// Type definitions for Antd v0.12.10 -// Project: http://ant.design -// Definitions by: bang88 , Bruce Mitchener -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 - -/// - -declare namespace Antd { - // Affix - interface AffixProps { - /** - * 达到指定偏移量后触发 - */ - offset?: number - } - /** - * # Affix - * 将页面元素钉在可视范围。 - * ## 何时使用 - * 当内容区域比较长,需要滚动页面时,这部分内容对应的操作或者导航需要在滚动范围内始终展现。常用于侧边菜单和按钮组合。 - * 页面可视范围过小时,慎用此功能以免遮挡页面内容。 - */ - export class Affix extends React.Component { - render(): JSX.Element - } - - - // Alert - interface AlertProps { - /** - * 必选参数,指定警告提示的样式,有四种选择`success`、`info`、`warn`、`error` - */ - type: string, - /**可选参数,默认不显示关闭按钮 */ - closable?: boolean, - /**可选参数,自定义关闭按钮 */ - closeText?: React.ReactNode, - /**必选参数,警告提示内容 */ - message: React.ReactNode, - /**可选参数,警告提示的辅助性文字介绍 */ - description?: React.ReactNode, - /**可选参数,关闭时触发的回调函数 */ - onClose?: Function, - /**可选参数,是否显示辅助图标 */ - showIcon?: boolean - } - - - /** - * # Alert - * 警告提示,展现需要关注的信息。 - - * ## 何时使用 - - * - 当某个页面需要向用户显示警告的信息时。 - * - 非浮层的静态展现形式,始终展现,不会自动消失,用户可以点击关闭。 - * */ - export class Alert extends React.Component { - render(): JSX.Element - } - - - // Badge - /** - * #Badge - * - * 图标右上角的圆形徽标数字。 - - * ## 何时使用 - - * 一般出现在通知图标或头像的右上角,用于显示需要处理的消息条数,通过醒目视觉形式吸引用户处理。 - * - */ - export class Badge extends React.Component { - render(): JSX.Element - } - interface BadgeProps { - /** 展示的数字,大于 overflowCount 时显示为 `${overflowCount}+`,为 0 时隐藏*/ - count: number, - /** 展示封顶的数字值*/ - overflowCount?: number, - /** 不展示数字,只有一个小红点*/ - dot?: boolean - } - - - // Button - interface ButtonProps { - /** 设置按钮类型,可选值为 `primary` `ghost` 或者不设 */ - type?: ButtonType | string, - /** 设置按钮形状,可选值为 `circle` `circle-outline` 或者不设*/ - shape?: string, - /** 设置按钮大小,可选值为 `small` `large` 或者不设*/ - size?: string, - /** 设置 `button` 原生的 `type` 值,可选值请参考 HTML标准*/ - htmlType?: string, - /** `click` 事件的 handler*/ - onClick?: Function, - /** 设置按钮载入状态*/ - loading?: boolean, - /** 样式名*/ - className?: string, - } - - - enum ButtonType { - primary, - ghost, - dashed - } - - interface ButtonGroupProps { - /** 设置按钮大小,可选值为 `small` `large` 或者不设*/ - size?: string - - } - - /** - 可以将多个 `Button` 放入 `Button.Group` 的容器中。 - - 通过设置 `size` 为 `large` `small` 分别把按钮组合设为大、小尺寸。若不设置 `size`,则尺寸为中。*/ - class ButtonGroup extends React.Component { - render(): JSX.Element - } - - /** - * #Button - 按钮用于开始一个即时操作。 - - ## 何时使用 - - 标记了一个(或封装一组)操作命令,响应用户点击行为,触发相应的业务逻辑。*/ - export class Button extends React.Component { - static Group: typeof ButtonGroup - render(): JSX.Element - } - - - - // Breadcrumb - - interface BreadcrumbItemProps { - /** 链接,如不传则不可点击 */ - href?: string - } - export class BreadcrumbItem extends React.Component { - render(): JSX.Element - } - - interface BreadcrumbProps { - /** router 的路由栈信息 */ - routes?: Array, - /** 路由的参数*/ - params?: Object, - /** 分隔符自定义*/ - separator?: string | React.ReactNode - } - /** - * #Breadcrumb - 显示当前页面在系统层级结构中的位置,并能向上返回。 - - ## 何时使用 - - - 当系统拥有超过两级以上的层级结构时; - - 当需要告知用户“你在哪里”时; - - 当需要向上导航的功能时。*/ - export class Breadcrumb extends React.Component { - static Item: typeof BreadcrumbItem - render(): JSX.Element - } - - - // Calendar - interface CalendarProps { - /** 自定义渲染月单元格*/ - monthCellRender?: Function, - /** 自定义渲染日期单元格*/ - dateCellRender?: Function, - /** 是否全屏显示*/ - fullscreen?: boolean, - /** 国际化配置*/ - locale?: Object, - prefixCls?: string, - className?: string, - style?: Object, - /** 日期面板变化回调*/ - onPanelChange?: Function, - /** 展示日期*/ - value?: Date, - /** 默认展示日期*/ - defaultValue?: Date, - /** 初始模式,`month/year`*/ - mode?: string - } - /** - * #Calendar - 按照日历形式展示数据的容器。 - - ## 何时使用 - - 当数据是日期或按照日期划分时,例如日程、课表、价格日历等,农历等。目前支持年/月切换。 - */ - export class Calendar extends React.Component { - render(): JSX.Element - } - - - // Carousel - interface CarouselProps { - /** 动画效果函数,可取 scrollx, fade*/ - effect?: string, - /** 是否显示面板指示点*/ - dots?: boolean, - /** 垂直显示*/ - vertical?: boolean, - /** 是否自动切换*/ - autoplay?: boolean, - /** 动画效果*/ - easing?: string, - /** 切换面板的回调*/ - beforeChange?: Function, - /** 切换面板的回调*/ - afterChange?: Function - } - /** - * #Carousel - 旋转木马,一组轮播的区域。 - - ## 何时使用 - - - 当有一组平级的内容。 - - 当内容空间不足时,可以用走马灯的形式进行收纳,进行轮播展现。 - - 常用于一组图片或卡片轮播。 - */ - export class Carousel extends React.Component { - render(): JSX.Element - } - - - - // Cascader - interface CascaderProps { - /** 可选项数据源*/ - options: Object, - /** 默认的选中项*/ - defaultValue?: Array, - /** 指定选中项*/ - value?: Array, - /** 选择完成后的回调*/ - onChange?: Function, - /** 选择后展示的渲染函数*/ - displayRender?: Function, - /** 自定义样式*/ - style?: Object, - /** 自定义类名*/ - className?: string, - /** 自定义浮层类名*/ - popupClassName?: string, - /** 浮层预设位置:`bottomLeft` `bottomRight` `topLeft` `topRight` */ - popupPlacement?: string, - /** 输入框占位文本*/ - placeholder?: string, - /** 输入框大小,可选 `large` `default` `small` */ - size?: string, - /** 禁用*/ - disabled?: boolean, - /** 是否支持清除*/ - allowClear?: boolean - - } - /** - * #Cascader - 级联选择框。 - - - ## 何时使用 - - - 需要从一组相关联的数据集合进行选择,例如省市区,公司层级,事物分类等。 - - 从一个较大的数据集合中进行选择时,用多级分类进行分隔,方便选择。 - - 比起 Select 组件,可以在同一个浮层中完成选择,有较好的体验。*/ - export class Cascader extends React.Component { - render(): JSX.Element - } - - - - - // Checkbox - interface CheckboxProps { - /** 指定当前是否选中*/ - checked?: boolean, - /** 初始是否选中*/ - defaultChecked?: boolean, - /** 变化时回调函数*/ - onChange?: Function - } - - interface CheckboxGroupProps { - /** 默认选中的选项*/ - defaultValue?: Array, - /** 指定选中的选项*/ - value?: Array, - /** 指定可选项*/ - options?: Array, - /** 变化时回调函数*/ - onChange?: Function - } - /** Checkbox 组*/ - class CheckboxGroup extends React.Component { - render(): JSX.Element - } - /** - * #Checkbox - 多选框。 - - ## 何时使用 - - - 在一组可选项中进行多项选择时; - - 单独使用可以表示两种状态之间的切换,和 `switch` 类似。区别在于切换 `switch` 会直接触发状态改变,而 `checkbox` 一般用于状态标记,需要和提交操作配合。 - */ - export class Checkbox extends React.Component { - static Group: typeof CheckboxGroup - render(): JSX.Element - } - - - - // Collapse - - interface CollapseProps { - /** 当前激活 tab 面板的 key*/ - activeKey?: Array | string, - /** 初始化选中面板的key */ - defaultActiveKey?: Array, - /** 切换面板的回调*/ - onChange?: Function - - } - class CollapsePanel extends React.Component<{ - /** 对应 activeKey */ - key: string, - /** 面板头内容*/ - header: React.ReactNode | string - }, {}> { - render(): JSX.Element - } - /** - * #Collapse - 可以折叠/展开的内容区域。 - - ## 何时使用 - - - 对复杂区域进行分组和隐藏,保持页面的整洁。 - - `手风琴` 是一种特殊的折叠面板,只允许单个内容区域展开。*/ - export class Collapse extends React.Component { - static Panel: typeof CollapsePanel - render(): JSX.Element - } - - - - // DatePicker - interface DatePickerProps { - - value?: string | Date, - defaultValue?: string | Date, - /** 展示的日期格式,配置参考 [GregorianCalendarFormat](https://github.com/yiminghe/gregorian-calendar-format)*/ - format?: string, - /** 不可选择的日期*/ - disabledDate?: Function, - /** 时间发生变化的回调,发生在用户选择时间时*/ - onChange?: Function, - /** 禁用*/ - disabled?: boolean, - style?: Object, - /** 格外的弹出日历样式*/ - popupStyle?: Object, - /** 输入框大小,`large` 高度为 32px,`small` 为 22px,默认是 28px*/ - size?: string, - /** 国际化配置*/ - locale?: Object, - /** 增加时间选择功能*/ - showTime?: boolean, - /** 点击确定按钮的回调*/ - onOk?: Function, - /** 定义浮层的容器,默认为 body 上新建 div*/ - getCalendarContainer?: Function - - } - interface RangePickProps extends DatePickerProps { - - } - class RangePicker extends React.Component { - render(): JSX.Element - } - class MonthPicker extends React.Component { - render(): JSX.Element - } - /** - * #DatePicker - 输入或选择日期的控件。 - - ## 何时使用 - - 当用户需要输入一个日期,可以点击标准输入框,弹出日期面板进行选择。*/ - export class DatePicker extends React.Component, {}> { - static RangePicker: typeof RangePicker - static MonthPicker: typeof MonthPicker - render(): JSX.Element - } - - - - - // Dropdown - - interface DropdownProps { - /** 触发下拉的行为 ['click'] or ['hover']*/ - trigger?: Array, - /** 菜单节点*/ - overlay: React.ReactNode - - } - - class DropdownButton extends React.Component<{ - /** 按钮类型*/ - type?: string, - /** 点击左侧按钮的回调*/ - onClick?: Function, - /** 触发下拉的行为*/ - trigger?: string, - /** 菜单节点*/ - overlay: React.ReactNode - }, {}> { - render(): JSX.Element - } - /** - * #Dropdown - 向下弹出的列表。 - - ## 何时使用 - - 当页面上的操作命令过多时,用此组件可以收纳操作元素。点击或移入触点,会出现一个下拉菜单。可在列表中进行选择,并执行相应的命令。 - */ - export class Dropdown extends React.Component { - static Button: typeof DropdownButton - render(): JSX.Element - } - - - - // Form - - interface FormItemProps { - prefixCls?: string, - /** label 标签的文本*/ - label?: React.ReactNode, - /** label 标签布局,通 `` 组件,设置 `span` `offset` 值,如 `{span: 3, offset: 12}`*/ - labelCol?: Object, - /** 提示信息,如不设置,则会根据校验规则自动生成 */ - help?: React.ReactNode | boolean, - /** 额外的提示信息,和 help 类似,当需要错误信息和提示文案同时出现时,可以使用这个。*/ - extra?: string, - /** 是否必填,如不设置,则会根据校验规则自动生成 */ - validateStatus?: string, - /** 配合 validateStatus 属性使用,是否展示校验状态图标 */ - hasFeedback?: boolean, - /** 需要为输入控件设置布局样式时,使用该属性,用法同 labelCol*/ - wrapperCol?: Object, - className?: string, - required?: boolean, - id?: string - } - /** - 表单一定会包含表单域,表单域可以是输入控件,标准表单域,标签,下拉菜单,文本域等。 - - 这里我们分别封装了表单域 `` 和输入控件 ``。*/ - export class FormItem extends React.Component { - render(): JSX.Element - } - interface FormComponentProps { - form: CreateFormOptions - } - export class FormComponent extends React.Component { - render(): JSX.Element - } - - // function create - type CreateFormOptions = { - /** 获取一组输入控件的值,如不传入参数,则获取全部组件的值*/ - getFieldsValue(): (fieldNames?: Array) => any - /** 获取一个输入控件的值*/ - getFieldValue(): (fieldName: string) => any - /** 设置一组输入控件的值*/ - setFieldsValue(): (obj: Object) => void - /** 设置一组输入控件的值*/ - setFields(): (obj: Object) => void - /** 校验并获取一组输入域的值与 Error*/ - validateFields(): (fieldNames?: Array, options?: Object, callback?: (erros: any, values: any) => void) => any - /** 与 `validateFields` 相似,但校验完后,如果校验不通过的菜单域不在可见范围内,则自动滚动进可见范围 */ - validateFieldsAndScroll(): (fieldNames?: Array, options?: Object, callback?: (erros: any, values: any) => void) => any - /** 获取某个输入控件的 Error */ - getFieldError(): (name: string) => Object - /** 判断一个输入控件是否在校验状态*/ - isFieldValidating(): (name: string) => Object - /**重置一组输入控件的值与状态,如不传入参数,则重置所有组件*/ - resetFields(): (names?: Array) => void - - getFieldsValue(): (id: string, options: { - /** 子节点的值的属性,如 Checkbox 的是 'checked'*/ - valuePropName?: string, - /** 子节点的初始值,类型、可选值均由子节点决定*/ - initialValue?: any, - /** 收集子节点的值的时机*/ - trigger?: string, - /** 校验子节点值的时机*/ - validateTrigger?: string, - /** 校验规则,参见 [async-validator](https://github.com/yiminghe/async-validator) */ - rules?: Array, - /** 必填输入控件唯一标志*/ - id?: string - }) => Array - - - } - - interface ComponentDecorator { - (component: T): T; - } - interface FormProps { - prefixCls?: string, - /** 水平排列布局*/ - horizontal?: boolean, - /** 行内排列布局*/ - inline?: boolean, - /** 经 `Form.create()` 包装过的组件会自带 `this.props.form` 属性,直接传给 Form 即可*/ - form?: Object, - /** 数据验证成功后回调事件*/ - onSubmit?: (e: React.FormEvent
) => void, - } - /** - * #Form - 具有数据收集、校验和提交功能的表单,包含复选框、单选框、输入框、下拉选择框等元素。 - - ## 表单 - - 我们为 `form` 提供了以下两种排列方式: - - - 水平排列:可以实现 `label` 标签和表单控件的水平排列; - - 行内排列:使其表现为 `inline-block` 级别的控件。 - */ - export class Form extends React.Component { - static Item: typeof FormItem - static create(options?: { - /** - * 当 `Form.Item` 子节点的值发生改变时触发,可以把对应的值转存到 Redux store - */ - onFieldsChange?: (props: Object, fields: Array) => void, - /** 把 props 转为对应的值,可用于把 Redux store 中的值读出 */ - mapPropsToFields?: (props: Object) => void - }): ComponentDecorator - render(): JSX.Element - } - - - - - - // Icon - interface IconProps { - /** 图标类型*/ - type: string - } - /** - * #Icon - 有含义的矢量图形,每一个图标打倒一个敌人。 - - ## 图标的命名规范 - - 我们为每个图标赋予了语义化的命名,命名规则如下: - - - 实心和描线图标保持同名,用 `-o` 来区分,比如 `question-circle`(实心) 和 `question-circle-o`(描线); - - - 命名顺序:`[icon名]-[形状可选]-[描线与否]-[方向可选]`。 - - ## 如何使用 - - 使用 `` 标签声明组件,指定图标对应的 type 属性,示例代码如下: - - ```html - - ``` - - 最终会渲染为: - - ```html - - ```*/ - export class Icon extends React.Component { - render(): JSX.Element - } - - - - - // Input - interface InputProps { - /** 【必须】声明 input 类型,同原生 input 标签的 type 属性*/ - type?: string, - id: string | number, - /** 控件大小,默认值为 default 。注:标准表单内的输入框大小限制为 large。 {'large','default','small'}*/ - size?: string, - /** 是否禁用状态,默认为 false*/ - disabled?: boolean, - value?: any, - /** 设置初始默认值*/ - defaultValue?: any, - className?: string, - /** 带标签的 input,设置前置标签*/ - addonBefore?: React.ReactNode, - /** 带标签的 input,设置后置标签*/ - addonAfter?: React.ReactNode, - prefixCls?: string, - placeholder?: string - } - export class Input extends React.Component { - render(): JSX.Element - } - - - - - // InputNumber - interface InputNumberProps { - /** 最小值*/ - min: number, - /** 最大值*/ - max: number, - /** 当前值*/ - value?: number, - /** 每次改变步数*/ - step?: number, - /** 初始值*/ - defaultValue?: number, - /** 变化回调*/ - onChange?: Function, - /** 禁用*/ - disabled?: boolean, - /** 输入框大小*/ - size?: string - - } - /** - * #InputNumber - 通过鼠标或键盘,输入范围内的数值。 - - ## 何时使用 - - 当需要获取标准数值时。*/ - export class InputNumber extends React.Component { - render(): JSX.Element - } - - - // Layout - // Row - interface RowProps { - type?: string, - align?: string, - justify?: string, - className?: string - } - export class Row extends React.Component { - render(): JSX.Element - } - - // Col - interface ColProps { - span?: string, - order?: string, - offset?: string, - push?: string, - pull?: string, - className?: string - } - /** - 在多数业务情况下,Ant Design需要在设计区域内解决大量信息收纳的问题,因此在12栅格系统的基础上,我们将整个设计建议区域按照24等分的原则进行划分。 - - 划分之后的信息区块我们称之为“盒子”。建议横向排列的盒子数量最多四个,最少一个。“盒子”在整个屏幕上占比见上图。设计部分基于盒子的单位定制盒子内部的排版规则,以保证视觉层面的舒适感。 - - ## 概述 - - 布局的栅格化系统,我们是基于行(row)和列(col)来定义信息区块的外部框架,以保证页面的每个区域能够稳健地排布起来。下面简单介绍一下它的工作原理: - - * 通过`row`在水平方向建立一组`column`(简写col) - * 你的内容应当放置于`col`内,并且,只有`col`可以作为`row`的直接元素 - * 栅格系统中的列是指1到24的值来表示其跨越的范围。例如,三个等宽的列可以使用`.col-8`来创建 - * 如果一个`row`中的`col`总和超过24,那么多余的`col`会作为一个整体另起一行排列 - - ## Flex 布局 - - 我们的栅格化系统支持 Flex 布局,允许子元素在父节点内的水平对齐方式 - 居左、居中、居右、等宽排列、分散排列。子元素与子元素之间,支持顶部对齐、垂直居中对齐、底部对齐的方式。同时,支持使用 order 来定义元素的排列顺序。 - - Flex 布局是基于 24 栅格来定义每一个“盒子”的宽度,但排版则不拘泥于栅格。*/ - export class Col extends React.Component { - render(): JSX.Element - } - - - - - // Menu - interface MenuItemProps { - /** - * (是否禁用) - * - * @type {boolean} - */ - disabled?: boolean, - key: string - } - export class MenuItem extends React.Component { - render(): JSX.Element - } - - interface MenuSubMenuProps { - /** - * (子菜单项值) - * - * @type {(string | React.ReactNode)} - */ - title: string | React.ReactNode, - /** - * (子菜单的菜单项) - * - * @type {(MenuItem | MenuSubMenu)} - */ - children?: JSX.Element[] - } - export class MenuSubMenu extends React.Component { - render(): JSX.Element - } - - interface MenuItemGroupProps { - /** - * (分组标题) - * - * @type {(string | React.ReactNode)} - */ - title: string | React.ReactNode, - /** - * (分组的菜单项) - * - * @type {MenuItem} - */ - children?: JSX.Element[] - } - export class MenuItemGroup extends React.Component { - render(): JSX.Element - } - - - // enum - enum MenuTheme { - light, - dark - } - enum MenuMode { - vertical, - horizontal, - inline - } - interface MenuProps { - /** 主题颜色*/ - theme?: MenuTheme | string, - /** 菜单类型 enum: `vertical` `horizontal` `inline`*/ - mode?: MenuMode | string, - /** 当前选中的菜单项 key 数组*/ - selectedKeys?: Array, - /** 初始选中的菜单项 key 数组*/ - defaultSelectedKeys?: Array, - /** 当前展开的菜单项 key 数组*/ - openKeys?: Array, - /** 初始展开的菜单项 key 数组*/ - defaultOpenKeys?: Array, - /** - * 被选中时调用 - * - * @type {(item: any, key: string, selectedKeys: Array) => void} - */ - onSelect?: (item: any, key: string, selectedKeys: Array) => void, - /** 取消选中时调用*/ - onDeselect?: (item: any, key: string, selectedKeys: Array) => void, - /** 点击 menuitem 调用此函数*/ - onClick?: (item: any, key: string) => void, - /** 根节点样式*/ - style?: Object - } - /** - # Menu - 为页面和功能提供导航的菜单列表。 - - ## 何时使用 - - 导航菜单是一个网站的灵魂,用户依赖导航在各个页面中进行跳转。一般分为顶部导航和侧边导航,顶部导航提供全局性的类目和功能,侧边导航提供多级结构来收纳和排列网站架构。 - - 更多布局和导航的范例可以参考:[常用布局](/spec/layout)。*/ - export class Menu extends React.Component { - static Item: typeof MenuItem - static SubMenu: typeof MenuSubMenu - static ItemGroup: typeof MenuItemGroup - static Divider: typeof React.Component - render(): JSX.Element - } - - - - // Message - type MessageFunc = ( - /** 提示内容*/ - content: string, - /** 自动关闭的延时*/ - duration?: number - ) => void - /** - * #Message - 全局展示操作反馈信息。 - - ## 何时使用 - - - 可提供成功、警告和错误等反馈信息。 - - 顶部居中显示并自动消失,是一种不打断用户操作的轻量级提示方式。*/ - export const message: { - - success: MessageFunc - error: MessageFunc - info: MessageFunc - loading: MessageFunc - config: (options: { - /** - * 消息距离顶部的位置 - * - * @type {number} - */ - top: number - }) => void - destroy: () => void - } - - // Modal - type ModalFunc = (options: { - visible?: boolean, - title?: React.ReactNode | string, - onOk?: Function, - onCancel?: Function, - width?: string | number, - iconClassName?: string, - okText?: string, - cancelText?: string - }) => void - - interface ModalProps { - /** 对话框是否可见*/ - visible?: boolean, - /** 确定按钮 loading*/ - confirmLoading?: boolean, - /** 标题*/ - title?: React.ReactNode | string, - /** 是否显示右上角的关闭按钮*/ - closable?: boolean, - /** 点击确定回调*/ - onOk?: Function, - /** 点击遮罩层或右上角叉或取消按钮的回调*/ - onCancel?: Function, - /** 宽度*/ - width?: string | number, - /** 底部内容*/ - footer?: React.ReactNode | string, - /** 确认按钮文字*/ - okText?: string, - /** 取消按钮文字*/ - cancelText?: string, - /** 点击蒙层是否允许关闭*/ - maskClosable?: boolean - } - - /** - # Modal - 模态对话框。 - - ## 何时使用 - - 需要用户处理事务,又不希望跳转页面以致打断工作流程时,可以使用 `Modal` 在当前页面正中打开一个浮层,承载相应的操作。 - - 另外当需要一个简洁的确认框询问用户时,可以使用精心封装好的 `ant.Modal.confirm()` 等方法。*/ - export class Modal extends React.Component { - static info: ModalFunc - static success: ModalFunc - static error: ModalFunc - static confirm: ModalFunc - render(): JSX.Element - } - - - - - // Notification - type NotificationFunc = ( - config: { - /** 通知提醒标题,必选 */ - message: React.ReactNode | string, - /** 通知提醒内容,必选*/ - description: React.ReactNode | string, - /** 自定义关闭按钮*/ - btn?: React.ReactNode | string, - /** 当前通知唯一标志*/ - key?: string, - /** 点击默认关闭按钮时触发的回调函数*/ - onClose?: Function, - /** 默认 4.5 秒后自动关闭,配置为 null 则不自动关闭*/ - duration?: number - }) => void - /** - * #notification - 全局展示通知提醒信息。 - - ## 何时使用 - - 在系统右上角显示通知提醒信息。经常用于以下情况: - - - 较为复杂的通知内容。 - - 带有交互的通知,给出用户下一步的行动点。 - - 系统主动推送。*/ - export const notification: { - success: NotificationFunc - error: NotificationFunc - info: NotificationFunc - warn: NotificationFunc - close: (key: string) => void - destroy: () => void - config: (options: { - /** 消息距离顶部的位置*/ - top: number - }) => void - - } - - - - - // Pagination - interface PaginationProps { - /** 当前页数*/ - current?: number, - /** 默认的当前页数*/ - defaultCurrent?: number, - /** 数据总数*/ - total: number, - /** 初始的每页条数*/ - defaultPageSize?: number, - /** 每页条数*/ - pageSize?: number, - /** 页码改变的回调,参数是改变后的页码*/ - onChange?: Function, - /** 是否可以改变 pageSize */ - showSizeChanger?: boolean, - /** 指定每页可以显示多少条*/ - pageSizeOptions?: Array - /** pageSize 变化的回调 */ - onShowSizeChange?: Function, - /** 是否可以快速跳转至某页*/ - showQuickJumper?: boolean, - /** 当为「small」时,是小尺寸分页 */ - size?: string, - /** 当添加该属性时,显示为简单分页*/ - simple?: Object, - /** 用于显示总共有多少条数据*/ - showTotal?: Function - } - /** - * #Pagination - 采用分页的形式分隔长列表,每次只加载一个页面。 - - ## 何时使用 - - - 当加载/渲染所有数据将花费很多时间时; - - 可切换页码浏览数据。*/ - export class Pagination extends React.Component { - render(): JSX.Element - } - - - - - // Popconfirm - enum Placement { - top, left, right, bottom - } - interface PopconfirmProps { - /** - * 气泡框位置,可选 `top/left/right/bottom` - * - * @type {(Placement | string)} - */ - placement?: Placement | string, - /** 确认框的描述*/ - title?: string, - /** 点击确认的回调*/ - onConfirm?: Function, - onCancel?: Function, - /** 显示隐藏的回调*/ - onVisibleChange?: (visible: boolean) => void, - /** 确认按钮文字*/ - okText?: string, - /** 取消按钮文字*/ - cancelText?: string - } - /** - * #Popconfirm - 点击元素,弹出气泡式的确认框。 - - ## 何时使用 - - 目标元素的操作需要用户进一步的确认时,在目标元素附近弹出浮层提示,询问用户。 - - 和 `confirm` 弹出的全屏居中模态对话框相比,交互形式更轻量。 - */ - export class Popconfirm extends React.Component { - render(): JSX.Element - } - - - - - // Popover - enum Trigger { - hover, focus, click - } - enum PopoverPlacement { - top, - left, right, bottom, - topLeft, topRight, bottomLeft, bottomRight, - leftTop, leftBottom, rightTop, rightBottom - } - interface PopoverProps { - /** 触发行为,可选 `hover/focus/click` */ - trigger?: Trigger | string, - /** 气泡框位置,可选 `top/left/right/bottom` `topLeft/topRight/bottomLeft/bottomRight` `leftTop/leftBottom/rightTop/rightBottom`*/ - placement?: PopoverPlacement | string, - /** 卡片标题*/ - title?: React.ReactNode | string, - /** 卡片内容*/ - overlay?: React.ReactNode | string, - prefixCls?: string, - /** 用于手动控制浮层显隐*/ - visible?: boolean, - /** 显示隐藏改变的回调*/ - onVisibleChange?: Function - } - /** - * #Popover - 点击/鼠标移入元素,弹出气泡式的卡片浮层。 - - ## 何时使用 - - 当目标元素有进一步的描述和相关操作时,可以收纳到卡片中,根据用户的操作行为进行展现。 - - 和 `Tooltip` 的区别是,用户可以对浮层上的元素进行操作,因此它可以承载更复杂的内容,比如链接或按钮等。 - */ - export class Popover extends React.Component { - render(): JSX.Element - } - - - - - // Progress - enum ProgressStatus { - normal, - exception, - active - } - - interface LineProps { - /** 百分比*/ - percent: number, - /** 内容的模板函数*/ - format?: (percent: any) => void, - /** 状态,可选:normal、exception、active*/ - status?: ProgressStatus | string, - /** 进度条线的宽度,单位是px*/ - strokeWidth?: number, - /** 是否显示进度数值和状态图标*/ - showInfo?: boolean - } - export class Line extends React.Component { - render(): JSX.Element - } - - interface CircleProps { - /** 百分比*/ - percent: number, - /** 内容的模板函数*/ - format?: (percent: any) => void, - /** 状态,可选:normal、exception*/ - status?: ProgressStatus | string, - /** 进度条线的宽度,单位是进度条画布宽度的百分比*/ - strokeWidth?: number, - /** 必填,进度条画布宽度,单位px。这里没有提供height属性设置,Line型高度就是strokeWidth,Circle型高度等于width*/ - width?: number - } - export class Circle extends React.Component { - render(): JSX.Element - } - /** - * #Progress - 展示操作的当前进度。 - - ## 何时使用 - - 在操作需要较长时间才能完成时,为用户显示该操作的当前进度和状态。 - - * 当一个操作会打断当前界面,或者需要在后台运行,且耗时可能超过2秒时; - * 当需要显示一个操作完成的百分比时。*/ - export const Progress: { - Line: typeof Line, - Circle: typeof Circle - } - - - // QueueAnim - interface QueueAnimProps { - /** 动画内置参数 `left` `right` `top` `bottom` `scale` `scaleBig` `scaleX` `scaleY`*/ - type?: string | Array, - /** 配置动画参数 如 `{opacity:[1, 0],translateY:[0, -30]}` 具体参考 [velocity](http://julian.com/research/velocity) 的写法*/ - animConfig?: Object | Array, - /** 整个动画的延时,以毫秒为单位*/ - delay?: number | Array, - /** 每个动画的时间,以毫秒为单位*/ - duration?: number | Array, - /** 每个动画的间隔时间,以毫秒为单位*/ - interval?: number | Array, - /** 出场时是否倒放,从最后一个 dom 开始往上播放 */ - leaveReverse?: boolean, - /** 动画的缓动函数,[查看详细](http://julian.com/research/velocity/#easing)*/ - ease?: string | Array, - /** 进出场动画进行中的类名*/ - animatingClassName?: Array, - /** QueueAnim 替换的标签名*/ - component?: string - } - /** - * #QueueAnim - 通过简单的配置对一组元素添加串行的进场动画效果。 - - ## 何时使用 - - - 从内容A到内容B的转变过程时能有效的吸引用户注意力,突出视觉中心,提高整体视觉效果。 - - - 小的信息元素排布或块状较多的情况下,根据一定的路径层次依次进场,区分维度层级,来凸显量级,使页面转场更加流畅和舒适,提高整体视觉效果和产品的质感。 - - - 特别适合首页和需要视觉展示效果的宣传页,以及单页应用的切换页面动效。 - */ - export class QueueAnim extends React.Component { - render(): JSX.Element - } - - - - - // Radio - enum RadioGroupSize { - large, - default, - small - } - interface RadioGroupProps { - /** 选项变化时的回调函数*/ - onChange?: (e: Event) => void, - /** 用于设置当前选中的值*/ - value?: string, - /** 默认选中的值*/ - defaultValue?: string, - /** 大小,只对按钮样式生效*/ - size?: RadioGroupSize | string - } - export class RadioGroup extends React.Component { - render(): JSX.Element - } - - - interface RadioProps { - /** 指定当前是否选中*/ - checked?: boolean, - /** 初始是否选中*/ - defaultChecked?: boolean, - /** 根据 value 进行比较,判断是否选中 */ - value?: any - } - /** - * #Radio - 单选框。 - - ## 何时使用 - - - 用于在多个备选项中选中单个状态。 - - 和 Select 的区别是,Radio 所有选项默认可见,方便用户在比较中选择,因此选项不宜过多。 - */ - export class Radio extends React.Component { - static Group: typeof RadioGroup - static Button: typeof Button - render(): JSX.Element - } - - - - // Select - interface SelectOptionProps { - /** 是否禁用*/ - disabled?: boolean, - /** 如果 react 需要你设置此项,此项值与 value 的值相同,然后可以省略 value 设置*/ - key?: string, - /** 默认根据此属性值进行筛选*/ - value: string - } - export class SelectOption extends React.Component { - render(): JSX.Element - } - - interface SelectOptGroupProps { - /** 组名*/ - label: string | React.ReactNode, - key?: string - } - export class SelectOptGroup extends React.Component { - render(): JSX.Element - } - - interface SelectProps { - /** 指定当前选中的条目*/ - value?: string | Array, - /** 指定默认选中的条目*/ - defaultValue?: string | Array, - /** 支持多选*/ - multiple?: boolean, - /** 支持清除, 单选模式有效*/ - allowClear?: boolean, - /** 是否根据输入项进行筛选,可为一个函数,返回满足要求的 option 即可*/ - filterOption?: boolean | Function, - /** 可以把随意输入的条目作为 tag,输入项不需要与下拉选项匹配*/ - tags?: boolean, - /** 被选中时调用,参数为选中项的 value 值 */ - onSelect?: (value: any, option: any) => void, - /** 取消选中时调用,参数为选中项的 option value 值,仅在 multiple 或 tags 模式下生效*/ - onDeselect?: (value: any, option: any) => void, - /** 选中option,或input的value变化(combobox 模式下)时,调用此函数*/ - onChange?: (value: any, label: any) => void, - /** 文本框值变化时回调*/ - onSearch?: (value: string) => void, - /** 选择框默认文字*/ - placeholder?: string, - /** 搜索框默认文字*/ - searchPlaceholder?: string, - /** 当下拉列表为空时显示的内容*/ - notFoundContent?: string, - /** 下拉菜单和选择器同宽*/ - dropdownMatchSelectWidth?: boolean, - /** 搜索时过滤对应的 option 属性,如设置为 children 表示对内嵌内容进行搜索*/ - optionFilterProp?: string, - /** 输入框自动提示模式*/ - combobox?: SVGSymbolElement, - /** 选择框大小,可选 `large` `small` */ - size?: string, - /** 在下拉中显示搜索框*/ - showSearch?: boolean, - /** 是否禁用*/ - disabled?: boolean, - style?: Object - } - /** - * #Select - 类似 Select2 的选择器。 - - ## 何时使用 - - 弹出一个下拉菜单给用户选择操作,用于代替原生的选择器,或者需要一个更优雅的多选器时。*/ - export class Select extends React.Component { - static Option: typeof SelectOption - static OptGroup: typeof SelectOptGroup - render(): JSX.Element - } - - - - // Slider - interface SliderProps { - /** 最小值*/ - min?: number, - /** 最大值*/ - max?: number, - /** 步长,取值必须大于 0,并且可被 (max - min) 整除。当 `marks` 不为空对象时,可以设置 `step` 为 `null`,此时 Slider 的可选值仅有 marks 标出来的部分。*/ - step?: number, - /** 分段标记,key 的类型必须为 `Number` 且取值在闭区间 [min, max] 内*/ - marks?: { key: number, value: any }, - /** 设置当前取值。当 `range` 为 `false` 时,使用 `Number`,否则用 `[Number, Number]`*/ - value?: number | Array, - /** 设置当前取值。当 `range` 为 `false` 时,使用 `Number`,否则用 `[Number, Number]`*/ - defaultValue?: number | Array, - /** `marks` 不为空对象时有效,值为 true 时表示值为包含关系,false 表示并列*/ - included?: boolean, - /** 值为 `true` 时,滑块为禁用状态*/ - disabled?: boolean, - /** 当 `range` 为 `true` 时,该属性可以设置是否允许两个滑块交换位置。*/ - allowCross?: boolean, - /** 当 Slider 的值发生改变时,会触发 onChange 事件,并把改变后的值作为参数传入。*/ - onChange?: Function, - /** 与 `onmouseup` 触发时机一致,把当前值作为参数传入。*/ - onAfterChange?: Function, - /** Slider 会把当前值传给 `tipFormatter`,并在 Tooltip 中显示 `tipFormatter` 的返回值,若为 null,则隐藏 Tooltip。*/ - tipFormatter?: Function | any, - range?: boolean - } - /** - * #Slider - 滑动型输入器,展示当前值和可选范围。 - - ## 何时使用 - - 当用户需要在数值区间/自定义区间内进行选择时,可为连续或离散值。*/ - export class Slider extends React.Component { - render(): JSX.Element - } - - - - - // Spin - interface SpinProps { - /** spin组件中点的大小,可选值为 small default large*/ - size?: string, - /** 用于内嵌其他组件的模式,可以关闭 loading 效果*/ - spining?: boolean - } - /** - * #Spin - 用于页面和区块的加载中状态。 - - ## 何时使用 - - 页面局部处于等待异步数据或正在渲染过程时,合适的加载动效会有效缓解用户的焦虑。 - */ - export class Spin extends React.Component { - render(): JSX.Element - } - - - - - // Steps - enum StepStatus { - wait, process, finish - } - interface StepProps { - /** 可选参数,指定状态。当不配置该属性时,会使用父Steps元素的current来自动指定状态。*/ - status?: StepStatus | string, - /** 必要参数,标题。*/ - title: string | React.ReactNode, - /** 可选参数,步骤的详情描述。*/ - description?: string | React.ReactNode, - /** 可选参数,步骤的Icon。如果不指定,则使用默认的样式。*/ - icon?: string | React.ReactNode - } - export class Step extends React.Component { - render(): JSX.Element - } - - interface StepsProps { - /** 可选参数,指定当前处理正在执行状态的步骤,从0开始记数。在子Step元素中,可以通过status属性覆盖状态。*/ - current?: number, - /** 可选参数,指定大小(目前只支持普通和迷你两种大小)。 small, default */ - size?: string, - /** 可选参数,指定步骤条方向(目前支持水平和竖直两种方向,默认水平方向)。*/ - direction?: string, - /** 可选参数,指定步骤的详细描述文字的最大宽度。*/ - maxDescriptionWidth?: number - - } - /** - * #Steps - 引导用户按照流程完成任务的导航条。 - - ## 何时使用 - - 当任务复杂或者存在先后关系时,将其分解成一系列步骤,从而简化任务。*/ - export class Steps extends React.Component { - static Step: typeof Step - render(): JSX.Element - } - - - - // Switch - interface SwitchProps { - /** 指定当前是否选中*/ - checked?: boolean, - /** 初始是否选中*/ - defaultChecked?: boolean, - /** 变化时回调函数*/ - onChange?: (checked: boolean) => void, - /** 选中时的内容*/ - checkedChildren?: React.ReactNode, - /** 非选中时的内容*/ - unCheckedChildren?: React.ReactNode, - /** 开关大小*/ - size?: string - } - /** - * #Switch - 开关选择器。 - - ## 何时使用 - - - 需要表示开关状态/两种状态之间的切换时; - - 和 `checkbox `的区别是,切换 `switch` 会直接触发状态改变,而 `checkbox` 一般用于状态标记,需要和提交操作配合。 - */ - export class Switch extends React.Component { - render(): JSX.Element - } - - - - - // Table - enum RowSelectionType { - checkbox, - radio - } - type SelectedRowKeys = Array - interface RowSelection { - type?: RowSelectionType | string, - selectedRowKeys?: SelectedRowKeys, - onChange?: (selectedRowKeys: SelectedRowKeys, selectedRows: any) => void, - getCheckboxProps?: (record: any) => void, - onSelect?: (record: any, selected: any, selectedRows: any) => void, - onSelectAll?: (rselectedecord: any, selectedRows: any, changeRows: any) => void - } - interface Columns { - /** React 需要的 key,建议设置*/ - key?: string, - /** 列头显示文字*/ - title?: string | React.ReactNode, - /** 列数据在数据项中对应的 key*/ - dataIndex?: string, - /** 生成复杂数据的渲染函数,参数分别为当前列的值,当前列数据,列索引,@return里面可以设置表格[行/列合并](#demo-colspan-rowspan)*/ - render?: (text?: any, record?: any, index?: number) => React.ReactNode, - /** 表头的筛选菜单项*/ - filters?: Array, - /** 本地模式下,确定筛选的运行函数*/ - onFilter?: Function, - /** 是否多选*/ - filterMultiple?: boolean, - /** 排序函数,本地排序使用一个函数,需要服务端排序可设为 true */ - sorter?: boolean | Function, - /** 表头列合并,设置为 0 时,不渲染*/ - colSpan?: number, - /** 列宽度*/ - width?: string | number, - /** 列的 className*/ - className?: string - } - interface TableProps { - /** 列表项是否可选择*/ - rowSelection?: RowSelection, - /** 分页器*/ - pagination?: Object, - /** 正常或迷你类型 : `default` or `small` */ - size?: string, - /** 数据数组*/ - dataSource: Array, - /** 表格列的配置描述*/ - columns: Columns, - /** 表格行 key 的取值*/ - rowKey?: (record: any, index: number) => string, - /** 额外的展开行*/ - expandedRowRender?: Function, - /** 默认展开的行*/ - defaultExpandedRowKeys?: Array, - /** 分页、排序、筛选变化时触发*/ - onChange?: (pagination: Object, filters: any, sorter: any) => void, - /** 页面是否加载中*/ - loading?: boolean, - /** 默认文案设置,目前包括排序、过滤、空数据文案: `{ filterConfirm: '确定', filterReset: '重置', emptyText: '暂无数据' }` */ - locale?: Object, - /** 展示树形数据时,每层缩进的宽度,以 px 为单位*/ - indentSize?: number, - /** 处理行点击事件*/ - onRowClick?: (record: any, index: number) => void, - /** 是否固定表头*/ - useFixedHeader?: boolean, - /** 是否展示外边框和列边框*/ - bordered?: boolean, - /** 是否显示表头*/ - showHeader?: boolean, - /** 表格底部自定义渲染函数*/ - footer?: (currentPageData: Object) => void - - } - /** - * #Table - 展示行列数据。 - - ## 何时使用 - - - 当有大量结构化的数据需要展现时; - - 当需要对数据进行排序、搜索、分页、自定义操作等复杂行为时。*/ - export class Table extends React.Component { - render(): JSX.Element - } - - - - // Tabs - interface TabPaneProps { - /** 选项卡头显示文字*/ - tab: React.ReactNode | string - } - export class TabPane extends React.Component { - render(): JSX.Element - } - - enum TabsType { - line, card, 'editable-card' - } - enum TabsPosition { - top, - right, - bottom, - left - } - interface TabsProps { - /** 当前激活 tab 面板的 key */ - activeKey?: string, - /** 初始化选中面板的 key,如果没有设置 activeKey*/ - defaultActiveKey?: string, - /** 切换面板的回调*/ - onChange?: Function, - /** tab 被点击的回调 */ - onTabClick?: Function, - /** tab bar 上额外的元素 */ - tabBarExtraContent?: React.ReactNode, - /** 页签的基本样式,可选 `line`、`card` `editable-card` 类型*/ - type?: TabsType | string, - /** 页签位置,可选值有 `top` `right` `bottom` `left`*/ - tabPosition?: TabsPosition | string, - /** 新增和删除页签的回调,在 `type="editable-card"` 时有效*/ - onEdit?: (targetKey: string, action: any) => void - } - /** - * #Tabs - 选项卡切换组件。 - - ## 何时使用 - - 提供平级的区域将大块内容进行收纳和展现,保持界面整洁。 - - Ant Design 依次提供了三级选项卡,分别用于不同的场景。 - - - 卡片式的页签,提供可关闭的样式,常用于容器顶部。 - - 标准线条式页签,用于容器内部的主功能切换,这是最常用的 Tabs。 - - [RadioButton](/components/radio/#demo-radiobutton) 可作为更次级的页签来使用。*/ - export class Tabs extends React.Component { - static TabPane: typeof TabPane - render(): JSX.Element - } - - - - - // Tag - interface TagProps { - /** 标签是否可以关闭*/ - closable?: boolean, - /** 关闭时的回调*/ - onClose?: Function, - /** 动画关闭后的回调*/ - afterClose?: Function, - /** 标签的色彩*/ - color?: string - } - /** - * #Tag - 进行标记和分类的小标签。 - - ## 何时使用 - - - 用于标记事物的属性和维度。 - - 进行分类。*/ - export class Tag extends React.Component { - render(): JSX.Element - } - - - - - - - // TimePicker - interface TimePickerProps { - /** 默认时间*/ - value?: string | Date, - /** 初始默认时间*/ - defaultValue?: string | Date, - /** 展示的时间格式 : "HH:mm:ss"、"HH:mm"、"mm:ss" */ - format?: string, - /** 时间发生变化的回调*/ - onChange?: (Date: Date) => void, - /** 禁用全部操作*/ - disabled?: boolean, - /** 没有值的时候显示的内容*/ - placeholder?: string, - /** 国际化配置*/ - locale?: Object, - /** 隐藏禁止选择的选项*/ - hideDisabledOptions?: boolean, - /** 禁止选择部分小时选项*/ - disabledHours?: Function, - /** 禁止选择部分分钟选项*/ - disabledMinutes?: Function, - /** 禁止选择部分秒选项*/ - disabledSeconds?: Function - - } - /** - * #TimePicker - 输入或选择时间的控件。 - - 何时使用 - -------- - - 当用户需要输入一个时间,可以点击标准输入框,弹出时间面板进行选择。 - */ - export class TimePicker extends React.Component { - render(): JSX.Element - } - - - - - // Timeline - interface TimeLineItemProps { - /** 指定圆圈颜色。*/ - color?: string - } - export class TimeLineItem extends React.Component { - render(): JSX.Element - } - - interface TimelineProps { - /** 指定最后一个幽灵节点是否存在或内容*/ - pending?: boolean | React.ReactNode - } - /** - * #Timeline - 垂直展示的时间流信息。 - - ## 何时使用 - - - 当有一系列信息需要从上至下按时间排列时; - - 需要有一条时间轴进行视觉上的串联时;*/ - export class Timeline extends React.Component { - static Item: typeof TimeLineItem - render(): JSX.Element - } - - - - // Tooltip - - interface TooltipProps { - /** 气泡框位置,可选 `top` `left` `right` `bottom` `topLeft` `topRight` `bottomLeft` `bottomRight` `leftTop` `leftBottom` `rightTop` `rightBottom`*/ - placement?: PopoverPlacement | string, - /** 提示文字*/ - title?: string | React.ReactNode - } - /** - * #Tooltip - 简单的文字提示气泡框。 - - ## 何时使用 - - 鼠标移入则显示提示,移出消失,气泡浮层不承载复杂文本和操作。 - - 可用来代替系统默认的 `title` 提示,提供一个`按钮/文字/操作`的文案解释。*/ - export class Tooltip extends React.Component { - render(): JSX.Element - } - - - - - - // Transfer - interface TransferProps { - /** 数据源*/ - dataSource: Array, - /** 每行数据渲染函数*/ - render?: (record: Object) => any, - /** 显示在右侧框数据的key集合*/ - targetKeys: Array, - /** 变化时回调函数*/ - onChange?: (targetKeys: any, direction: string, moveKeys: any) => void, - /** 两个穿梭框的自定义样式*/ - listStyle?: Object, - /** 自定义类*/ - className?: string, - /** 标题集合,顺序从左至右*/ - titles?: Array, - /** 操作文案集合,顺序从上至下*/ - operations?: Array, - /** 是否显示搜索框*/ - showSearch?: boolean, - /** 搜索框的默认值*/ - searchPlaceholder?: string, - /** 当列表为空时显示的内容*/ - notFoundContent?: React.ReactNode | string - /** 底部渲染函数*/ - footer?: (props: any) => any - } - /** - * #Transfer - 双栏穿梭选择框。 - - ## 何时使用 - - 用直观的方式在两栏中移动元素,完成选择行为。 - */ - export class Transfer extends React.Component { - render(): JSX.Element - } - - - - - - // Tree - interface TreeNodeProps { - disabled?: boolean, - disableCheckbox?: boolean, - title?: string | React.ReactNode, - key?: string, - isLeaf?: boolean - } - export class TreeNode extends React.Component { - render(): JSX.Element - } - - interface TreeProps { - showLine?: boolean, - className?: string, - /** 是否支持多选*/ - multiple?: boolean, - /** 是否支持选中*/ - checkable?: boolean, - /** 默认展开所有树节点*/ - defaultExpandAll?: boolean, - /** 默认展开指定的树节点*/ - defaultExpandedKeys?: Array, - /** (受控)展开指定的树节点*/ - expandedKeys?: Array, - /** (受控)选中复选框的树节点*/ - checkedKeys?: Array, - /** 默认选中复选框的树节点*/ - defaultCheckedKeys?: Array, - /** (受控)设置选中的树节点*/ - selectedKeys?: Array, - /** 默认选中的树节点*/ - defaultSelectedKeys?: Array, - /** 展开/收起节点时触发 */ - onExpand?: (node: any, expanded: any, expandedKeys: any) => void, - /** 点击复选框触发*/ - onCheck?: (checkedKeys: any, e: { checked: boolean, checkedNodes: any, node: any, event: Event }) => void, - /** 点击树节点触发*/ - onSelect?: (selectedKeys: any, e: { selected: boolean, selectedNodes: any, node: any, event: Event }) => void, - /** filter some treeNodes as you need. it should return true */ - filterTreeNode?: (node: any) => boolean, - /** 异步加载数据*/ - loadData?: (node: any) => void, - /** 响应右键点击*/ - onRightClick?: (options: { event: Event, node: any }) => void, - /** 设置节点可拖拽(IE>8)*/ - draggable?: boolean, - /** 开始拖拽时调用*/ - onDragStart?: (options: { event: Event, node: any }) => void, - /** dragenter 触发时调用*/ - onDragEnter?: (options: { event: Event, node: any, expandedKeys: any }) => void, - /** dragover 触发时调用 */ - onDragOver?: (options: { event: Event, node: any }) => void, - /** dragleave 触发时调用*/ - onDragLeave?: (options: { event: Event, node: any }) => void, - /** drop 触发时调用*/ - onDrop?: (options: { event: Event, node: any, dragNode: any, dragNodesKeys: any }) => void, - } - /** - * #Tree - * 文件夹、组织架构、生物分类、国家地区等等,世间万物的大多数结构都是树形结构。使用`树控件`可以完整展现其中的层级关系,并具有展开收起选择等交互功能。 - */ - export class Tree extends React.Component { - static TreeNode: typeof TreeNode - render(): JSX.Element - } - - - - - - // TreeSelect - interface TreeSelectTreeNodeProps { - disabled?: boolean, - /** 此项必须设置(其值在整个树范围内唯一)*/ - key: string, - /** 默认根据此属性值进行筛选*/ - value?: string, - /** 树节点显示的内容*/ - title?: React.ReactNode | string, - /** 是否是叶子节点*/ - isLeaf?: boolean - } - export class TreeSelectTreeNode extends React.Component { - render(): JSX.Element - } - - type TreeData = Array<{ value: any, label: string, children: TreeData }> - interface TreeSelectProps { - style?: Object, - /** 指定当前选中的条目*/ - value?: string | Array, - /** 指定默认选中的条目*/ - defaultValue?: string | Array, - /** 支持多选*/ - multiple?: boolean, - /** 可以把随意输入的条目作为 tag,输入项不需要与下拉选项匹配*/ - tags?: boolean, - /** 被选中时调用,参数为选中项的 value 值*/ - onSelect?: (value: any) => void, - /** 选中option,或input的value变化(combobox 模式下)时,调用此函数*/ - onChange?: (value: any, label: any) => void, - /** 显示清除按钮*/ - allowClear?: boolean, - /** 文本框值变化时回调*/ - onSearch?: (value: any) => void, - /** 选择框默认文字*/ - placeholder?: string, - /** 搜索框默认文字*/ - searchPlaceholder?: string, - /** 下拉菜单的样式*/ - dropdownStyle?: Object, - /** 下拉菜单和选择器同宽*/ - dropdownMatchSelectWidth?: boolean, - /** 输入框自动提示模式*/ - combobox?: boolean, - /** 选择框大小,可选 `large` `small`*/ - size?: string, - /** 在下拉中显示搜索框*/ - showSearch?: boolean, - /** 是否禁用*/ - disabled?: boolean, - /** 默认展开所有树节点*/ - treeDefaultExpandAll?: boolean, - /** 显示checkbox*/ - treeCheckable?: boolean, - /** 是否根据输入项进行筛选,返回值true*/ - filterTreeNode?: (treeNode: any) => boolean, - /** 输入项过滤对应的 treeNode 属性*/ - treeNodeFilterProp?: string, - /** 作为显示的prop设置*/ - treeNodeLabelProp?: string, - /** treeNodes数据,如果设置则不需要手动构造TreeNode节点(如果value在整个树范围内不唯一,需要设置`key`其值为整个树范围内的唯一id*/ - treeData?: TreeData, - /** 异步加载数据*/ - loadData?: (node: any) => void - } - /** - * #TreeSelect - 树型选择控件。 - - ## 何时使用 - - 类似 Select 的选择控件,可选择的数据结构是一个树形结构时,可以使用 TreeSelect,例如公司层级、学科系统、分类目录等等。 - */ - export class TreeSelect extends React.Component { - static TreeNode: typeof TreeSelectTreeNode - render(): JSX.Element - } - - - - - - - // Upload - interface UploadProps { - /** 可选参数, 上传的文件 */ - name?: string, - /** 必选参数, 上传的地址 */ - action: string, - /** 可选参数, 上传所需参数 */ - data?: Object, - /** 可选参数, 设置上传的请求头部,IE10 以上有效*/ - headers?: Object, - /** 可选参数, 是否展示 uploadList, 默认开启 */ - showUploadList?: boolean, - /** 可选参数, 是否支持多选文件,`ie10+` 支持。开启后按住 ctrl 可选择多个文件。*/ - multiple?: boolean, - /** 可选参数, 接受上传的文件类型, 详见 input accept Attribute */ - accept?: string, - /** 可选参数, 上传文件之前的钩子,参数为上传的文件,若返回 `false` 或者 Promise 则停止上传。**注意:该方法不支持老 IE**。*/ - beforeUpload?: Function, - /** 可选参数, 上传文件改变时的状态,详见 onChange */ - onChange?: (info: Object) => void, - /** 上传列表的内建样式,支持两种基本样式 `text` or `picture` */ - listType?: string, - /** 自定义类名*/ - className?: string - - } - /** - * #Upload - 文件选择上传和拖拽上传控件。 - - ## 何时使用 - - 上传是将信息(网页、文字、图片、视频等)通过网页或者上传工具发布到远程服务器上的过程。 - - - 当需要上传一个或一些文件时。 - - 当需要展现上传的进度时。 - - 当需要使用拖拽交互时。*/ - export class Upload extends React.Component { - render(): JSX.Element - } - - - - - - -} - - -// export all antd -declare module 'antd' { - export = Antd -} -// single export point -declare module 'antd/lib/Affix' { - export default Antd.Affix -} -declare module 'antd/lib/Button' { - export default Antd.Button -} -declare module 'antd/lib/Alert' { - export default Antd.Alert -} -declare module 'antd/lib/Badge' { - export default Antd.Badge -} -declare module 'antd/lib/Breadcrumb' { - export default Antd.Breadcrumb -} -declare module 'antd/lib/Calendar' { - export default Antd.Calendar -} -declare module 'antd/lib/Carousel' { - export default Antd.Carousel -} -declare module 'antd/lib/Cascader' { - export default Antd.Cascader -} -declare module 'antd/lib/Checkbox' { - export default Antd.Checkbox -} -declare module 'antd/lib/Collapse' { - export default Antd.Collapse -} -declare module 'antd/lib/DatePicker' { - export default Antd.DatePicker -} -declare module 'antd/lib/Dropdown' { - export default Antd.Dropdown -} -declare module 'antd/lib/Icon' { - export default Antd.Icon -} -declare module 'antd/lib/Form' { - export default Antd.Form -} -declare module 'antd/lib/Input' { - export default Antd.Input -} -declare module 'antd/lib/InputNumber' { - export default Antd.InputNumber -} -declare module 'antd/lib/Row' { - export default Antd.Row -} -declare module 'antd/lib/Col' { - export default Antd.Col -} -declare module 'antd/lib/Menu' { - export default Antd.Menu -} -declare module 'antd/lib/message' { - export default Antd.message -} -declare module 'antd/lib/Modal' { - export default Antd.Modal -} -declare module 'antd/lib/notification' { - export default Antd.notification -} -declare module 'antd/lib/Pagination' { - export default Antd.Pagination -} -declare module 'antd/lib/Popconfirm' { - export default Antd.Popconfirm -} -declare module 'antd/lib/Popover' { - export default Antd.Popover -} -declare module 'antd/lib/Progress' { - export default Antd.Progress -} -declare module 'antd/lib/QueueAnim' { - export default Antd.QueueAnim -} -declare module 'antd/lib/Radio' { - export default Antd.Radio -} -declare module 'antd/lib/Select' { - export default Antd.Select -} -declare module 'antd/lib/Slider' { - export default Antd.Slider -} -declare module 'antd/lib/Spin' { - export default Antd.Spin -} -declare module 'antd/lib/Steps' { - export default Antd.Steps -} -declare module 'antd/lib/Switch' { - export default Antd.Switch -} -declare module 'antd/lib/Table' { - export default Antd.Table -} -declare module 'antd/lib/Tabs' { - export default Antd.Tabs -} -declare module 'antd/lib/Tag' { - export default Antd.Tag -} -declare module 'antd/lib/TimePicker' { - export default Antd.TimePicker -} -declare module 'antd/lib/Timeline' { - export default Antd.Timeline -} -declare module 'antd/lib/Tooltip' { - export default Antd.Tooltip -} -declare module 'antd/lib/Transfer' { - export default Antd.Transfer -} -declare module 'antd/lib/Tree' { - export default Antd.Tree -} -declare module 'antd/lib/TreeSelect' { - export default Antd.TreeSelect -} -declare module 'antd/lib/Upload' { - export default Antd.Upload -} diff --git a/applicationinsights-js/applicationinsights-js-tests.ts b/applicationinsights-js/applicationinsights-js-tests.ts index f77bab2b0a..06a7d06bc5 100644 --- a/applicationinsights-js/applicationinsights-js-tests.ts +++ b/applicationinsights-js/applicationinsights-js-tests.ts @@ -1,4 +1,3 @@ - // More samples on: https://github.com/Microsoft/ApplicationInsights-JS/blob/master/API-reference.md var config: Microsoft.ApplicationInsights.IConfig = { @@ -24,7 +23,11 @@ var config: Microsoft.ApplicationInsights.IConfig = { disableCorrelationHeaders: true, disableFlushOnBeforeUnload: false, enableSessionStorageBuffer: false, - cookieDomain: "" + cookieDomain: "", + isCookieUseDisabled: true, + isRetryDisabled: true, + isPerfAnalyzerEnabled: true, + isStorageUseDisabled: true }; var appInsights: Microsoft.ApplicationInsights.IAppInsights = { @@ -35,17 +38,17 @@ var appInsights: Microsoft.ApplicationInsights.IAppInsights = { startTrackPage(name?: string) { return null; }, stopTrackPage(name?: string, url?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { return null; }, trackPageView(name?: string, url?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }, duration?: number) { return null; }, - startTrackEvent(name: string) { return null }, - stopTrackEvent(name: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { return null }, - trackEvent(name: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { return null }, - trackAjax(id: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number, method?: string) { return null }, - trackException(exception: Error, handledAt?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }, severityLevel?: AI.SeverityLevel) { return null }, - trackMetric(name: string, average: number, sampleCount?: number, min?: number, max?: number, properties?: { [name: string]: string; }) { return null }, - trackTrace(message: string, properties?: { [name: string]: string; }) { return null }, - flush() { return null }, - setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string) { return null }, - clearAuthenticatedUserContext() { return null }, - _onerror(message: string, url: string, lineNumber: number, columnNumber: number, error: Error) { return null } + startTrackEvent(name: string) { return null; }, + stopTrackEvent(name: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { return null; }, + trackEvent(name: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { return null; }, + trackDependency(id: string, method: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number) { return null; }, + trackException(exception: Error, handledAt?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }, severityLevel?: AI.SeverityLevel) { return null; }, + trackMetric(name: string, average: number, sampleCount?: number, min?: number, max?: number, properties?: { [name: string]: string; }) { return null; }, + trackTrace(message: string, properties?: { [name: string]: string; }) { return null; }, + flush() { return null; }, + setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string) { return null; }, + clearAuthenticatedUserContext() { return null; }, + _onerror(message: string, url: string, lineNumber: number, columnNumber: number, error: Error) { return null; } }; // trackPageView @@ -75,6 +78,9 @@ appInsights.trackException(new Error("sample error"), "handledAt", null, null); appInsights.trackTrace("message"); appInsights.trackTrace("message", null); +// trackDependency +appInsights.trackDependency("id", "POST", "http://example.com/test/abc", "/test/abc", null, true, null); + // flush appInsights.flush(); diff --git a/applicationinsights-js/index.d.ts b/applicationinsights-js/index.d.ts index ba154e5fe6..c032919618 100644 --- a/applicationinsights-js/index.d.ts +++ b/applicationinsights-js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for ApplicationInsights-JS v0.23.2 +// Type definitions for ApplicationInsights-JS 1.0 // Project: https://github.com/Microsoft/ApplicationInsights-JS // Definitions by: Kamil Szostak // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -323,7 +323,7 @@ declare module Microsoft.ApplicationInsights.Telemetry { /** * Constructs a new instance of the EventTelemetry object */ - constructor(name: string, properties?: Object, measurements?: Object); + constructor(name: string, properties?: any, measurements?: any); } class Exception implements Microsoft.ApplicationInsights.ISerializable { @@ -348,7 +348,7 @@ declare module Microsoft.ApplicationInsights.Telemetry { /** * Constructs a new isntance of the ExceptionTelemetry object */ - constructor(exception: Error, handledAt?: string, properties?: Object, measurements?: Object, severityLevel?: AI.SeverityLevel); + constructor(exception: Error, handledAt?: string, properties?: any, measurements?: any, severityLevel?: AI.SeverityLevel); /** * Creates a simple exception with 1 stack frame. Useful for manual constracting of exception. */ @@ -369,7 +369,7 @@ declare module Microsoft.ApplicationInsights.Telemetry { /** * Constructs a new instance of the MetricTelemetry object */ - constructor(name: string, value: number, count?: number, min?: number, max?: number, properties?: Object); + constructor(name: string, value: number, count?: number, min?: number, max?: number, properties?: any); } class PageView extends AI.PageViewData implements Microsoft.ApplicationInsights.ISerializable { @@ -477,7 +477,7 @@ declare module Microsoft.ApplicationInsights.Telemetry { /** * Constructs a new instance of the MetricTelemetry object */ - constructor(message: string, properties?: Object); + constructor(message: string, properties?: any); } } @@ -567,8 +567,12 @@ declare module Microsoft.ApplicationInsights { disableCorrelationHeaders?: boolean; disableFlushOnBeforeUnload?: boolean; enableSessionStorageBuffer?: boolean; + isCookieUseDisabled?: boolean; cookieDomain?: string; + isRetryDisabled?: boolean; + isPerfAnalyzerEnabled?: boolean; url?: string; + isStorageUseDisabled?: boolean; } /** @@ -657,7 +661,7 @@ declare module Microsoft.ApplicationInsights { interface IAppInsights { config: IConfig; context: ITelemetryContext; - queue: (() => void)[]; + queue: Array<() => void>; /** * Starts timing how long the user views a page or other item. Call this when the page opens. * This method doesn't send any telemetry. Call {@link stopTrackTelemetry} to log the page when it closes. @@ -717,16 +721,16 @@ declare module Microsoft.ApplicationInsights { [name: string]: number; }): any; /** - * Log an AJAX request - * @param id Event id - * @param absoluteUrl Full url - * @param pathName Leave this parameter blank - * @param totalTime Total time it took for AJAX request to complete - * @param success Whether AJAX request succeeded or failed - * @param resultCode Result code returned from AJAX call - * @param method HTTP verb that was used (GET, POST) - */ - trackAjax(id: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number, method?: string): any; + * Log a dependency call + * @param id unique id, this is used by the backend o correlate server requests. Use Util.newId() to generate a unique Id. + * @param method represents request verb (GET, POST, etc.) + * @param absoluteUrl absolute url used to make the dependency request + * @param pathName the path part of the absolute url + * @param totalTime total request time + * @param success indicates if the request was sessessful + * @param resultCode response code returned by the dependency request + */ + trackDependency(id: string, method: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number): any; /** * Log an exception you have caught. * @param exception An Error from a catch clause, or the string error message. @@ -755,7 +759,7 @@ declare module Microsoft.ApplicationInsights { /** * Log a diagnostic message. * @param message A message string - * @param properties map[string, string] - additional data used to filter traces in the portal. Defaults to empty. + * @param properties map[string, string] - additional data used to filter traces in the portal. Defaults to empty. */ trackTrace(message: string, properties?: { [name: string]: string; @@ -776,7 +780,7 @@ declare module Microsoft.ApplicationInsights { * Clears the authenticated user id and the account id from the user context. */ clearAuthenticatedUserContext(): any; - downloadAndSetup?(config: Microsoft.ApplicationInsights.IConfig): void; + downloadAndSetup?(config: Microsoft.ApplicationInsights.IConfig): any; /** * The custom error handler for Application Insights * @param {string} message - The error message diff --git a/applicationinsights-js/tslint.json b/applicationinsights-js/tslint.json new file mode 100644 index 0000000000..119a5839d0 --- /dev/null +++ b/applicationinsights-js/tslint.json @@ -0,0 +1,8 @@ +{ + "extends": "../tslint.json", + "rules": { + "interface-name": [ false ], + "no-internal-module": false, + "no-single-declare-module": false + } +} \ No newline at end of file diff --git a/auth0-js/auth0-js-tests.ts b/auth0-js/auth0-js-tests.ts index 7c910d1765..cbd791030b 100644 --- a/auth0-js/auth0-js-tests.ts +++ b/auth0-js/auth0-js-tests.ts @@ -1,4 +1,4 @@ -import 'auth0-js'; +import * as auth0 from 'auth0-js'; let webAuth = new auth0.WebAuth({ domain: 'mine.auth0.com', @@ -64,7 +64,7 @@ webAuth.signupAndAuthorize({ webAuth.client.login({ - ealm: 'Username-Password-Authentication', //connection name or HRD domain + realm: 'Username-Password-Authentication', //connection name or HRD domain username: 'info@auth0.com', password: 'areallystrongpassword', audience: 'https://mystore.com/api/v2', diff --git a/auth0-js/index.d.ts b/auth0-js/index.d.ts index 11cf16a3ed..f51e3979d3 100644 --- a/auth0-js/index.d.ts +++ b/auth0-js/index.d.ts @@ -1,456 +1,511 @@ -// Type definitions for Auth0.js 8.1 +// Type definitions for Auth0.js 8.2 // Project: https://github.com/auth0/auth0.js // Definitions by: Adrian Chia // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare namespace auth0 { +export as namespace auth0; - export class Authentication { - constructor(options: AuthOptions); - passwordless: PasswordlessAuthentication; - dbConnection: DBConnection; +export class Authentication { + constructor(options: AuthOptions); - /** - * Builds and returns the `/authorize` url in order to initialize a new authN/authZ transaction - * - * @method buildAuthorizeUrl - * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db - */ - buildAuthorizeUrl(options: any): string; + passwordless: PasswordlessAuthentication; + dbConnection: DBConnection; - /** - * Builds and returns the Logout url in order to initialize a new authN/authZ transaction - * - * @method buildLogoutUrl - * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--v2-logout - */ - buildLogoutUrl(options?: any): string; + /** + * Builds and returns the `/authorize` url in order to initialize a new authN/authZ transaction + * + * @method buildAuthorizeUrl + * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db + */ + buildAuthorizeUrl(options: any): string; - /** - * Makes a call to the `oauth/token` endpoint with `password` grant type - * - * @method loginWithDefaultDirectory - * @param {Object} options: https://auth0.com/docs/api-auth/grant/password - * @param {Function} callback - */ - loginWithDefaultDirectory(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + /** + * Builds and returns the Logout url in order to initialize a new authN/authZ transaction + * + * @method buildLogoutUrl + * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--v2-logout + */ + buildLogoutUrl(options?: any): string; - /** - * Makes a call to the `/ro` endpoint - * @param {any} options - * @param {Function} callback - * @deprecated `loginWithResourceOwner` will be soon deprecated, user `login` instead. - */ - loginWithResourceOwner(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + /** + * Makes a call to the `oauth/token` endpoint with `password` grant type + * + * @method loginWithDefaultDirectory + * @param {Object} options: https://auth0.com/docs/api-auth/grant/password + * @param {Function} callback + */ + loginWithDefaultDirectory(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; - /** - * Makes a call to the `oauth/token` endpoint with `password-realm` grant type - * @param {any} options - * @param {Function} callback - */ - login(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + /** + * Makes a call to the `/ro` endpoint + * @param {any} options + * @param {Function} callback + * @deprecated `loginWithResourceOwner` will be soon deprecated, user `login` instead. + */ + loginWithResourceOwner(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; - /** - * Makes a call to the `oauth/token` endpoint - * @param {any} options - * @param {Function} callback - */ - oauthToken(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + /** + * Makes a call to the `oauth/token` endpoint with `password-realm` grant type + * @param {any} options + * @param {Function} callback + */ + login(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; - /** - * Makes a call to the `/ssodata` endpoint - * - * @method getSSOData - * @param {Boolean} withActiveDirectories - * @param {Function} callback - * @deprecated `getSSOData` will be soon deprecated. - */ - getSSOData(callback?: (error?: Auth0Error, authResult?: any) => any): void; + /** + * Makes a call to the `oauth/token` endpoint + * @param {any} options + * @param {Function} callback + */ + oauthToken(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; - /** - * Makes a call to the `/ssodata` endpoint - * - * @method getSSOData - * @param {Boolean} withActiveDirectories - * @param {Function} callback - * @deprecated `getSSOData` will be soon deprecated. - */ - getSSOData(withActiveDirectories: boolean, callback?: (error?: Auth0Error, authResult?: any) => any): void; + /** + * Makes a call to the `/ssodata` endpoint + * + * @method getSSOData + * @param {Boolean} withActiveDirectories + * @param {Function} callback + * @deprecated `getSSOData` will be soon deprecated. + */ + getSSOData(callback?: (error?: Auth0Error, authResult?: any) => any): void; - /** - * Makes a call to the `/userinfo` endpoint and returns the user profile - * - * @method userInfo - * @param {String} accessToken - * @param {Function} callback - */ - userInfo(token: string, callback: (error?: Auth0Error, user?: any) => any): void; + /** + * Makes a call to the `/ssodata` endpoint + * + * @method getSSOData + * @param {Boolean} withActiveDirectories + * @param {Function} callback + * @deprecated `getSSOData` will be soon deprecated. + */ + getSSOData(withActiveDirectories: boolean, callback?: (error?: Auth0Error, authResult?: any) => any): void; - /** - * Makes a call to the `/delegation` endpoint - * - * @method delegation - * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--delegation - * @param {Function} callback - * @deprecated `delegation` will be soon deprecated. - */ - delegation(options: any, callback: (error?: Auth0Error, authResult?: Auth0DelegationToken) => any): any; + /** + * Makes a call to the `/userinfo` endpoint and returns the user profile + * + * @method userInfo + * @param {String} accessToken + * @param {Function} callback + */ + userInfo(token: string, callback: (error?: Auth0Error, user?: any) => any): void; - /** - * Fetches the user country based on the ip. - * - * @method getUserCountry - * @param {Function} callback - */ - getUserCountry(callback: (error?: Auth0Error, result?: any) => any): void; - } - - export class PasswordlessAuthentication { - constructor(request: any, option: any); - - /** - * Builds and returns the passwordless TOTP verify url in order to initialize a new authN/authZ transaction - * - * @method buildVerifyUrl - * @param {Object} options - * @param {Function} callback - */ - buildVerifyUrl(options: any): string; - - /** - * Initializes a new passwordless authN/authZ transaction - * - * @method start - * @param {Object} options: https://auth0.com/docs/api/authentication#passwordless - * @param {Function} callback - */ - start(options: PasswordlessStartOptions, callback: any): void; - - /** - * Verifies the passwordless TOTP and returns an error if any. - * - * @method buildVerifyUrl - * @param {Object} options - * @param {Function} callback - */ - verify(options: any, callback: any): void; - } - - export class DBConnection { - constructor(request: any, option: any); - - /** - * Signup a new user - * - * @method signup - * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup - * @param {Function} calback - */ - signup(options: any, callback: any): void; - - /** - * Initializes the change password flow - * - * @method signup - * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-change_password - * @param {Function} callback - */ - changePassword(options: ChangePasswordOptions, callback: any): void; - } - - export class Management { - constructor(options: ManagementOptions); - - /** - * Returns the user profile. https://auth0.com/docs/api/management/v2#!/Users/get_users_by_id - * - * @method getUser - * @param {String} userId - * @param {Function} callback - */ - getUser(userId: string, callback: (error?: Auth0Error, user?: any) => any): void; - - /** - * Updates the user metdata. It will patch the user metdata with the attributes sent. - * https://auth0.com/docs/api/management/v2#!/Users/patch_users_by_id - * - * @method patchUserMetadata - * @param {String} userId - * @param {Object} userMetadata - * @param {Function} callback - */ - patchUserMetadata(userId: string, userMetadata: any, callback: (error?: Auth0Error, user?: any) => any): void; - - /** - * Link two users. https://auth0.com/docs/api/management/v2#!/Users/post_identities - * - * @method linkUser - * @param {String} userId - * @param {String} secondaryUserToken - * @param {Function} callback - */ - linkUser(userId: string, secondaryUserToken: string, callback: (error?: Auth0Error, user?: any) => any): void; - } - - export class WebAuth { - constructor(options: AuthOptions); - client: Authentication; - popup: Popup; - redirect: Redirect; - - /** - * Redirects to the hosted login page (`/authorize`) in order to initialize a new authN/authZ transaction - * - * @method authorize - * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db - */ - authorize(options: any): void; - - /** - * Parse the url hash and extract the returned tokens depending on the transaction. - * - * Only validates id_tokens signed by Auth0 using the RS256 algorithm using the public key exposed - * by the `/.well-known/jwks.json` endpoint. Id tokens signed with other algorithms will not be - * accepted. - * - * @method parseHash - * @param {Object} options: - * @param {String} options.state [OPTIONAL] to verify the response - * @param {String} options.nonce [OPTIONAL] to verify the id_token - * @param {String} options.hash [OPTIONAL] the url hash. If not provided it will extract from window.location.hash - * @param {Function} callback: any(err, token_payload) - */ - parseHash(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; - - /** - * Decodes the id_token and verifies the nonce. - * - * @method validateToken - * @param {String} token - * @param {String} state - * @param {String} nonce - * @param {Function} callback: function(err, {payload, transaction}) - */ - validateToken(token: string, state: string, nonce: string, callback: any): void; - - /** - * Executes a silent authentication transaction under the hood in order to fetch a new token. - * - * @method renewAuth - * @param {Object} options: any valid oauth2 parameter to be sent to the `/authorize` endpoint - * @param {Function} callback - */ - renewAuth(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; - - /** - * Initialices a change password transaction - * - * @method changePassword - * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-change_password - * @param {Function} callback - */ - changePassword(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; - - /** - * Signs up a new user - * - * @method signup - * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup - * @param {Function} callback - */ - signup(options: any, callback: any): void; - - /** - * Signs up a new user, automatically logs the user in after the signup and returns the user token. - * The login will be done using /oauth/token with password-realm grant type. - * - * @method signupAndAuthorize - * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup - * @param {Function} callback - */ - signupAndAuthorize(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; - - /** - * Redirects to the auth0 logout page - * - * @method logout - * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--v2-logout - */ - logout(options: any): void; - - passwordlessStart(options: PasswordlessStartOptions, callback: (error?: Auth0Error, data?: any) => any): void; - - /** - * Verifies the passwordless TOTP and redirects to finish the passwordless transaction - * - * @method passwordlessVerify - * @param {Object} options: - * @param {Object} options.type: `sms` or `email` - * @param {Object} options.phoneNumber: only if type = sms - * @param {Object} options.email: only if type = email - * @param {Object} options.connection: the connection name - * @param {Object} options.verificationCode: the TOTP code - * @param {Function} callback - */ - passwordlessVerify(options: any, callback: any): void; - } - - export class Redirect { - constructor(client: any, options: any); - - /** - * Initializes the legacy Lock login flow in a popup - * - * @method loginWithCredentials - * @param {Object} options - * @param {Function} callback - * @deprecated `webauth.popup.loginWithCredentials` will be soon deprecated, use `webauth.client.login` instead. - */ - loginWithCredentials(options: any, callback: any): void; - - /** - * Signs up a new user and automatically logs the user in after the signup. - * - * @method signupAndLogin - * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup - * @param {Function} callback - */ - signupAndLogin(options: any, callback: any): void; - } - - export class Popup { - constructor(client: any, options: any); - - /** - * Initializes the popup window and returns the instance to be used later in order to avoid being blocked by the browser. - * - * @method preload - * @param {Object} options: receives the window height and width and any other window feature to be sent to window.open - */ - preload(options: any): any; - - /** - * Internal use. - * - * @method getPopupHandler - */ - getPopupHandler(options: any, preload: boolean): any; - /** - * Opens in a popup the hosted login page (`/authorize`) in order to initialize a new authN/authZ transaction - * - * @method authorize - * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db - * @param {Function} callback - */ - authorize(options: any, callback: any): void; - - /** - * Initializes the legacy Lock login flow in a popup - * - * @method loginWithCredentials - * @param {Object} options - * @param {Function} callback - * @deprecated `webauth.popup.loginWithCredentials` will be soon deprecated, use `webauth.client.login` instead. - */ - loginWithCredentials(options: any, callback: any): void; - - /** - * Verifies the passwordless TOTP and returns the requested token - * - * @method passwordlessVerify - * @param {Object} options: - * @param {Object} options.type: `sms` or `email` - * @param {Object} options.phoneNumber: only if type = sms - * @param {Object} options.email: only if type = email - * @param {Object} options.connection: the connection name - * @param {Object} options.verificationCode: the TOTP code - * @param {Function} callback - */ - passwordlessVerify(options: any, callback: any): void; - - /** - * Signs up a new user and automatically logs the user in after the signup. - * - * @method signupAndLogin - * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup - * @param {Function} callback - */ - signupAndLogin(options: any, callback: any): void; - } - - interface ManagementOptions { - domain: string; - token: string; - _sendTelemetry?: boolean; - _telemetryInfo?: any; - } - - interface AuthOptions { - domain: string; - clientID: string; - responseType?: string; - responseMode?: string; - redirectUri?: string; - scope?: string; - audience?: string; - leeway?: number; - _disableDeprecationWarnings?: boolean; - _sendTelemetry?: boolean; - _telemetryInfo?: any; - } - - interface PasswordlessAuthOptions { - connection: string; - verificationCode: string; - phoneNumber: string; - email: string; - } - - interface Auth0Error { - error: any; - errorDescription: string; - } - - interface Auth0DecodedHash { - accessToken?: string; - idToken?: string; - idTokenPayload?: any; - refreshToken?: string; - state?: string; - expiresIn?: number; - tokenType?: string; - } - - /** Represents the response from an API Token Delegation request. */ - interface Auth0DelegationToken { - /** The length of time in seconds the token is valid for. */ - ExpiresIn: number; - /** The JWT for delegated access. */ - idToken: string; - /** The type of token being returned. Possible values: "Bearer" */ - tokenType: string; - } - - interface ChangePasswordOptions { - connection: string; - email: string; - password?: string; - } - - interface PasswordlessStartOptions { - connection: string; - send: string; - phoneNumber?: string; - email?: string; - authParams?: any; - } - - interface PasswordlessVerifyOptions { - connection: string; - verificationCode: string; - phoneNumber?: string; - email?: string; - } + /** + * Makes a call to the `/delegation` endpoint + * + * @method delegation + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--delegation + * @param {Function} callback + * @deprecated `delegation` will be soon deprecated. + */ + delegation(options: any, callback: (error?: Auth0Error, authResult?: Auth0DelegationToken) => any): any; + /** + * Fetches the user country based on the ip. + * + * @method getUserCountry + * @param {Function} callback + */ + getUserCountry(callback: (error?: Auth0Error, result?: any) => any): void; +} + +export class PasswordlessAuthentication { + constructor(request: any, option: any); + + /** + * Builds and returns the passwordless TOTP verify url in order to initialize a new authN/authZ transaction + * + * @method buildVerifyUrl + * @param {Object} options + * @param {Function} callback + */ + buildVerifyUrl(options: any): string; + + /** + * Initializes a new passwordless authN/authZ transaction + * + * @method start + * @param {Object} options: https://auth0.com/docs/api/authentication#passwordless + * @param {Function} callback + */ + start(options: PasswordlessStartOptions, callback: any): void; + + /** + * Verifies the passwordless TOTP and returns an error if any. + * + * @method buildVerifyUrl + * @param {Object} options + * @param {Function} callback + */ + verify(options: any, callback: any): void; +} + +export class DBConnection { + constructor(request: any, option: any); + + /** + * Signup a new user + * + * @method signup + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup + * @param {Function} calback + */ + signup(options: any, callback: any): void; + + /** + * Initializes the change password flow + * + * @method signup + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-change_password + * @param {Function} callback + */ + changePassword(options: ChangePasswordOptions, callback: any): void; +} + +export class Management { + constructor(options: ManagementOptions); + + /** + * Returns the user profile. https://auth0.com/docs/api/management/v2#!/Users/get_users_by_id + * + * @method getUser + * @param {String} userId + * @param {Function} callback + */ + getUser(userId: string, callback: (error?: Auth0Error, user?: any) => any): void; + + /** + * Updates the user metdata. It will patch the user metdata with the attributes sent. + * https://auth0.com/docs/api/management/v2#!/Users/patch_users_by_id + * + * @method patchUserMetadata + * @param {String} userId + * @param {Object} userMetadata + * @param {Function} callback + */ + patchUserMetadata(userId: string, userMetadata: any, callback: (error?: Auth0Error, user?: any) => any): void; + + /** + * Link two users. https://auth0.com/docs/api/management/v2#!/Users/post_identities + * + * @method linkUser + * @param {String} userId + * @param {String} secondaryUserToken + * @param {Function} callback + */ + linkUser(userId: string, secondaryUserToken: string, callback: (error?: Auth0Error, user?: any) => any): void; +} + +export class WebAuth { + constructor(options: AuthOptions); + client: Authentication; + popup: Popup; + redirect: Redirect; + + /** + * Redirects to the hosted login page (`/authorize`) in order to initialize a new authN/authZ transaction + * + * @method authorize + * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db + */ + authorize(options: any): void; + + /** + * Parse the url hash and extract the returned tokens depending on the transaction. + * + * Only validates id_tokens signed by Auth0 using the RS256 algorithm using the public key exposed + * by the `/.well-known/jwks.json` endpoint. Id tokens signed with other algorithms will not be + * accepted. + * + * @method parseHash + * @param {Object} options: + * @param {String} options.state [OPTIONAL] to verify the response + * @param {String} options.nonce [OPTIONAL] to verify the id_token + * @param {String} options.hash [OPTIONAL] the url hash. If not provided it will extract from window.location.hash + * @param {Function} callback: any(err, token_payload) + */ + parseHash(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Decodes the id_token and verifies the nonce. + * + * @method validateToken + * @param {String} token + * @param {String} state + * @param {String} nonce + * @param {Function} callback: function(err, {payload, transaction}) + */ + validateToken(token: string, state: string, nonce: string, callback: any): void; + + /** + * Executes a silent authentication transaction under the hood in order to fetch a new token. + * + * @method renewAuth + * @param {Object} options: any valid oauth2 parameter to be sent to the `/authorize` endpoint + * @param {Function} callback + */ + renewAuth(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Initialices a change password transaction + * + * @method changePassword + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-change_password + * @param {Function} callback + */ + changePassword(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Signs up a new user + * + * @method signup + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup + * @param {Function} callback + */ + signup(options: any, callback: any): void; + + /** + * Signs up a new user, automatically logs the user in after the signup and returns the user token. + * The login will be done using /oauth/token with password-realm grant type. + * + * @method signupAndAuthorize + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup + * @param {Function} callback + */ + signupAndAuthorize(options: any, callback: (error?: Auth0Error, authResult?: any) => any): void; + + /** + * Redirects to the auth0 logout page + * + * @method logout + * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--v2-logout + */ + logout(options: any): void; + + passwordlessStart(options: PasswordlessStartOptions, callback: (error?: Auth0Error, data?: any) => any): void; + + /** + * Verifies the passwordless TOTP and redirects to finish the passwordless transaction + * + * @method passwordlessVerify + * @param {Object} options: + * @param {Object} options.type: `sms` or `email` + * @param {Object} options.phoneNumber: only if type = sms + * @param {Object} options.email: only if type = email + * @param {Object} options.connection: the connection name + * @param {Object} options.verificationCode: the TOTP code + * @param {Function} callback + */ + passwordlessVerify(options: any, callback: any): void; +} + +export class Redirect { + constructor(client: any, options: any); + + /** + * Initializes the legacy Lock login flow in a popup + * + * @method loginWithCredentials + * @param {Object} options + * @param {Function} callback + * @deprecated `webauth.popup.loginWithCredentials` will be soon deprecated, use `webauth.client.login` instead. + */ + loginWithCredentials(options: any, callback: any): void; + + /** + * Signs up a new user and automatically logs the user in after the signup. + * + * @method signupAndLogin + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup + * @param {Function} callback + */ + signupAndLogin(options: any, callback: any): void; +} + +export class Popup { + constructor(client: any, options: any); + + /** + * Returns a new instance of the popup handler + * + * @method buildPopupHandler + */ + buildPopupHandler(): any; + + /** + * Initializes the popup window and returns the instance to be used later in order to avoid being blocked by the browser. + * + * @method preload + * @param {Object} options: receives the window height and width and any other window feature to be sent to window.open + */ + preload(options: any): any; + + /** + * Internal use. + * + * @method getPopupHandler + */ + getPopupHandler(options: any, preload: boolean): any; + /** + * Opens in a popup the hosted login page (`/authorize`) in order to initialize a new authN/authZ transaction + * + * @method authorize + * @param {Object} options: https://auth0.com/docs/api/authentication#!#get--authorize_db + * @param {Function} callback + */ + authorize(options: any, callback: any): void; + + /** + * Initializes the legacy Lock login flow in a popup + * + * @method loginWithCredentials + * @param {Object} options + * @param {Function} callback + * @deprecated `webauth.popup.loginWithCredentials` will be soon deprecated, use `webauth.client.login` instead. + */ + loginWithCredentials(options: any, callback: any): void; + + /** + * Verifies the passwordless TOTP and returns the requested token + * + * @method passwordlessVerify + * @param {Object} options: + * @param {Object} options.type: `sms` or `email` + * @param {Object} options.phoneNumber: only if type = sms + * @param {Object} options.email: only if type = email + * @param {Object} options.connection: the connection name + * @param {Object} options.verificationCode: the TOTP code + * @param {Function} callback + */ + passwordlessVerify(options: any, callback: any): void; + + /** + * Signs up a new user and automatically logs the user in after the signup. + * + * @method signupAndLogin + * @param {Object} options: https://auth0.com/docs/api/authentication#!#post--dbconnections-signup + * @param {Function} callback + */ + signupAndLogin(options: any, callback: any): void; +} + +interface ManagementOptions { + domain: string; + token: string; + _sendTelemetry?: boolean; + _telemetryInfo?: any; +} + +interface AuthOptions { + domain: string; + clientID: string; + responseType?: string; + responseMode?: string; + redirectUri?: string; + scope?: string; + audience?: string; + leeway?: number; + plugins?: any[]; + _disableDeprecationWarnings?: boolean; + _sendTelemetry?: boolean; + _telemetryInfo?: any; +} + +interface PasswordlessAuthOptions { + connection: string; + verificationCode: string; + phoneNumber: string; + email: string; +} + +interface Auth0Error { + error?: any; + errorDescription?: string; + code?: string; + description?: string; + name?: string; + policy?: string; + original?: any; + statusCode?: number; + statusText?: string; +} + +interface Auth0DecodedHash { + accessToken?: string; + idToken?: string; + idTokenPayload?: any; + refreshToken?: string; + state?: string; + expiresIn?: number; + tokenType?: string; +} + +/** Represents the response from an API Token Delegation request. */ +interface Auth0DelegationToken { + /** The length of time in seconds the token is valid for. */ + ExpiresIn: number; + /** The JWT for delegated access. */ + idToken: string; + /** The type of token being returned. Possible values: "Bearer" */ + tokenType: string; +} + +interface ChangePasswordOptions { + connection: string; + email: string; + password?: string; +} + +interface PasswordlessStartOptions { + connection: string; + send: string; + phoneNumber?: string; + email?: string; + authParams?: any; +} + +interface PasswordlessVerifyOptions { + connection: string; + verificationCode: string; + phoneNumber?: string; + email?: string; +} + +interface Auth0UserProfile { + name: string; + nickname: string; + picture: string; + user_id: string; + username?: string; + given_name?: string; + family_name?: string; + email?: string; + email_verified?: string; + clientID: string; + gender?: string; + locale?: string; + identities: Auth0Identity[]; + created_at: string; + updated_at: string; + sub: string; + user_metadata?: any; + app_metadata?: any; +} + +interface MicrosoftUserProfile extends Auth0UserProfile { + emails?: string[]; //optional depending on whether email addresses permission is granted +} + +interface Office365UserProfile extends Auth0UserProfile { + tenantid: string; + upn: string; +} + +interface AdfsUserProfile extends Auth0UserProfile { + issuer?: string; +} + +interface Auth0Identity { + connection: string; + isSocial: boolean; + provider: string; + user_id: string; } diff --git a/auth0-lock/auth0-lock-tests.ts b/auth0-lock/auth0-lock-tests.ts index 8045386586..a241eb6d0c 100644 --- a/auth0-lock/auth0-lock-tests.ts +++ b/auth0-lock/auth0-lock-tests.ts @@ -1,4 +1,4 @@ -import 'auth0-js/v7'; +import * as auth0 from 'auth0-js'; import Auth0Lock from 'auth0-lock'; const CLIENT_ID = "YOUR_AUTH0_APP_CLIENTID"; @@ -38,7 +38,7 @@ lock.show(showOptions); // "on" event-driven example lock.on("authenticated", function(authResult : any) { - lock.getProfile(authResult.idToken, function(error, profile) { + lock.getProfile(authResult.idToken, function(error: auth0.Auth0Error, profile: auth0.Auth0UserProfile) { if (error) { // Handle error return; diff --git a/auth0-lock/index.d.ts b/auth0-lock/index.d.ts index 09c3f4fedd..285ad25288 100644 --- a/auth0-lock/index.d.ts +++ b/auth0-lock/index.d.ts @@ -1,9 +1,9 @@ -// Type definitions for auth0-lock 10.9 +// Type definitions for auth0-lock 10.10 // Project: http://auth0.com // Definitions by: Brian Caruso // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// interface Auth0LockAdditionalSignUpFieldOption { value: string; @@ -11,13 +11,13 @@ interface Auth0LockAdditionalSignUpFieldOption { } type Auth0LockAdditionalSignUpFieldOptionsCallback = - (error: Auth0Error, options: Auth0LockAdditionalSignUpFieldOption[]) => void; + (error: auth0.Auth0Error, options: Auth0LockAdditionalSignUpFieldOption[]) => void; type Auth0LockAdditionalSignUpFieldOptionsFunction = (callback: Auth0LockAdditionalSignUpFieldOptionsCallback) => void; type Auth0LockAdditionalSignUpFieldPrefillCallback = - (error: Auth0Error, prefill: string) => void; + (error: auth0.Auth0Error, prefill: string) => void; type Auth0LockAdditionalSignUpFieldPrefillFunction = (callback: Auth0LockAdditionalSignUpFieldPrefillCallback) => void; @@ -32,8 +32,8 @@ interface Auth0LockAdditionalSignUpField { validator?: (input: string) => { valid: boolean; hint?: string }; } -type Auth0LockAvatarUrlCallback = (error: Auth0Error, url: string) => void; -type Auth0LockAvatarDisplayNameCallback = (error: Auth0Error, displayName: string) => void; +type Auth0LockAvatarUrlCallback = (error: auth0.Auth0Error, url: string) => void; +type Auth0LockAvatarDisplayNameCallback = (error: auth0.Auth0Error, displayName: string) => void; interface Auth0LockAvatarOptions { url: (email: string, callback: Auth0LockAvatarUrlCallback) => void; @@ -63,6 +63,7 @@ interface Auth0LockAuthOptions { redirectUrl?: string; responseType?: string; sso?: boolean; + audience?: string; } interface Auth0LockPopupOptions { @@ -101,6 +102,7 @@ interface Auth0LockConstructorOptions { socialButtonStyle?: "big" | "small"; theme?: Auth0LockThemeOptions; usernameStyle?: string; + oidcConformant?: boolean; } interface Auth0LockFlashMessageOptions { @@ -123,15 +125,16 @@ interface Auth0LockStatic { new (clientId: string, domain: string, options?: Auth0LockConstructorOptions): Auth0LockStatic; // deprecated - getProfile(token: string, callback: (error: Auth0Error, profile: Auth0UserProfile) => void): void; - getUserInfo(token: string, callback: (error: Auth0Error, profile: Auth0UserProfile) => void): void; - + getProfile(token: string, callback: (error: auth0.Auth0Error, profile: auth0.Auth0UserProfile) => void): void; + getUserInfo(token: string, callback: (error: auth0.Auth0Error, profile: auth0.Auth0UserProfile) => void): void; + // https://github.com/auth0/lock#resumeauthhash-callback + resumeAuth( hash: string, callback: (error: auth0.Auth0Error, authResult: any) => void): void; show(options?: Auth0LockShowOptions): void; hide(): void; logout(query: any): void; on(event: "show" | "hide", callback: () => void): void; - on(event: "unrecoverable_error" | "authorization_error", callback: (error: Auth0Error) => void): void; + on(event: "unrecoverable_error" | "authorization_error", callback: (error: auth0.Auth0Error) => void): void; on(event: "authenticated", callback: (authResult: any) => void): void; on(event: string, callback: (...args: any[]) => void): void; } diff --git a/b_/b_-tests.ts b/b_/b_-tests.ts new file mode 100644 index 0000000000..c0a92a4c7d --- /dev/null +++ b/b_/b_-tests.ts @@ -0,0 +1,52 @@ +import b_ = require("b_"); + +const blockClass: string = b_("block"); +const blockWithModsClass: string = b_("block", {stringMod: "string", boolMod: true, numberMod: 5}); +const elemClass: string = b_("block", "elem"); +const elemWithModsClass: string = b_("block", "elem", {stringMod: "string", boolMod: true, numberMod: 5}); + +const withBlock = b_.with("block"); +const withBlockClass: string = withBlock(); +const withBlockWithModsClass: string = withBlock({stringMod: "string", boolMod: true, numberMod: 5}); +const withBlockElemClass: string = withBlock("elem"); +const withBlockElemWithModsClass: string = withBlock("elem", {stringMod: "string", boolMod: true, numberMod: 5}); + +const lockBlock = b_.lock("block"); +const lockBlockClass: string = lockBlock(); +const lockBlockWithModsClass: string = lockBlock({stringMod: "string", boolMod: true, numberMod: 5}); +const lockBlockElemClass: string = lockBlock("elem"); +const lockBlockElemWithModsClass: string = lockBlock("elem", {stringMod: "string", boolMod: true, numberMod: 5}); + +const withElem = b_.with("block", "elem"); +const withElemClass: string = withElem(); +const withElemWithModsClass: string = withElem({stringMod: "string", boolMod: true, numberMod: 5}); + +const parameterizedB_ = b_.B({ + tailSpace: " ", + elementSeparator: "-", + modSeparator: "_", + modValueSeparator: "-", + classSeparator: " ", + isFullModifier: true +}); + +const parameterizedBlockClass: string = parameterizedB_("block"); +const parameterizedBlockWithModsClass: string = parameterizedB_("block", {stringMod: "string", boolMod: true, numberMod: 5}); +const parameterizedElemClass: string = parameterizedB_("block", "elem"); +const parameterizedElemWithModsClass: string = parameterizedB_("block", "elem", {stringMod: "string", boolMod: true, numberMod: 5}); + +const parameterizedWithBlock = parameterizedB_.with("block"); +const parameterizedWithBlockClass: string = parameterizedWithBlock(); +const parameterizedWithBlockWithModsClass: string = parameterizedWithBlock({stringMod: "string", boolMod: true, numberMod: 5}); +const parameterizedWithBlockElemClass: string = parameterizedWithBlock("elem"); +const parameterizedWithBlockElemWithModsClass: string = parameterizedWithBlock("elem", {stringMod: "string", boolMod: true, numberMod: 5}); + +const parameterizedLockBlock = parameterizedB_.lock("block"); +const parameterizedLockBlockClass: string = parameterizedLockBlock(); +const parameterizedLockBlockWithModsClass: string = parameterizedLockBlock({stringMod: "string", boolMod: true, numberMod: 5}); +const parameterizedLockBlockElemClass: string = parameterizedLockBlock("elem"); +const parameterizedLockBlockElemWithModsClass: string = parameterizedLockBlock("elem", {stringMod: "string", boolMod: true, numberMod: 5}); + +const parameterizedWithElem = parameterizedB_.with("block", "elem"); +const parameterizedWithElemClass: string = parameterizedWithElem(); +const parameterizedWithElemWithModsClass: string = parameterizedWithElem({stringMod: "string", boolMod: true, numberMod: 5}); diff --git a/b_/index.d.ts b/b_/index.d.ts new file mode 100644 index 0000000000..fe59f2d72e --- /dev/null +++ b/b_/index.d.ts @@ -0,0 +1,40 @@ +// Type definitions for b_ 1.3 +// Project: https://github.com/azproduction/b_ +// Definitions by: Vasya Aksyonov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface Options { + tailSpace?: string; + elementSeparator?: string; + modSeparator?: string; + modValueSeparator?: string; + classSeparator?: string; + isFullModifier?: boolean; +} + +interface Mods { + [name: string]: any; +} + +interface Formatter { + (block: string, mods?: Mods): string; + (block: string, elem: string, mods?: Mods): string; + + with(block: string): BlockFormatter; + with(block: string, elem: string): ElemFormatter; + + lock(block: string): BlockFormatter; + lock(block: string, elem: string): ElemFormatter; + + B(options: Options): Formatter; +} + +interface BlockFormatter { + (mods?: Mods): string; + (elem: string, mods?: Mods): string; +} + +type ElemFormatter = (mods?: Mods) => string; + +declare const formatter: Formatter; +export = formatter; diff --git a/b_/tsconfig.json b/b_/tsconfig.json new file mode 100644 index 0000000000..5271d3aeeb --- /dev/null +++ b/b_/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "b_-tests.ts" + ] +} diff --git a/b_/tslint.json b/b_/tslint.json new file mode 100644 index 0000000000..2221e40e4a --- /dev/null +++ b/b_/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } \ No newline at end of file diff --git a/chai-enzyme/chai-enzyme-tests.tsx b/chai-enzyme/chai-enzyme-tests.tsx index a70f7e7f96..1398db807d 100644 --- a/chai-enzyme/chai-enzyme-tests.tsx +++ b/chai-enzyme/chai-enzyme-tests.tsx @@ -40,5 +40,8 @@ expect(wrapper).to.have.data("test", "Test"); expect(wrapper).to.have.style("background", "green"); expect(wrapper).to.have.state("test", "test"); expect(wrapper).to.have.prop("test", 5); +expect(wrapper).to.have.props(["test1", "test2"]); +expect(wrapper).to.have.props({ test: 5 }); expect(wrapper).to.contain(); +expect(wrapper).to.containMatchingElement(); expect(wrapper).to.match(); diff --git a/chai-enzyme/index.d.ts b/chai-enzyme/index.d.ts index 6997abd5fe..0d9eb2994f 100644 --- a/chai-enzyme/index.d.ts +++ b/chai-enzyme/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for chai-enzyme 0.5.0 +// Type definitions for chai-enzyme 0.6.1 // Project: https://github.com/producthunt/chai-enzyme // Definitions by: Alexey Svetliakov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -39,6 +39,12 @@ declare namespace Chai { */ className(name: string): Assertion; + /** + * Assert that the wrapper contains a certain element: + * @param selector + */ + containMatchingElement(selector: EnzymeSelector): Assertion; + /** * Assert that the wrapper contains a descendant matching the given selector: * @param selector @@ -140,6 +146,18 @@ declare namespace Chai { * @param val */ prop(key: string, val?: any): Assertion; + + /** + * Assert that the wrapper has given props [with values]: + * @param keys + */ + props(keys: string[]): Assertion; + + /** + * Assert that the wrapper has given props [with values]: + * @param props + */ + props(props: EnzymeSelector): Assertion; } } diff --git a/chrome/index.d.ts b/chrome/index.d.ts index 211375a3fe..b88ae5faf0 100644 --- a/chrome/index.d.ts +++ b/chrome/index.d.ts @@ -1831,7 +1831,7 @@ declare namespace chrome.devtools.panels { * If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ - setObject(jsonObject: string, rootTitle?: string, callback?: () => void): void; + setObject(jsonObject: Object, rootTitle?: string, callback?: () => void): void; /** * Sets a JSON-compliant object to be displayed in the sidebar pane. * @param jsonObject An object to be displayed in context of the inspected page. Evaluated in the context of the caller (API client). @@ -1839,7 +1839,7 @@ declare namespace chrome.devtools.panels { * If you specify the callback parameter, it should be a function that looks like this: * function() {...}; */ - setObject(jsonObject: string, callback?: () => void): void; + setObject(jsonObject: Object, callback?: () => void): void; /** * Sets an HTML page to be displayed in the sidebar pane. * @param path Relative path of an extension page to display within the sidebar. diff --git a/combined-stream/combined-stream-tests.ts b/combined-stream/combined-stream-tests.ts new file mode 100644 index 0000000000..776e530e63 --- /dev/null +++ b/combined-stream/combined-stream-tests.ts @@ -0,0 +1,30 @@ +import * as CombinedStream from "combined-stream"; +import { createReadStream, createWriteStream } from "fs"; + +const stream1 = new CombinedStream(); + +stream1.append(createReadStream("tsconfig.json")); +stream1.append(createReadStream("tslint.json")); +stream1.append(createReadStream("index.d.ts")); + +stream1.pipe(createWriteStream("combined.txt")); + +const stream2 = CombinedStream.create({ + maxDataSize: 1 << 32, + pauseStreams: false, +}); + +stream1.destroy(); + +// should log true +console.log(CombinedStream.isStreamLike(stream2)); + +stream2.on("data", (data) => { + console.log(data); +}); + +stream2.pipe(createWriteStream("combined.txt")); + +stream2.write(CombinedStream.name); + +stream2.destroy(); diff --git a/combined-stream/index.d.ts b/combined-stream/index.d.ts new file mode 100644 index 0000000000..cada758701 --- /dev/null +++ b/combined-stream/index.d.ts @@ -0,0 +1,56 @@ +// Type definitions for combined-stream 1.0 +// Project: https://github.com/felixge/node-combined-stream +// Definitions by: Felix Geisendörfer , Tomek Łaziuk +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Stream } from "stream"; + +declare class CombinedStream extends Stream implements CombinedStream.Options { + readonly writable: boolean; + readonly readable: boolean; + readonly dataSize: number; + maxDataSize: number; + pauseStreams: boolean; + append(stream: NodeJS.ReadableStream | NodeJS.WritableStream | Buffer | string): this; + write(data: any): void; + pause(): void; + resume(): void; + end(): void; + destroy(): void; + + // private properties + _released: boolean; + // @TODO it should be a type of Array<'delayed-stream' instance | Buffer | string> + _streams: Array; + _currentStream: Stream | Buffer | string | null; + _getNext(): void; + _pipeNext(): void; + _handleErrors(stream: NodeJS.EventEmitter): void; + _reset(): void; + _checkDataSize(): void; + _updateDataSize(): void; + _emitError(error: Error): void; + + // events + on(event: "close" | "end" | "resume" | "pause", cb: () => void): this; + on(event: "error", cb: (err: Error) => void): this; + on(event: "data", cb: (data: any) => void): this; + once(event: "close" | "end" | "resume" | "pause", cb: () => void): this; + once(event: "error", cb: (err: Error) => void): this; + once(event: "data", cb: (data: any) => void): this; +} + +declare namespace CombinedStream { + export interface Options { + maxDataSize?: number; + pauseStreams?: boolean; + } + + export function create(options?: Options): CombinedStream; + + export function isStreamLike(stream: any): stream is Stream; +} + +export = CombinedStream; diff --git a/combined-stream/tsconfig.json b/combined-stream/tsconfig.json new file mode 100644 index 0000000000..e1986a21be --- /dev/null +++ b/combined-stream/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "combined-stream-tests.ts" + ] +} diff --git a/combined-stream/tslint.json b/combined-stream/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/combined-stream/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/cucumber/cucumber-tests.ts b/cucumber/cucumber-tests.ts index 87089671ae..3eb86b223f 100644 --- a/cucumber/cucumber-tests.ts +++ b/cucumber/cucumber-tests.ts @@ -97,6 +97,24 @@ function StepSample() { } ) }); + cucumber.defineSupportCode(function(hook: cucumber.Hooks){ + hook.addTransform({ + captureGroupRegexps: ['red|blue|green'], + transformer: (arg: string) => arg, + typeName: 'color' + }); + }); + + cucumber.defineSupportCode(function({After, Given}) { + Given( /^a variable set to (\d+)$/, (x:string) => { + console.log("the number is: " + x); + }); + After((scenario: HookScenario, callback?: Callback) => { + console.log("After"); + callback(); + }); + }); + let fns : cucumber.SupportCodeConsumer[] = cucumber.getSupportCodeFns() cucumber.clearSupportCodeFns(); diff --git a/cucumber/index.d.ts b/cucumber/index.d.ts index a8b85539ce..99f31c5372 100644 --- a/cucumber/index.d.ts +++ b/cucumber/index.d.ts @@ -64,6 +64,12 @@ declare namespace cucumber { (scenario: HookScenario, runScenario?: (error:string, callback?:Function)=>void): void; } + interface Transform { + captureGroupRegexps: Array; + transformer: (arg: string) => any; + typeName: string; + } + export interface Hooks { Before(code: HookCode): void; After(code: HookCode): void; @@ -72,6 +78,7 @@ declare namespace cucumber { setWorldConstructor(world: () => void): void; registerHandler(handlerOption:string, code:(event:any, callback:CallbackStepDefinition) =>void): void; registerListener(listener: EventListener): void; + addTransform(transform: Transform): void; } export class EventListener { diff --git a/d3-geo/d3-geo-tests.ts b/d3-geo/d3-geo-tests.ts index 3d28bb610f..f1701c10c8 100644 --- a/d3-geo/d3-geo-tests.ts +++ b/d3-geo/d3-geo-tests.ts @@ -537,6 +537,19 @@ geoPathCentroid = geoPathCanvas.centroid(sampleExtendedFeatureCollection); // geoPathCentroid = geoPathSVG.centroid(sampleExtendedFeatureCollection); // fails, wrong data object type + +// measure(...) ------------------------------------------------------ + +let geoPathMeasure: number = geoPathCanvas.measure(samplePolygon); +geoPathMeasure = geoPathCanvas.measure(sampleSphere); +geoPathMeasure = geoPathCanvas.measure(sampleGeometryCollection); +geoPathMeasure = geoPathCanvas.measure(sampleExtendedGeometryCollection); +geoPathMeasure = geoPathCanvas.measure(sampleFeature); +geoPathMeasure = geoPathCanvas.measure(sampleExtendedFeature1); +geoPathMeasure = geoPathCanvas.measure(sampleExtendedFeature2); +geoPathMeasure = geoPathCanvas.measure(sampleFeatureCollection); +geoPathMeasure = geoPathCanvas.measure(sampleExtendedFeatureCollection); + // render path to context of get path string---------------------------- // render to GeoContext/Canvas diff --git a/d3-geo/index.d.ts b/d3-geo/index.d.ts index 9ab3ae74cd..02ce38ba93 100644 --- a/d3-geo/index.d.ts +++ b/d3-geo/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for D3JS d3-geo module v1.4.0 +// Type definitions for D3JS d3-geo module v1.5.0 // Project: https://github.com/d3/d3-geo/ // Definitions by: Hugues Stefanski , Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -908,7 +908,7 @@ export interface GeoPath { * this method first computes the area of the exterior ring, and then subtracts the area of any interior holes. * This method observes any clipping performed by the projection; see projection.clipAngle and projection.clipExtent. * - * @param An object for which the area is to be calculated. + * @param object An object for which the area is to be calculated. */ area(object: DatumObject): number; @@ -921,7 +921,7 @@ export interface GeoPath { * the minimum latitude is typically the maximum y-value, and the maximum latitude is typically the minimum y-value.) * This method observes any clipping performed by the projection; see projection.clipAngle and projection.clipExtent. * - * @param An object for which the bounds are to be calculated. + * @param object An object for which the bounds are to be calculated. */ bounds(object: DatumObject): [[number, number], [number, number]]; @@ -931,10 +931,20 @@ export interface GeoPath { * For example, a noncontiguous cartogram might scale each state around its centroid. * This method observes any clipping performed by the projection; see projection.clipAngle and projection.clipExtent. * - * @param An object for which the centroid is to be calculated. + * @param pbject An object for which the centroid is to be calculated. */ centroid(object: DatumObject): [number, number]; + /** + * Returns the projected planar length (typically in pixels) for the specified GeoJSON object. + * Point and MultiPoint features have zero length. For Polygon and MultiPolygon features, this method computes the summed length of all rings. + * + * This method observes any clipping performed by the projection. + * + * @param object An object for which the measure is to be calculated. + */ + measure(object: DatumObject): number; + /** * Returns the current render context which defaults to null. * diff --git a/d3/index.d.ts b/d3/index.d.ts index bf7fa8e6b6..d5fe886d63 100644 --- a/d3/index.d.ts +++ b/d3/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for D3JS d3 standard bundle 4.5 +// Type definitions for D3JS d3 standard bundle 4.6 // Project: https://github.com/d3/d3 // Definitions by: Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/dc/dc-tests.ts b/dc/dc-tests.ts index 9d2688fdf0..643594276d 100644 --- a/dc/dc-tests.ts +++ b/dc/dc-tests.ts @@ -180,6 +180,8 @@ d3.json("data/yelp_test_set_business.json", (yelp_data:IYelpData[]) => { .xAxis() .tickFormat((v: string) => v); + lineChart.legend(dc.legend().x(200).y(10).itemHeight(13).gap(5)); + rowChart .width(340) .height(850) diff --git a/dc/index.d.ts b/dc/index.d.ts index e7be4f86aa..9f9d7d3a57 100644 --- a/dc/index.d.ts +++ b/dc/index.d.ts @@ -111,14 +111,14 @@ declare namespace dc { } export interface Legend { - x: IGetSet; - y: IGetSet; - gap: IGetSet; - itemHeight: IGetSet; - horizontal: IGetSet; - legendWidth: IGetSet; - itemWidth: IGetSet; - autoItemWidth: IGetSet; + x: IGetSet; + y: IGetSet; + gap: IGetSet; + itemHeight: IGetSet; + horizontal: IGetSet; + legendWidth: IGetSet; + itemWidth: IGetSet; + autoItemWidth: IGetSet; render: () => void; } diff --git a/deep-equal/deep-equal-tests.ts b/deep-equal/deep-equal-tests.ts index 2f4f238a4f..ed23a35838 100644 --- a/deep-equal/deep-equal-tests.ts +++ b/deep-equal/deep-equal-tests.ts @@ -1,8 +1,11 @@ -import * as deepEqual from "deep-equal"; +import deepEqual = require("deep-equal"); -let isDeepEqual1: boolean = deepEqual({}, {}); -let isDeepEqual2: boolean = deepEqual({}, {}, { strict: true }); -let isDeepEqual3: boolean = deepEqual({}, {}, { strict: false }); +const isDeepEqual1: boolean = deepEqual({}, {}); +const isDeepEqual2: boolean = deepEqual({}, {}, { strict: true }); +const isDeepEqual3: boolean = deepEqual({}, {}, { strict: false }); +const isDeepEqual4: boolean = deepEqual(undefined, undefined); +const isDeepEqual5: boolean = deepEqual(3, false); +const isDeepEqual6: boolean = deepEqual("a-string", null); -console.log(isDeepEqual1, isDeepEqual2, isDeepEqual3); +console.log(isDeepEqual1, isDeepEqual2, isDeepEqual3, isDeepEqual4, isDeepEqual5, isDeepEqual6); diff --git a/deep-equal/index.d.ts b/deep-equal/index.d.ts index eef762a4ea..d9c4b5f6cf 100644 --- a/deep-equal/index.d.ts +++ b/deep-equal/index.d.ts @@ -1,17 +1,15 @@ -// Type definitions for deep-equal +// Type definitions for deep-equal 1.0 // Project: https://github.com/substack/node-deep-equal -// Definitions by: remojansen +// Definitions by: remojansen , Jay Anslow // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - - interface DeepEqualOptions { strict: boolean; } -declare let deepEqual: ( - actual: Object, - expected: Object, - opts?: DeepEqualOptions) => boolean; +declare function deepEqual( + actual: any, + expected: any, + opts?: DeepEqualOptions): boolean; export = deepEqual; diff --git a/deep-equal/tsconfig.json b/deep-equal/tsconfig.json index b192443e3f..6d21a4a7e6 100644 --- a/deep-equal/tsconfig.json +++ b/deep-equal/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/deep-equal/tslint.json b/deep-equal/tslint.json new file mode 100644 index 0000000000..f9e30021f4 --- /dev/null +++ b/deep-equal/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "../tslint.json" +} diff --git a/dockerode/index.d.ts b/dockerode/index.d.ts index c317d5d32e..968199436a 100644 --- a/dockerode/index.d.ts +++ b/dockerode/index.d.ts @@ -184,6 +184,7 @@ declare namespace Dockerode { Created: number; Ports: Port[]; Labels: { [label: string]: string }; + State: string; Status: string; HostConfig: { NetworkMode: string; diff --git a/elasticsearch/index.d.ts b/elasticsearch/index.d.ts index 84c8f281f9..a0606a4961 100644 --- a/elasticsearch/index.d.ts +++ b/elasticsearch/index.d.ts @@ -88,6 +88,7 @@ declare module Elasticsearch { export interface ConfigOptions { host?: any; hosts?: any; + httpAuth?: string; log?: any; apiVersion?: string; plugins?: any; diff --git a/express-serve-static-core/index.d.ts b/express-serve-static-core/index.d.ts index 42f1a535f7..a4ce9612e7 100644 --- a/express-serve-static-core/index.d.ts +++ b/express-serve-static-core/index.d.ts @@ -848,6 +848,8 @@ interface Response extends http.ServerResponse, Express.Response { * */ vary(field: string): Response; + + app: Application; } interface Handler extends RequestHandler { } diff --git a/extract-text-webpack-plugin/extract-text-webpack-plugin-tests.ts b/extract-text-webpack-plugin/extract-text-webpack-plugin-tests.ts index 63177ebde3..ca992ea3ef 100644 --- a/extract-text-webpack-plugin/extract-text-webpack-plugin-tests.ts +++ b/extract-text-webpack-plugin/extract-text-webpack-plugin-tests.ts @@ -22,18 +22,18 @@ configuration = { // Extract css files { test: /\.css$/, - loader: ExtractTextPlugin.extract({ - fallbackLoader: "style-loader", - loader: "css-loader", + use: ExtractTextPlugin.extract({ + fallback: "style-loader", + use: "css-loader", }) }, // Optionally extract less files // or any other compile-to-css language { test: /\.less$/, - loader: ExtractTextPlugin.extract({ - fallbackLoader: "style-loader", - loader: ["css-loader", "less-loader"], + use: ExtractTextPlugin.extract({ + fallback: "style-loader", + use: ["css-loader", "less-loader"], }) } // You could also use other loaders the same way. I. e. the autoprefixer-loader @@ -70,10 +70,13 @@ configuration = { // ... module: { rules: [ - { test: /\.css$/, loader: ExtractTextPlugin.extract({ - fallbackLoader: "style-loader", - loader: "css-loader" - }) } + { + test: /\.css$/, + use: ExtractTextPlugin.extract({ + fallback: "style-loader", + use: "css-loader" + }) + } ] }, plugins: [ @@ -89,8 +92,8 @@ configuration = { // ... module: { rules: [ - { test: /\.scss$/i, loader: extractCSS.extract(['css','sass']) }, - { test: /\.less$/i, loader: extractLESS.extract(['css','less']) }, + { test: /\.scss$/i, use: extractCSS.extract(['css','sass']) }, + { test: /\.less$/i, use: extractLESS.extract(['css','less']) }, ] }, plugins: [ diff --git a/extract-text-webpack-plugin/index.d.ts b/extract-text-webpack-plugin/index.d.ts index 21052b08c1..6da0c183c3 100644 --- a/extract-text-webpack-plugin/index.d.ts +++ b/extract-text-webpack-plugin/index.d.ts @@ -1,15 +1,15 @@ // Type definitions for extract-text-webpack-plugin 2.0.0 -// Project: https://github.com/webpack/extract-text-webpack-plugin -// Definitions by: flying-sheep +// Project: https://github.com/webpack-contrib/extract-text-webpack-plugin +// Definitions by: flying-sheep , kayo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import { Plugin, OldLoader } from 'webpack' +import { Plugin, OldLoader, NewLoader } from 'webpack' /** * extract-text-webpack-plugin has no support for .options instead of .query yet. * See https://github.com/webpack/extract-text-webpack-plugin/issues/281 */ -type Loader = string | OldLoader +type Loader = string | OldLoader | NewLoader interface ExtractPluginOptions { /** the filename of the result file. May contain `[name]`, `[id]` and `[contenthash]` */ @@ -24,9 +24,9 @@ interface ExtractPluginOptions { interface ExtractOptions { /** the loader(s) that should be used for converting the resource to a css exporting module */ - loader: Loader | Loader[] + use: Loader | Loader[] /** the loader(s) that should be used when the css is not extracted (i.e. in an additional chunk when `allChunks: false`) */ - fallbackLoader?: Loader | Loader[] + fallback?: Loader | Loader[] /** override the `publicPath` setting for this loader */ publicPath?: string } diff --git a/gettext.js/gettext.js-tests.ts b/gettext.js/gettext.js-tests.ts new file mode 100644 index 0000000000..6e5b4448ae --- /dev/null +++ b/gettext.js/gettext.js-tests.ts @@ -0,0 +1,21 @@ +import * as Gettext from 'gettext.js'; + +const json: Gettext.JsonData = { + "": { + "locale": "fr", + "plural-forms": "nplurals=2; plural=n>1;" + }, + "Welcome": "Bienvenue", + "There is %1 apple": [ + "Il y a %1 pomme", + "Il y a %1 pommes" + ] +}; + +const instance: Gettext.Gettext = Gettext.i18n(); + +instance.loadJSON(json, 'messages'); +instance.setLocale('fr'); +if (instance.ngettext('There is %1 apple', 'There are %1 apples', 0) === 'Il y a %1 pomme') { + throw new Error('Failed test'); +} diff --git a/gettext.js/index.d.ts b/gettext.js/index.d.ts new file mode 100644 index 0000000000..5096490721 --- /dev/null +++ b/gettext.js/index.d.ts @@ -0,0 +1,45 @@ +// Type definitions for gettext.js 0.5 +// Project: https://github.com/guillaumepotier/gettext.js +// Definitions by: Julien Crouzet +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export type PluralForm = (n: number) => number; + +export type GettextStatic = (options?: GettextOptions) => Gettext; + +export interface GettextOptions { + domain?: string; + locale?: string; + plural_func?: PluralForm; + ctxt_delimiter?: string; +} + +export interface JsonDataHeader { + locale: string; + "plural-forms": string; +} + +export interface JsonDataMessages { + [key: string]: string | string[] | JsonDataHeader; +} + +export interface JsonData extends JsonDataMessages { + "": JsonDataHeader; +} + +export interface Gettext { + setMessages: (domain: string, locale: string, messages: JsonDataMessages, plural_forms?: PluralForm) => Gettext; + loadJSON: (jsonData: JsonData, domain?: string) => Gettext; + setLocale: (locale: string) => Gettext; + getLocale: () => string; + textdomain: (domain?: string) => Gettext | string; + gettext: (msgid: string, ...args: any[]) => string; + ngettext: (msgid: string, msgid_plural: string, n: number, ...args: any[]) => string; + pgettext: (msgctxt: string, msgid: string, ...args: any[]) => string; + dcnpgettext: (domain: string, msgctxt: string, msgid: string, msgid_plural: string, n: number, ...args: any[]) => string; + __: (msgid: string, ...args: any[]) => string; + _n: (msgid: string, msgid_plural: string, n: number, ...args: any[]) => string; + _p: (msgctxt: string, msgid: string, ...args: any[]) => string; +} + +export const i18n: GettextStatic; diff --git a/gettext.js/tsconfig.json b/gettext.js/tsconfig.json new file mode 100644 index 0000000000..d01ec061ab --- /dev/null +++ b/gettext.js/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "gettext.js-tests.ts" + ] +} diff --git a/gettext.js/tslint.json b/gettext.js/tslint.json new file mode 100644 index 0000000000..2221e40e4a --- /dev/null +++ b/gettext.js/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } \ No newline at end of file diff --git a/gm/gm-tests.ts b/gm/gm-tests.ts index debd18ecff..2189d9064d 100644 --- a/gm/gm-tests.ts +++ b/gm/gm-tests.ts @@ -78,6 +78,7 @@ gm(src) .authenticate(password) .autoOrient() .backdrop() + .background(color) .bitdepth(bits) .blackThreshold(intensity) .blackThreshold(r, g, b) diff --git a/gm/index.d.ts b/gm/index.d.ts index 288ce150ce..7fd419ede3 100644 --- a/gm/index.d.ts +++ b/gm/index.d.ts @@ -108,6 +108,7 @@ declare namespace m { authenticate(password: string): State; autoOrient(): State; backdrop(): State; + background(color: string): State; bitdepth(bits: number): State; blackThreshold(intensity: number): State; blackThreshold(red: number, green: number, blue: number, opacity?: number): State; diff --git a/google-protobuf/google-protobuf-tests.ts b/google-protobuf/google-protobuf-tests.ts new file mode 100644 index 0000000000..796969b2b3 --- /dev/null +++ b/google-protobuf/google-protobuf-tests.ts @@ -0,0 +1,139 @@ +import * as jspb from "google-protobuf"; + +/* This is a typescript version of a simple generated class from a proto file that is shown below. In order to make + this ES5 JS file into TypeScript there have been quite a few modifications, but the same calls are made to the library + classes. + + // FILE: simple.proto + syntax = "proto3"; + + package examplecom; + + message MySimple { + string my_string = 1; + bool my_bool = 2; + repeated string some_labels = 3; + } +*/ + +class MySimple extends jspb.Message { + constructor(opt_data?: any) { + super(); // This isn't actually called in the JS version of this file, but it's required by TS + jspb.Message.initialize(this, opt_data, 0, -1, MySimple.repeatedFields_, null); + }; + + static repeatedFields_ = [3]; + + toObject(opt_includeInstance: boolean) { + return MySimple.toObject(opt_includeInstance, this); + }; + + static toObject(includeInstance: boolean, msg: MySimple) { + const obj = { + myString: jspb.Message.getFieldWithDefault(msg, 1, ""), + myBool: jspb.Message.getFieldWithDefault(msg, 2, false), + someLabelsList: jspb.Message.getField(msg, 3), + }; + + if (includeInstance) { + // This is commented out because it's not valid in TS, but it's a simple append to an object + // obj['$jspbMessageInstance'] = msg; + } + return obj; + }; + + static deserializeBinary(bytes: Uint8Array) { + const reader = new jspb.BinaryReader(bytes); + const msg = new MySimple(); + return MySimple.deserializeBinaryFromReader(msg, reader); + }; + + static deserializeBinaryFromReader(msg: MySimple, reader: jspb.BinaryReader) { + while (reader.nextField()) { + if (reader.isEndGroup()) { + break; + } + const field = reader.getFieldNumber(); + switch (field) { + case 1: + const value1 = (reader.readString()); + msg.setMyString(value1); + break; + case 2: + const value2 = (reader.readBool()); + msg.setMyBool(value2); + break; + case 3: + const value3 = (reader.readString()); + msg.addSomeLabels(value3); + break; + default: + reader.skipField(); + break; + } + } + return msg; + }; + + serializeBinary(): Uint8Array { + const writer = new jspb.BinaryWriter(); + MySimple.serializeBinaryToWriter(this, writer); + return writer.getResultBuffer(); + }; + + static serializeBinaryToWriter(message: MySimple, writer: jspb.BinaryWriter) { + let f1 = message.getMyString(); + if (f1.length > 0) { + writer.writeString( + 1, + f1, + ); + } + const f2 = message.getMyBool(); + if (f2) { + writer.writeBool( + 2, + f2, + ); + } + const f3 = message.getSomeLabelsList(); + if (f3.length > 0) { + writer.writeRepeatedString( + 3, + f3, + ); + } + } + + getMyString(): string { + return jspb.Message.getFieldWithDefault(this, 1, ""); + } + + setMyString(value: string) { + jspb.Message.setField(this, 1, value); + } + + getMyBool(): boolean { + return jspb.Message.getFieldWithDefault(this, 2, false); + } + + setMyBool(value: boolean) { + jspb.Message.setField(this, 2, value); + } + + getSomeLabelsList(): string[] { + return jspb.Message.getField(this, 3); + } + + setSomeLabelsList(value: string[]) { + jspb.Message.setField(this, 3, value || []); + } + + addSomeLabels(value: string, opt_index?: number) { + jspb.Message.addToRepeatedField(this, 3, value, opt_index); + } + + clearSomeLabelsList() { + this.setSomeLabelsList([]); + } +} diff --git a/google-protobuf/index.d.ts b/google-protobuf/index.d.ts new file mode 100644 index 0000000000..f40780ed8a --- /dev/null +++ b/google-protobuf/index.d.ts @@ -0,0 +1,675 @@ +// Type definitions for google-protobuf 3.2 +// Project: https://github.com/google/google-protobuf +// Definitions by: Marcus Longmuir +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +type ByteSource = ArrayBuffer|Uint8Array|number[]|string; +type ScalarFieldType = boolean|number|string; +type RepeatedFieldType = ScalarFieldType[] | Uint8Array[]; +type AnyFieldType = ScalarFieldType | RepeatedFieldType | Uint8Array; +type FieldValue = (string|number|boolean|Uint8Array|any/*This should be Array, but that isn't allowed*/|undefined) + +export class Message { + getJsPbMessageId(): (string | undefined); + static initialize(msg: Message, + data: Message.MessageArray, + messageId: (string | number), + suggestedPivot: number, + repeatedFields: number[], + oneofFields?: number[][] | null): void; + static toObjectList(field: T[], + toObjectFn: (includeInstance: boolean, + data: T) => {}, + includeInstance?: boolean): {}[]; + static toObjectExtension(msg: Message, + obj: {}, + extensions: {[key: number]: ExtensionFieldInfo}, + getExtensionFn: (fieldInfo: ExtensionFieldInfo) => Message, + includeInstance?: boolean): void; + serializeBinaryExtensions(proto: Message, + writer: BinaryWriter, + extensions: {[key: number]: ExtensionFieldBinaryInfo}, + getExtensionFn: (fieldInfo: ExtensionFieldInfo) => T): void + readBinaryExtension(proto: Message, + reader: BinaryReader, + extensions: {[key: number]: ExtensionFieldBinaryInfo}, + setExtensionFn: (fieldInfo: ExtensionFieldInfo, + val: T) => void): void + static getField(msg: Message, + fieldNumber: number): FieldValue|null; + static getOptionalFloatingPointField(msg: Message, + fieldNumber: number): (number | undefined); + static getRepeatedFloatingPointField(msg: Message, + fieldNumber: number): number[]; + static bytesAsB64(bytes: Uint8Array): string; + static bytesAsU8(str: string): Uint8Array; + static bytesListAsB64(bytesList: Uint8Array[]): string[]; + static bytesListAsU8(strList: string[]): Uint8Array[]; + static getFieldWithDefault(msg: Message, + fieldNumber: number, + defaultValue: T): T; + static getMapField(msg: Message, + fieldNumber: number, + noLazyCreate: boolean, + valueCtor: typeof Message): Map; + static setField(msg: Message, + fieldNumber: number, + value: FieldValue): void; + static addToRepeatedField(msg: Message, + fieldNumber: number, + value: any, + index?: number): void; + static setOneofField(msg: Message, + fieldNumber: number, + oneof: number[], + value: FieldValue): void; + static computeOneofCase(msg: Message, + oneof: number[]): number; + static getWrapperField(msg: Message, + ctor: typeof Message, + fieldNumber: number, + required?: number): Message; + static getRepeatedWrapperField(msg: Message, + ctor: typeof Message, + fieldNumber: number): Message[]; + static setWrapperField(msg: Message, + fieldNumber: number, + value?: (Message|Map)): void; + static setOneofWrapperField(msg: Message, + fieldNumber: number, + oneof: number[], + value: any): void; + static setRepeatedWrapperField(msg: Message, + fieldNumber: number, + value: any): void; + static addToRepeatedWrapperField(msg: Message, + fieldNumber: number, + value: any, + ctor: typeof Message, + index: number): any; + static toMap(field: any[], + mapKeyGetterFn: (field: any) => string, + toObjectFn?: Message.StaticToObject, + includeInstance?: boolean): void; + toArray(): Message.MessageArray; + toString(): string; + getExtension(fieldInfo: ExtensionFieldInfo): T; + setExtension(fieldInfo: ExtensionFieldInfo, + value: T): void; + static difference(m1: T, + m2: T): T; + static equals(m1: Message, + m2: Message): boolean; + static compareExtensions(extension1: {}, + extension2: {}): boolean; + static compareFields(field1: any, + field2: any): boolean; + cloneMessage(): Message; + clone(): Message; + static clone(msg: T): T; + static cloneMessage(msg: T): T; + static copyInto(fromMessage: Message, + toMessage: Message): void; + static registerMessageType(id: number, + constructor: typeof Message): void; +} + +export namespace Message { + export type MessageArray = any[]; // This type needs to reference itself + interface StaticToObject { + (includeInstance: boolean, + msg: Message): {}; + } +} + +export class ExtensionFieldInfo { + fieldIndex: number; + fieldName: number; + ctor: typeof Message; + toObjectFn: Message.StaticToObject; + isRepeated: number; + constructor(fieldIndex: number, + fieldName: {[key: string]: number}, + ctor: typeof Message, + toObjectFn: Message.StaticToObject, + isRepeated: number); + isMessageType(): boolean; +} + +export class ExtensionFieldBinaryInfo { + fieldInfo: ExtensionFieldInfo; + binaryReaderFn: BinaryRead; + binaryWriterFn: BinaryWrite; + opt_binaryMessageSerializeFn: (msg: Message, + writer: BinaryWriter) => void; + opt_binaryMessageDeserializeFn: (msg: Message, + reader: BinaryReader) => Message; + opt_isPacked: boolean; + constructor(fieldInfo: ExtensionFieldInfo, + binaryReaderFn: BinaryRead, + binaryWriterFn: BinaryWrite, + opt_binaryMessageSerializeFn: (msg: Message, + writer: BinaryWriter) => void, + opt_binaryMessageDeserializeFn: (msg: Message, + reader: BinaryReader) => Message, + opt_isPacked: boolean); +} + +export class Map { + constructor(arr: Array<[K, V]>, + valueCtor?: {new(init: any): V}); + toArray(): Array<[K, V]>; + toObject(includeInstance: boolean, + valueToObject: (includeInstance: boolean) => any): Array<[K, V]>; + static fromObject(entries: Array<[K, V]>, + valueCtor: any, + valueFromObject: any): Map; + getLength(): number; + clear(): void; + del(key: K): boolean; + getEntryList(): Array<[K, V]>; + entries(): Map.Iterator<[K, V]>; + keys(): Map.Iterator; + forEach(callback: (entry: V, + key: K) => void, + thisArg?: {}): void; + set(key: K, + value: V): void; + get(key: K): (V | undefined); + has(key: K): boolean; +} + +export namespace Map { + // This is implemented by jspb.Map.ArrayIteratorIterable_, but that class shouldn't be exported + interface Iterator { + next(): IteratorResult; + } + type IteratorResult = { + done: boolean, + value: T, + } +} + +interface BinaryReadReader { + (msg: any, + binaryReader: BinaryReader): void; +} + +interface BinaryRead { + (msg: any, + reader: BinaryReadReader): void; +} + +interface BinaryWriteCallback { + (value: any, + binaryWriter: BinaryWriter): void; +} + +interface BinaryWrite { + (fieldNumber: number, + value: any, + writerCallback: BinaryWriteCallback): void; +} + +export class BinaryReader { + constructor(bytes?: ByteSource, + start?: number, + length?: number); + static alloc(bytes?: ByteSource, + start?: number, + length?: number): BinaryReader; + alloc(bytes?: ByteSource, + start?: number, + length?: number): BinaryReader; + free(): void; + getFieldCursor(): number; + getCursor(): number; + getBuffer(): Uint8Array; + getFieldNumber(): number; + getWireType(): BinaryConstants.WireType; + isEndGroup(): boolean; + getError(): boolean; + setBlock(bytes?: ByteSource, + start?: number, + length?: number): void; + reset(): void; + advance(count: number): void; + nextField(): boolean; + unskipHeader(): void; + skipMatchingFields(): void; + skipVarintField(): void; + skipDelimitedField(): void; + skipFixed32Field(): void; + skipFixed64Field(): void; + skipGroup(): void; + skipField(): void; + registerReadCallback(callbackName: string, + callback: (binaryReader: BinaryReader) => any): void; + runReadCallback(callbackName: string): any; + readAny(fieldType: BinaryConstants.FieldType): AnyFieldType; + readMessage: BinaryRead; + readGroup(field: number, + message: Message, + reader: BinaryReadReader): void; + getFieldDecoder(): BinaryDecoder; + readInt32(): number; + readInt32String(): string; + readInt64(): number; + readInt64String(): string; + readUint32(): number; + readUint32String(): string; + readUint64(): number; + readUint64String(): string; + readSint32(): number; + readSint64(): number; + readSint64String(): string; + readFixed32(): number; + readFixed64(): number; + readFixed64String(): string; + readSfixed32(): number; + readSfixed32String(): string; + readSfixed64(): number; + readSfixed64String(): string; + readFloat(): number; + readDouble(): number; + readBool(): boolean; + readEnum(): number; + readString(): string; + readBytes(): Uint8Array; + readVarintHash64(): string; + readFixedHash64(): string; + readPackedInt32(): number[]; + readPackedInt32String(): string[]; + readPackedInt64(): number[]; + readPackedInt64String(): string[]; + readPackedUint32(): number[]; + readPackedUint32String(): string[]; + readPackedUint64(): number[]; + readPackedUint64String(): string[]; + readPackedSint32(): number[]; + readPackedSint64(): number[]; + readPackedSint64String(): string[]; + readPackedFixed32(): number[]; + readPackedFixed64(): number[]; + readPackedFixed64String(): string[]; + readPackedSfixed32(): number[]; + readPackedSfixed64(): number[]; + readPackedSfixed64String(): string[]; + readPackedFloat(): number[]; + readPackedDouble(): number[]; + readPackedBool(): boolean[]; + readPackedEnum(): number[]; + readPackedVarintHash64(): string[]; + readPackedFixedHash64(): string[]; +} + +export class BinaryWriter { + constructor(); + writeSerializedMessage(bytes: Uint8Array, + start: number, + end: number): void; + maybeWriteSerializedMessage(bytes?: Uint8Array, + start?: number, + end?: number): void; + reset(): void; + getResultBuffer(): Uint8Array; + getResultBase64String(): string; + beginSubMessage(field: number): void; + endSubMessage(field: number): void; + writeAny(fieldType: BinaryConstants.FieldType, + field: number, + value: AnyFieldType): void; + writeInt32(field: number, + value?: number): void; + writeInt32String(field: number, + value?: string): void; + writeInt64(field: number, + value?: number): void; + writeInt64String(field: number, + value?: string): void; + writeUint32(field: number, + value?: number): void; + writeUint32String(field: number, + value?: string): void; + writeUint64(field: number, + value?: number): void; + writeUint64String(field: number, + value?: string): void; + writeSint32(field: number, + value?: number): void; + writeSint64(field: number, + value?: number): void; + writeSint64String(field: number, + value?: string): void; + writeFixed32(field: number, + value?: number): void; + writeFixed64(field: number, + value?: number): void; + writeFixed64String(field: number, + value?: string): void; + writeSfixed32(field: number, + value?: number): void; + writeSfixed64(field: number, + value?: number): void; + writeSfixed64String(field: number, + value?: string): void; + writeFloat(field: number, + value?: number): void; + writeDouble(field: number, + value?: number): void; + writeBool(field: number, + value?: boolean): void; + writeEnum(field: number, + value?: number): void; + writeString(field: number, + value?: string): void; + writeBytes(field: number, + value?: ByteSource): void; + writeMessage: BinaryWrite; + writeGroup(field: number, + value: any, + writeCallback: BinaryWriteCallback): void; + writeFixedHash64(field: number, + value?: string): void; + writeVarintHash64(field: number, + value?: string): void; + writeRepeatedInt32(field: number, + value?: number[]): void; + writeRepeatedInt32String(field: number, + value?: string[]): void; + writeRepeatedInt64(field: number, + value?: number[]): void; + writeRepeatedInt64String(field: number, + value?: string[]): void; + writeRepeatedUint32(field: number, + value?: number[]): void; + writeRepeatedUint32String(field: number, + value?: string[]): void; + writeRepeatedUint64(field: number, + value?: number[]): void; + writeRepeatedUint64String(field: number, + value?: string[]): void; + writeRepeatedSint32(field: number, + value?: number[]): void; + writeRepeatedSint64(field: number, + value?: number[]): void; + writeRepeatedSint64String(field: number, + value?: string[]): void; + writeRepeatedFixed32(field: number, + value?: number[]): void; + writeRepeatedFixed64(field: number, + value?: number[]): void; + writeRepeatedFixed64String(field: number, + value?: string[]): void; + writeRepeatedSfixed32(field: number, + value?: number[]): void; + writeRepeatedSfixed64(field: number, + value?: number[]): void; + writeRepeatedSfixed64String(field: number, + value?: string[]): void; + writeRepeatedFloat(field: number, + value?: number[]): void; + writeRepeatedDouble(field: number, + value?: number[]): void; + writeRepeatedBool(field: number, + value?: boolean[]): void; + writeRepeatedEnum(field: number, + value?: number[]): void; + writeRepeatedString(field: number, + value?: string[]): void; + writeRepeatedBytes(field: number, + value?: ByteSource[]): void; + writeRepeatedMessage(field: number, + value: Message[], + writerCallback: BinaryWriteCallback): void; + writeRepeatedGroup(field: number, + value: Message[], + writerCallback: BinaryWriteCallback): void; + writeRepeatedFixedHash64(field: number, + value?: string[]): void; + writeRepeatedVarintHash64(field: number, + value?: string[]): void; + writePackedInt32(field: number, + value?: number[]): void; + writePackedInt32String(field: number, + value?: string[]): void; + writePackedInt64(field: number, + value?: number[]): void; + writePackedInt64String(field: number, + value?: string[]): void; + writePackedUint32(field: number, + value?: number[]): void; + writePackedUint32String(field: number, + value?: string[]): void; + writePackedUint64(field: number, + value?: number[]): void; + writePackedUint64String(field: number, + value?: string[]): void; + writePackedSint32(field: number, + value?: number[]): void; + writePackedSint64(field: number, + value?: number[]): void; + writePackedSint64String(field: number, + value?: string[]): void; + writePackedFixed32(field: number, + value?: number[]): void; + writePackedFixed64(field: number, + value?: number[]): void; + writePackedFixed64String(field: number, + value?: string[]): void; + writePackedSfixed32(field: number, + value?: number[]): void; + writePackedSfixed64(field: number, + value?: number[]): void; + writePackedSfixed64String(field: number, + value?: string[]): void; + writePackedFloat(field: number, + value?: number[]): void; + writePackedDouble(field: number, + value?: number[]): void; + writePackedBool(field: number, + value?: boolean[]): void; + writePackedEnum(field: number, + value?: number[]): void; + writePackedFixedHash64(field: number, + value?: string[]): void; + writePackedVarintHash64(field: number, + value?: string[]): void; +} + +export class BinaryEncoder { + constructor(); + length(): number; + end(): number[]; + writeSplitVarint64(lowBits: number, + highBits: number): void; + writeSplitFixed64(lowBits: number, + highBits: number): void; + writeUnsignedVarint32(value: number): void; + writeSignedVarint32(value: number): void; + writeUnsignedVarint64(value: number): void; + writeSignedVarint64(value: number): void; + writeZigzagVarint32(value: number): void; + writeZigzagVarint64(value: number): void; + writeZigzagVarint64String(value: string): void; + writeUint8(value: number): void; + writeUint16(value: number): void; + writeUint32(value: number): void; + writeUint64(value: number): void; + writeInt8(value: number): void; + writeInt16(value: number): void; + writeInt32(value: number): void; + writeInt64(value: number): void; + writeInt64String(value: string): void; + writeFloat(value: number): void; + writeDouble(value: number): void; + writeBool(value: boolean): void; + writeEnum(value: number): void; + writeBytes(bytes: Uint8Array): void; + writeVarintHash64(hash: string): void; + writeFixedHash64(hash: string): void; + writeString(value: string): number; +} + +export class BinaryDecoder { + constructor(bytes?: ByteSource, + start?: number, + length?: number) + static alloc(bytes?: ByteSource, + start?: number, + length?: number): BinaryDecoder; + free(): void; + clone(): BinaryDecoder; + clear(): void; + getBuffer(): Uint8Array; + setBlock(data: ByteSource, + start?: number, + length?: number): void; + getEnd(): number; + setEnd(end: number): void; + reset(): void; + getCursor(): number; + setCursor(cursor: number): void; + advance(count: number): void; + atEnd(): boolean; + pastEnd(): boolean; + getError(): boolean; + skipVarint(): void; + unskipVarint(value: number): void; + readUnsignedVarint32(): number; + readSignedVarint32(): number; + readUnsignedVarint32String(): number; + readSignedVarint32String(): number; + readZigzagVarint32(): number; + readUnsignedVarint64(): number; + readUnsignedVarint64String(): number; + readSignedVarint64(): number; + readSignedVarint64String(): number; + readZigzagVarint64(): number; + readZigzagVarint64String(): number; + readUint8(): number; + readUint16(): number; + readUint32(): number; + readUint64(): number; + readUint64String(): string; + readInt8(): number; + readInt16(): number; + readInt32(): number; + readInt64(): number; + readInt64String(): string; + readFloat(): number; + readDouble(): number; + readBool(): boolean; + readEnum(): number; + readString(length: number): string; + readStringWithLength(): string; + readBytes(length: number): Uint8Array; + readVarintHash64(): string; + readFixedHash64(): string; +} + +export class BinaryIterator { + constructor(decoder?: BinaryDecoder, + next?: () => number|boolean|string|null, + elements?: Array) + static alloc(decoder?: BinaryDecoder, + next?: () => number|boolean|string|null, + elements?: Array): BinaryIterator; + free(): void; + clear(): void; + get(): (ScalarFieldType | null); + atEnd(): boolean; + next(): (ScalarFieldType | null); +} + +export namespace BinaryConstants { + export enum FieldType { + INVALID = -1, + DOUBLE = 1, + FLOAT = 2, + INT64 = 3, + UINT64 = 4, + INT32 = 5, + FIXED64 = 6, + FIXED32 = 7, + BOOL = 8, + STRING = 9, + GROUP = 10, + MESSAGE = 11, + BYTES = 12, + UINT32 = 13, + ENUM = 14, + SFIXED32 = 15, + SFIXED64 = 16, + SINT32 = 17, + SINT64 = 18, + FHASH64 = 30, + VHASH64 = 31, + } + + export enum WireType { + INVALID = -1, + VARINT = 0, + FIXED64 = 1, + DELIMITED = 2, + START_GROUP = 3, + END_GROUP = 4, + FIXED32 = 5, + } + + const FieldTypeToWireType: (fieldType: FieldType) => WireType; + + const INVALID_FIELD_NUMBER: number; + const FLOAT32_EPS: number; + const FLOAT32_MIN: number; + const FLOAT32_MAX: number; + const FLOAT64_EPS: number; + const FLOAT64_MIN: number; + const FLOAT64_MAX: number; + const TWO_TO_20: number; + const TWO_TO_23: number; + const TWO_TO_31: number; + const TWO_TO_32: number; + const TWO_TO_52: number; + const TWO_TO_63: number; + const TWO_TO_64: number; + const ZERO_HASH: string; +} + +export namespace arith { + export class UInt64 { + lo: number; + hi: number; + constructor(lo: number, + hi: number); + cmp(other: UInt64): number; + rightShift(): UInt64; + leftShift(): UInt64; + msb(): boolean; + lsb(): boolean; + zero(): boolean; + add(other: UInt64): UInt64; + sub(other: UInt64): UInt64; + static mul32x32(a: number, + b: number): UInt64; + mul(a: number): UInt64; + div(divisor: number): [UInt64, UInt64]; + toString(): string; + static fromString(str: string): UInt64; + clone(): UInt64; + } + + export class Int64 { + lo: number; + hi: number; + constructor(lo: number, + hi: number); + add(other: Int64): Int64; + sub(other: Int64): Int64; + clone(): Int64; + toString(): string; + static fromString(str: string): Int64; + } +} + +// jspb.utils package excluded as it likely shouldn't be called by user code \ No newline at end of file diff --git a/google-protobuf/tsconfig.json b/google-protobuf/tsconfig.json new file mode 100644 index 0000000000..269fec20d9 --- /dev/null +++ b/google-protobuf/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "google-protobuf-tests.ts" + ] +} \ No newline at end of file diff --git a/google-protobuf/tslint.json b/google-protobuf/tslint.json new file mode 100644 index 0000000000..fdc7cdc370 --- /dev/null +++ b/google-protobuf/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "../tslint.json" +} \ No newline at end of file diff --git a/google.analytics/google.analytics-tests.ts b/google.analytics/google.analytics-tests.ts index 6b7962899b..32df930cc9 100644 --- a/google.analytics/google.analytics-tests.ts +++ b/google.analytics/google.analytics-tests.ts @@ -1,5 +1,5 @@ - -/// +declare function describe(desc: string, fn: () => void): void; +declare function it(desc: string, fn: () => void): void; describe("tester Google Analytics Tracker _gat object", () => { it("can set ga script element", () => { diff --git a/griddle-react/griddle-react-tests.tsx b/griddle-react/griddle-react-tests.tsx new file mode 100644 index 0000000000..5f241feeb5 --- /dev/null +++ b/griddle-react/griddle-react-tests.tsx @@ -0,0 +1,78 @@ +/* +Licensed under the MIT License (MIT) + +Copyright (c) 2016 David Hara +*/ + +import * as React from 'react'; +import { render } from 'react-dom'; +import Griddle, { CustomColumnComponentProps } from 'griddle-react'; +import CustomColumnComponentGrid from './test/CustomColumnComponent'; +import CustomHeaderComponentGrid from './test/CustomHeaderComponent'; +import CustomFilterComponentGrid from './test/CustomFilterComponent'; + +interface MyCustomResult { + name: string, + test: string +} + +class LinkComponent extends React.Component, any> { + render() { + var url = "speakers/" + this.props.rowData.test + "/" + this.props.data; + return {this.props.data} + } +} + +const StatelessFunctionComponent = (props: CustomColumnComponentProps) => { + var url = "speakers/" + props.rowData.test + "/" + props.data; + return {props.data} +}; + +var columnMeta = [ + { + columnName: "name", + order: 1, + locked: false, + visible: true, + customComponent: StatelessFunctionComponent + }]; + +var results: MyCustomResult[] = [ + { + name: 'David Hara', + test: 'blah' + }, + { + name: 'Hara, David', + test: 'blah2' + } +]; + +var rowMetaData = { + bodyCssClassName: (rowData: MyCustomResult) => { + return rowData.test; + } +}; + +type TypedGriddle = new () => Griddle; +const TypedGriddle = Griddle as TypedGriddle; + +render( +
+

Custom Column Component Grid

+ +

Custom Header Component Grid

+ +

Custom Filter Component Grid

+ + } + sortDescendingComponent={} + customRowComponent={LinkComponent} + /> +
, + document.getElementById('root') +); diff --git a/griddle-react/index.d.ts b/griddle-react/index.d.ts new file mode 100644 index 0000000000..e5d3e560bb --- /dev/null +++ b/griddle-react/index.d.ts @@ -0,0 +1,170 @@ +// Type definitions for griddle-react 0.7 +// Project: https://github.com/griddlegriddle/griddle +// Definitions by: David Hara +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/* +The MIT License (MIT) + +Copyright (c) 2016 David Hara + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +import * as React from 'react'; + +type ReactClass = React.ComponentClass | React.StatelessComponent + +export interface CustomColumnComponentProps { + data: any; + rowData: T; + metaData: ColumnMetaData; +} + +export interface CustomRowComponentProps { + data: T; +} + +export interface CustomGridComponentProps { + data: T[]; +} + +export interface CustomPagerComponentProps { + currentPage: number; + maxPage: number; + nextText: string; + previousText: string; + next(): void; + previous(): void; + setPage(number: number): void; +} + +export interface CustomHeaderComponentProps { + filterByColumn?(filter: string, columnName: string): void; + columnName: string; + displayName: string; +} + +export interface CustomFilterComponentProps { + placeholderText?: string; + changeFilter(val: any): void; +} + +export interface ColumnMetaData { + columnName: string; + cssClassName?: string; + customComponent?: ReactClass>; + customHeaderComponent?: ReactClass; + customHeaderComponentProps?: {}; + displayName?: string; + locked?: boolean; + order?: number; + sortable?: boolean; + visible?: boolean; +} + +export interface BodyCssClassNameFunction { + (rowData: T): string; +} + +export interface RowMetaData { + bodyCssClassName?: BodyCssClassNameFunction | string; +} + +export interface GriddleProps { + columns?: string[]; + columnMetadata?: ColumnMetaData[]; + rowMetadata?: RowMetaData; + results?: T[]; + resultsPerPage?: number; + initialSort?: string; + initialSortAscending?: boolean; + gridClassName?: string; + tableClassName?: string; + customFormatClassName?: string; + settingsText?: string; + filterPlaceholderText?: string; + nextText?: string; + previousText?: string; + maxRowsText?: string; + enableCustomFormatText?: string; + childrenColumnName?: string; + metadataColumns?: string[]; + showFilter?: boolean; + showSettings?: boolean; + useCustomRowComponent?: boolean; + useCustomGridComponent?: boolean; + useCustomPagerComponent?: boolean; + useCustomFilterer?: boolean; + useCustomFilterComponent?: boolean; + useGriddleStyles?: boolean; + customRowComponent?: ReactClass> + customGridComponent?: ReactClass> + customPagerComponent?: ReactClass + customFilterComponent?: ReactClass + customFilterer?(items: T[], query: any): T[]; + enableToggleCustom?: boolean; + noDataMessage?: string; + noDataClassName?: string; + customNoDataComponent?: ReactClass + showTableHeading?: boolean; + showPager?: boolean; + useFixedHeader?: boolean; + useExternal?: boolean; + externalSetPage?(index: number): void; + externalChangeSort?(sort: string, sortAscending: boolean): void; + externalSetFilter?(filter: string): void; + externalSetPageSize?(size: number): void; + externalMaxPage?: number; + externalCurrentPage?: number; + externalSortColumn?: string; + externalSortAscending?: boolean; + externalLoadingComponent?: ReactClass + externalIsLoading?: boolean; + enableInfiniteScroll?: boolean; + bodyHeight?: number; + paddingHeight?: number; + rowHeight?: number; + infiniteScrollLoadTreshold?: number; + useFixedLayout?: boolean; + isSubGriddle?: boolean; + enableSort?: boolean; + sortAscendingClassName?: string; + sortDescendingClassName?: string; + parentRowCollapsedClassName?: string; + parentRowExpandedClassName?: string; + settingsToggleClassName?: string; + nextClassName?: string; + previousClassName?: string; + sortAscendingComponent?: string | React.ReactElement; + sortDescendingComponent?: string | React.ReactElement; + sortDefaultComponent?: string | React.ReactElement; + parentRowCollapsedComponent?: string | React.ReactElement; + parentRowExpandedComponent?: string | React.ReactElement; + settingsIconComponent?: string | React.ReactElement; + nextIconComponent?: string | React.ReactElement; + previousIconComponent?: string | React.ReactElement; + onRowClick?(): void; +} + +declare class Griddle extends React.Component, any> { +} + +export default Griddle; diff --git a/griddle-react/test/CustomColumnComponent.tsx b/griddle-react/test/CustomColumnComponent.tsx new file mode 100644 index 0000000000..83adc8f05a --- /dev/null +++ b/griddle-react/test/CustomColumnComponent.tsx @@ -0,0 +1,70 @@ +/* +Licensed under the MIT License (MIT) + +Copyright (c) 2016 David Hara +*/ + +import * as React from 'react'; +import Griddle, { CustomColumnComponentProps } from 'griddle-react'; + +interface MyCustomResult { + name: string, + test: string +} + +class LinkComponent extends React.Component, any> { + render() { + var url = "speakers/" + this.props.rowData.test + "/" + this.props.data; + return {this.props.data} + } +} + +const StatelessFunctionComponent = (props: CustomColumnComponentProps) => { + var url = "speakers/" + props.rowData.test + "/" + props.data; + return {props.data} +}; + +var columnMeta = [ + { + columnName: "name", + order: 1, + locked: false, + visible: true, + customComponent: StatelessFunctionComponent + }]; + +var results: MyCustomResult[] = [ + { + name: 'David Hara', + test: 'blah' + }, + { + name: 'Hara, David', + test: 'blah2' + } +]; + +var rowMetaData = { + bodyCssClassName: (rowData: MyCustomResult) => { + return rowData.test; + } +}; + +class CustomColumnComponentGrid extends React.Component { + render() { + type TypedGriddle = new () => Griddle; + const TypedGriddle = Griddle as TypedGriddle; + + return ( + } + sortDescendingComponent={} + customRowComponent={LinkComponent} /> + ); + }; +} + +export default CustomColumnComponentGrid; \ No newline at end of file diff --git a/griddle-react/test/CustomFilterComponent.tsx b/griddle-react/test/CustomFilterComponent.tsx new file mode 100644 index 0000000000..e7508887f5 --- /dev/null +++ b/griddle-react/test/CustomFilterComponent.tsx @@ -0,0 +1,91 @@ +/* +Licensed under the MIT License (MIT) + +Copyright (c) 2016 David Hara +*/ + +import * as _ from 'lodash'; +import * as React from 'react'; +import Griddle, { CustomFilterComponentProps } from 'griddle-react'; + +const CustomFilterFunction = (items: ResultType[], query: string): ResultType[] => { + return _.filter(items, (item) => { + + let match = false; + _.forIn(item, (value, key) => { + if (String(value).toLowerCase().indexOf(query.toLowerCase()) >= 0) { + match = true; + return; + } + }); + + return match; + }); +}; + +class CustomFilterComponent extends React.Component { + query: string = ''; + + searchChange(event: React.FormEvent) { + this.query = event.currentTarget.value; + this.props.changeFilter(this.query); + } + + render() { + return ( +
+ +
+ ); + } +} + +interface ResultType { + id: number; + name: string; + city: string; + state: string; + country: string; + company: string; + favoriteNumber: number; +} + +var someData: ResultType[] = [ + { + "id": 0, + "name": "Mayer Leonard", + "city": "Kapowsin", + "state": "Hawaii", + "country": "United Kingdom", + "company": "Ovolo", + "favoriteNumber": 7 + }, + { + "id": 1, + "name": "Koch Becker", + "city": "Johnsonburg", + "state": "New Jersey", + "country": "Madagascar", + "company": "Eventage", + "favoriteNumber": 2 + } +]; + +class CustomFilterComponentGrid extends React.Component { + render() { + + type TypedGriddle = new () => Griddle; + const TypedGriddle = Griddle as TypedGriddle; + + return ( + + ); + } +} + +export default CustomFilterComponentGrid; diff --git a/griddle-react/test/CustomHeaderComponent.tsx b/griddle-react/test/CustomHeaderComponent.tsx new file mode 100644 index 0000000000..aed7d348aa --- /dev/null +++ b/griddle-react/test/CustomHeaderComponent.tsx @@ -0,0 +1,95 @@ +/* +Licensed under the MIT License (MIT) + +Copyright (c) 2016 David Hara +*/ + +import * as React from 'react'; +import Griddle, { ColumnMetaData, CustomHeaderComponentProps } from 'griddle-react'; + +interface MoreCustomHeaderComponentProps extends CustomHeaderComponentProps { + color: string; +} + +class HeaderComponent extends React.Component { + textOnClick(e: React.FormEvent) { + e.stopPropagation(); + } + + filterText(e: React.FormEvent) { + this.props.filterByColumn(e.currentTarget.value, this.props.columnName) + } + + render() { + return ( + +
{this.props.displayName}
+ +
+ ); + } +} + +interface ResultType { + id: number; + name: string; + city: string; + state: string; + country: string; + company: string; + favoriteNumber: number; +} + +var someData: ResultType[] = [ + { + "id": 0, + "name": "Mayer Leonard", + "city": "Kapowsin", + "state": "Hawaii", + "country": "United Kingdom", + "company": "Ovolo", + "favoriteNumber": 7 + }, + { + "id": 1, + "name": "Koch Becker", + "city": "Johnsonburg", + "state": "New Jersey", + "country": "Madagascar", + "company": "Eventage", + "favoriteNumber": 2 + } +]; + +var columnMeta: ColumnMetaData[] = [ + { + columnName: 'name', + order: 1, + sortable: false, + visible: true, + }, + { + columnName: 'city', + customHeaderComponent: HeaderComponent, + customHeaderComponentProps: {color: 'red'} + }, + { + columnName: 'state', + customHeaderComponent: HeaderComponent, + customHeaderComponentProps: {color: 'blue'} + } +]; + +class CustomHeaderComponentGrid extends React.Component { + render() { + + type TypedGriddle = new () => Griddle; + const TypedGriddle = Griddle as TypedGriddle; + + return ( + + ); + } +} + +export default CustomHeaderComponentGrid; diff --git a/griddle-react/tsconfig.json b/griddle-react/tsconfig.json new file mode 100644 index 0000000000..5dd6f9d98b --- /dev/null +++ b/griddle-react/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "jsx": "preserve", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "griddle-react-tests.tsx", + "test/CustomColumnComponent.tsx", + "test/CustomFilterComponent.tsx", + "test/CustomHeaderComponent.tsx" + ] +} diff --git a/griddle-react/tslint.json b/griddle-react/tslint.json new file mode 100644 index 0000000000..f9e30021f4 --- /dev/null +++ b/griddle-react/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "../tslint.json" +} diff --git a/isbn-utils/index.d.ts b/isbn-utils/index.d.ts new file mode 100644 index 0000000000..fe2ac4dae9 --- /dev/null +++ b/isbn-utils/index.d.ts @@ -0,0 +1,35 @@ +// Type definitions for isbn-utils 1.1 +// Project: https://github.com/GitbookIO/isbn-utils +// Definitions by: Jørgen Elgaard Larsen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +type IGroups = any; + +export class ISBNcodes { + readonly source: string; + readonly prefix: string; + readonly group: string; + readonly publisher: string; + readonly article: string; + readonly check: string; + readonly check10: string; + readonly check13: string; + readonly groupname: string; +} + +export class ISBN { + constructor(val: string, groups: IGroups); + asIsbn10(hyphenate?: boolean): string; + asIsbn13(hyphenate?: boolean): string; + codes: ISBNcodes; + isIsbn10(): boolean; + isIsbn13(): boolean; + isValid(): boolean; +} + +export function asIsbn10(isbn: string, hyphenate?: boolean): string; +export function asIsbn13(isbn: string, hyphenate?: boolean): string; +export function parse(isbn: string, groups?: IGroups): ISBN|null; +export function hyphenate(isbn: string): string; +export function isValid(isbn: string, groups?: IGroups): boolean; diff --git a/isbn-utils/isbn-utils-tests.ts b/isbn-utils/isbn-utils-tests.ts new file mode 100644 index 0000000000..91f72a0359 --- /dev/null +++ b/isbn-utils/isbn-utils-tests.ts @@ -0,0 +1,36 @@ +import * as isbn from 'isbn-utils'; + + +const isbn10a: isbn.ISBN|null = isbn.parse('4873113369'); +let b: boolean; +let s: string; + +if (isbn10a !== null) { + b = isbn10a.isIsbn10(); + b = isbn10a.isIsbn13(); + s = isbn10a.asIsbn10(); + s = isbn10a.asIsbn10(true); + s = isbn10a.asIsbn13(); + s = isbn10a.asIsbn13(true); + s = isbn10a.codes.source; + s = isbn10a.codes.prefix; + s = isbn10a.codes.group; + s = isbn10a.codes.publisher; + s = isbn10a.codes.article; + s = isbn10a.codes.check; + s = isbn10a.codes.check10; + s = isbn10a.codes.check13; + s = isbn10a.codes.groupname; +} + +const bad: isbn.ISBN|null = isbn.parse('invalid format'); +if (bad === null) { + s = 'Bummer.'; +} + +s = isbn.asIsbn13('4-87311-336-9'); +s = isbn.asIsbn13('4-87311-336-9', true); +s = isbn.asIsbn10('978-4-87311-336-4'); +s = isbn.asIsbn10('978-4-87311-336-4', true); + +s = isbn.hyphenate('9784873113364'); diff --git a/isbn-utils/tsconfig.json b/isbn-utils/tsconfig.json new file mode 100644 index 0000000000..b061bf6192 --- /dev/null +++ b/isbn-utils/tsconfig.json @@ -0,0 +1,23 @@ +{ + "files": [ + "index.d.ts", + "isbn-utils-tests.ts" + ], + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + } +} diff --git a/isbn-utils/tslint.json b/isbn-utils/tslint.json new file mode 100644 index 0000000000..f9e30021f4 --- /dev/null +++ b/isbn-utils/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "../tslint.json" +} diff --git a/jasmine-data_driven_tests/index.d.ts b/jasmine-data_driven_tests/index.d.ts index a2a7415093..827539a3a9 100644 --- a/jasmine-data_driven_tests/index.d.ts +++ b/jasmine-data_driven_tests/index.d.ts @@ -2,6 +2,38 @@ // Project: https://github.com/gburghardt/jasmine-data_driven_tests // Definitions by: Anthony MacKinnon // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 -declare function all(description: string, dataset: any[], assertion: (...args: any[]) => void): void; -declare function xall(description: string, dataset: any[], assertion: (...args: any[]) => void): void; \ No newline at end of file +declare var all: JasmineDataDrivenTest; +declare var xall: JasmineDataDrivenTest; + +interface JasmineDataDrivenTest { + ( + description: string, + dataset: Array<[T, U, V, W, X, Y, Z]>, + assertion: (arg0: T, arg1: U, arg2: V, arg3: W, arg4: X, arg5: Y, arg6: Z, done: () => void) => void): void; + ( + description: string, + dataset: Array<[T, U, V, W, X, Y]>, + assertion: (arg0: T, arg1: U, arg2: V, arg3: W, arg4: X, arg5: Y, done: () => void) => void): void; + ( + description: string, + dataset: Array<[T, U, V, W, X]>, + assertion: (arg0: T, arg1: U, arg2: V, arg3: W, arg4: X, done: () => void) => void): void; + ( + description: string, + dataset: Array<[T, U, V, W]>, + assertion: (arg0: T, arg1: U, arg2: V, arg3: W, done: () => void) => void): void; + ( + description: string, + dataset: Array<[T, U, V]>, + assertion: (arg0: T, arg1: U, arg2: V, done: () => void) => void): void; + ( + description: string, + dataset: Array<[T, U]>, + assertion: (arg0: T, arg1: U, done: () => void) => void): void; + ( + description: string, + dataset: T[], + assertion: (value: T, done: () => void) => void): void; +} diff --git a/jasmine-data_driven_tests/jasmine-data_driven_tests-tests.ts b/jasmine-data_driven_tests/jasmine-data_driven_tests-tests.ts index 27509d7383..727c253ad3 100644 --- a/jasmine-data_driven_tests/jasmine-data_driven_tests-tests.ts +++ b/jasmine-data_driven_tests/jasmine-data_driven_tests-tests.ts @@ -1,9 +1,8 @@ - /// all("A data driven test is a suite with multiple specs", ['a', 'b', 'c'], - (value: string) => { + value => { expect(value).not.toBe('d'); } ); @@ -13,7 +12,7 @@ all("A data driven test can have many arguments", [1, 2, 3], [2, 4, 6] ], - (a: number, b: number, c: number) => { + (a, b, c) => { expect(c - (a + b)).toBe(0); } ); @@ -23,7 +22,7 @@ all("A data driven test can be asynchronous", [3, 1], [5, 2] ], - (a: number, b: number, done: () => void) => { + (a, b, done) => { setTimeout(() => { expect(a - b > 0).toBe(true); done(); @@ -33,7 +32,7 @@ all("A data driven test can be asynchronous", xall("A data driven test can be pending", [1, 2, 3], - (value: number) => { + value => { expect(value < 4).toBe(true); } ); @@ -47,7 +46,7 @@ describe("A suite", () => { all("can contain data driven tests", [1, 2, 3], - (b: number) => { + b => { expect(a - b > 0).toBe(true); } ); diff --git a/jasmine-fixture/index.d.ts b/jasmine-fixture/index.d.ts index 8ea5956f1e..9a8c7b98b2 100644 --- a/jasmine-fixture/index.d.ts +++ b/jasmine-fixture/index.d.ts @@ -2,10 +2,14 @@ // Project: https://github.com/searls/jasmine-fixture // Definitions by: Craig Brett // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 -/** Affixes the given jquery selectors into the body and will be removed after each spec -* @param {string} selector The JQuery selector to be added to the dom -*/ +/// + +/** + * Affixes the given jquery selectors into the body and will be removed after each spec + * @param {string} selector The JQuery selector to be added to the dom + */ declare function affix(selector: string): JQuery; interface JQuery { diff --git a/jasmine-fixture/jasmine-fixture-tests.ts b/jasmine-fixture/jasmine-fixture-tests.ts index b0ec42d512..74eb750590 100644 --- a/jasmine-fixture/jasmine-fixture-tests.ts +++ b/jasmine-fixture/jasmine-fixture-tests.ts @@ -1,8 +1,6 @@ -/// /// /// - describe("Jasmine fixture extension", () => { describe("Affixes dom elements to body", () => { it("Inserts a new element on affix", () => { diff --git a/jimp/jimp-tests.ts b/jimp/jimp-tests.ts index 180ce27d7f..fd1ed1d2b7 100644 --- a/jimp/jimp-tests.ts +++ b/jimp/jimp-tests.ts @@ -1,7 +1,7 @@ import Jimp = require('jimp') // All code below is from node-jimp document -Jimp.read("lenna.png", function (err, data) { +Jimp.read("lenna.png", (err, data) => { if (err) throw err; data.resize(256, 256) // resize .quality(60) // set JPEG quality @@ -9,30 +9,30 @@ Jimp.read("lenna.png", function (err, data) { .write("lena-small-bw.jpg"); // save }); -Jimp.read("lenna.png").then(function (lenna) { +Jimp.read("lenna.png").then(lenna => { lenna.resize(256, 256) // resize .quality(60) // set JPEG quality .greyscale() // set greyscale .write("lena-small-bw.jpg"); // save -}).catch(function (err) { +}).catch(err => { console.error(err); }); -Jimp.read("./path/to/image.jpg", function (err, image) { +Jimp.read("./path/to/image.jpg", (err, image) => { // do stuff with the image (if no exception) }); -Jimp.read("./path/to/image.jpg").then(function (image) { +Jimp.read("./path/to/image.jpg").then(image => { // do stuff with the image -}).catch(function (err) { +}).catch(err => { // handle an exception }); -Jimp.read(new Buffer(''), function (err, image) { +Jimp.read(new Buffer(''), (err, image) => { // do stuff with the image (if no exception) }); -Jimp.read("http://www.example.com/path/to/lenna.jpg", function (err, image) { +Jimp.read("http://www.example.com/path/to/lenna.jpg", (err, image) => { // do stuff with the image (if no exception) }); @@ -51,51 +51,55 @@ var hex = 0xFFFFFFFF var r = 0 var n = 1 /* Resize */ -image.contain( w, h); // scale the image to the given width and height, some parts of the image may be letter boxed -image.cover( w, h); // scale the image to the given width and height, some parts of the image may be clipped -image.resize( w, h); // resize the image. Jimp.AUTO can be passed as one of the values. -image.scale(f ); // scale the image by the factor f -image.scaleToFit( w, h ); // scale the image to the largest size that fits inside the given width and height +image.contain(w, h); // scale the image to the given width and height, some parts of the image may be letter boxed +image.cover(w, h); // scale the image to the given width and height, some parts of the image may be clipped +image.resize(w, h); // resize the image. Jimp.AUTO can be passed as one of the values. +image.scale(f); // scale the image by the factor f +image.scaleToFit(w, h); // scale the image to the largest size that fits inside the given width and height // An optional resize mode can be passed with all resize methods. /* Crop */ image.autocrop(); // automatically crop same-color borders from image (if any) -image.crop( x, y, w, h ); // crop to the given region +image.crop(x, y, w, h); // crop to the given region /* Composing */ -image.blit( src, x, y ); +image.blit(src, x, y); // blit the image with another Jimp image at x, y, optionally cropped. -image.composite( src, x, y ); // composites another Jimp image over this image at x, y -image.mask( src, x, y ); // masks the image with another Jimp image at x, y using average pixel value +image.composite(src, x, y); // composites another Jimp image over this image at x, y +image.mask(src, x, y); // masks the image with another Jimp image at x, y using average pixel value /* Flip and rotate */ -image.flip( horz, vert ); // flip the image horizontally or vertically -image.mirror( horz, vert ); // an alias for flip -image.rotate( deg ); // rotate the image clockwise by a number of degrees. Optionally, a resize mode can be passed. If `false` is passed as the second parameter, the image width and height will not be resized. +image.flip(horz, vert); // flip the image horizontally or vertically +image.mirror(horz, vert); // an alias for flip +// rotate the image clockwise by a number of degrees. +// Optionally, a resize mode can be passed. +// If `false` is passed as the second parameter, +// the image width and height will not be resized. +image.rotate(deg); // JPEG images with EXIF orientation data will be automatically re-orientated as appropriate. /* Colour */ -image.brightness( val ); // adjust the brighness by a value -1 to +1 -image.contrast( val ); // adjust the contrast by a value -1 to +1 +image.brightness(val); // adjust the brighness by a value -1 to +1 +image.contrast(val); // adjust the contrast by a value -1 to +1 image.dither565(); // ordered dithering of the image and reduce color space to 16-bits (RGB565) image.greyscale(); // remove colour from the image image.invert(); // invert the image colours image.normalize(); // normalize the channels in an image /* Alpha channel */ -image.fade( f ); // an alternative to opacity, fades the image by a factor 0 - 1. 0 will haven no effect. 1 will turn the image -image.opacity( f ); // multiply the alpha channel by each pixel by the factor f, 0 - 1 +image.fade(f); // an alternative to opacity, fades the image by a factor 0 - 1. 0 will haven no effect. 1 will turn the image +image.opacity(f); // multiply the alpha channel by each pixel by the factor f, 0 - 1 image.opaque(); // set the alpha channel on every pixel to fully opaque -image.background( hex ); // set the default new pixel colour (e.g. 0xFFFFFFFF or 0x00000000) for by some operations (e.g. image.contain and +image.background(hex); // set the default new pixel colour (e.g. 0xFFFFFFFF or 0x00000000) for by some operations (e.g. image.contain and /* Blurs */ -image.gaussian( r ); // Gaussian blur the image by r pixels (VERY slow) -image.blur( r ); // fast blur the image by r pixels +image.gaussian(r); // Gaussian blur the image by r pixels (VERY slow) +image.blur(r); // fast blur the image by r pixels /* Effects */ -image.posterize( n ); // apply a posterization effect with n level +image.posterize(n); // apply a posterization effect with n level image.sepia(); // apply a sepia wash to the image image.clone(); // returns a clone of the image @@ -110,35 +114,35 @@ image.contain(250, 250, Jimp.HORIZONTAL_ALIGN_LEFT | Jimp.VERTICAL_ALIGN_TOP); var path = '' var str = '' var width = 0 -Jimp.loadFont( path ).then(function (font) { // load font from .fnt file +Jimp.loadFont(path).then(font => { // load font from .fnt file image.print(font, x, y, str); // print a message on an image image.print(font, x, y, str, width); // print a message on an image with text wrapped at width }); var cb = (err: Error, data: any) => {} -Jimp.loadFont( path, cb ); // using a callback pattern +Jimp.loadFont(path, cb); // using a callback pattern -Jimp.loadFont(Jimp.FONT_SANS_32_BLACK).then(function (font) { +Jimp.loadFont(Jimp.FONT_SANS_32_BLACK).then(font => { image.print(font, 10, 10, "Hello world!"); }); -image.write( path, cb ); // Node-style callback will be fired when write is successful +image.write(path, cb); // Node-style callback will be fired when write is successful var file = "new_name." + image.getExtension(); image.write(file) var mime = 'image/png' -image.getBuffer( mime, cb ); // Node-style callback will be fired with result -image.getBase64( mime, cb ); // Node-style callback will be fired with result -image.quality( n ); // set the quality of saved JPEG, 0 - 100 +image.getBuffer(mime, cb); // Node-style callback will be fired with result +image.getBase64(mime, cb); // Node-style callback will be fired with result +image.quality(n); // set the quality of saved JPEG, 0 - 100 var bool = true var number = 0 -image.rgba( bool ); // set whether PNGs are saved as RGBA (true, default) or RGB (false) -image.filterType( number ); // set the filter type for the saved PNG -image.deflateLevel( number ); // set the deflate level for the saved PNG -Jimp.deflateStrategy( number ); // set the deflate for the saved PNG (0-3) +image.rgba(bool); // set whether PNGs are saved as RGBA (true, default) or RGB (false) +image.filterType(number); // set the filter type for the saved PNG +image.deflateLevel(number); // set the deflate level for the saved PNG +Jimp.deflateStrategy(number); // set the deflate for the saved PNG (0-3) image.color([ { apply: 'hue', params: [ -90 ] }, @@ -146,11 +150,11 @@ image.color([ { apply: 'xor', params: [ '#06D' ] } ]); image.convolution([ - [-2,-1, 0], + [-2, -1, 0], [-1, 1, 1], [ 0, 1, 2] ]) -image.scan(0, 0, image.bitmap.width, image.bitmap.height, function (x, y, idx) { +image.scan(0, 0, image.bitmap.width, image.bitmap.height, function(x, y, idx) { // x, y is the position of this pixel on the image // idx is the position start position of this rgba tuple in the bitmap Buffer // this is the image @@ -172,11 +176,11 @@ var a = 0 Jimp.rgbaToInt(r, g, b, a); // e.g. converts 255, 255, 255, 255 to 0xFFFFFFFF Jimp.intToRGBA(hex); // e.g. converts 0xFFFFFFFF to {r: 255, g: 255, b: 255, a:255} -var image = new Jimp(256, 256, function (err, image) { +var image = new Jimp(256, 256, (err, image) => { // this image is 256 x 256, every pixel is set to 0x00000000 }); -var image = new Jimp(256, 256, 0xFF0000FF, function (err, image) { +var image = new Jimp(256, 256, 0xFF0000FF, (err, image) => { // this image is 256 x 256, every pixel is set to 0xFF0000FF }); @@ -202,13 +206,13 @@ if (distance < 0.15 || diff.percent < 0.15) { // not a match } -Jimp.read("lenna.png", function (err, image) { +Jimp.read("lenna.png", function(err, image) { this.greyscale().scale(0.5).write("lena-half-bw.png"); }); -Jimp.read("lenna.png", function (err, image) { - image.greyscale(function(err, image) { - image.scale(0.5, function (err, image) { +Jimp.read("lenna.png", (err, image) => { + image.greyscale((err, image) => { + image.scale(0.5, (err, image) => { image.write("lena-half-bw.png"); }); }); diff --git a/joi/index.d.ts b/joi/index.d.ts index 55e6b9c75f..fe1f0e39f8 100644 --- a/joi/index.d.ts +++ b/joi/index.d.ts @@ -91,6 +91,12 @@ export interface IpOptions { cidr?: string; } +export type GuidVersions = 'uuidv1' | 'uuidv2' | 'uuidv3' | 'uuidv4' | 'uuidv5' + +export interface GuidOptions { + version: GuidVersions[] | GuidVersions +} + export interface UriOptions { /** * Specifies one or more acceptable Schemes, should only include the scheme name. @@ -443,7 +449,7 @@ export interface StringSchema extends AnySchema { /** * Requires the string value to be a valid GUID. */ - guid(): StringSchema; + guid(options?: GuidOptions): StringSchema; /** * Requires the string value to be a valid hexadecimal string. diff --git a/joi/joi-tests.ts b/joi/joi-tests.ts index 59eb446b2f..3a222ff832 100644 --- a/joi/joi-tests.ts +++ b/joi/joi-tests.ts @@ -691,6 +691,8 @@ strSchema = strSchema.ip(ipOpts); strSchema = strSchema.uri(); strSchema = strSchema.uri(uriOpts); strSchema = strSchema.guid(); +strSchema = strSchema.guid({version: ['uuidv1', 'uuidv2', 'uuidv3', 'uuidv4', 'uuidv5']}); +strSchema = strSchema.guid({version: 'uuidv4'}); strSchema = strSchema.hex(); strSchema = strSchema.hostname(); strSchema = strSchema.isoDate(); diff --git a/jointjs/index.d.ts b/jointjs/index.d.ts index c8ef9ae302..95e2b2b7e3 100644 --- a/jointjs/index.d.ts +++ b/jointjs/index.d.ts @@ -156,6 +156,15 @@ declare namespace joint { findView(paper: Paper): ElementView; isElement(): boolean; scale(scaleX: number, scaleY: number, origin?: Point, options?: any): this; + addPort(port: any, opt?: any): this; + addPorts(ports: any[], opt?: any): this; + removePort(port: any, opt?: any): this; + hasPorts(): boolean; + hasPort(id: string): boolean; + getPorts(): any[]; + getPort(id: string): any; + getPortIndex(port: any): number; + portProp(portId: string, path: any, value?: any, opt?: any): joint.dia.Element; } interface CSSSelector { @@ -511,6 +520,7 @@ declare namespace joint { polyline?: ShapeAttrs; } class Polyline extends Generic { + constructor(attributes?: GenericAttributes, options?: Object); } class Image extends Generic { constructor(attributes?: GenericAttributes, options?: Object); @@ -539,28 +549,40 @@ declare namespace joint { namespace chess { class KingWhite extends basic.Generic { + constructor(attributes?: GenericAttributes, options?: Object); } class KingBlack extends basic.Generic { + constructor(attributes?: GenericAttributes, options?: Object); } class QueenWhite extends basic.Generic { + constructor(attributes?: GenericAttributes, options?: Object); } class QueenBlack extends basic.Generic { + constructor(attributes?: GenericAttributes, options?: Object); } class RookWhite extends basic.Generic { + constructor(attributes?: GenericAttributes, options?: Object); } class RookBlack extends basic.Generic { + constructor(attributes?: GenericAttributes, options?: Object); } class BishopWhite extends basic.Generic { + constructor(attributes?: GenericAttributes, options?: Object); } class BishopBlack extends basic.Generic { + constructor(attributes?: GenericAttributes, options?: Object); } class KnightWhite extends basic.Generic { + constructor(attributes?: GenericAttributes, options?: Object); } class KnightBlack extends basic.Generic { + constructor(attributes?: GenericAttributes, options?: Object); } class PawnWhite extends basic.Generic { + constructor(attributes?: GenericAttributes, options?: Object); } class PawnBlack extends basic.Generic { + constructor(attributes?: GenericAttributes, options?: Object); } } @@ -582,23 +604,28 @@ declare namespace joint { removeInPort(port: string, opt?: any): this; } class Coupled extends Model { + constructor(attributes?: ModelAttributes, options?: Object); } class Atomic extends Model { + constructor(attributes?: ModelAttributes, options?: Object); } class Link extends dia.Link { + constructor(attributes?: dia.LinkAttributes, options?: Object); } } namespace erd { class Entity extends basic.Generic { - constructor(attributes?: GenericAttributes, options?: Object); + constructor(attributes?: GenericAttributes, options?: Object); } class WeakEntity extends Entity { + constructor(attributes?: GenericAttributes, options?: Object); } class Relationship extends dia.Element { constructor(attributes?: GenericAttributes, options?: Object); } class IdentifyingRelationship extends Relationship { + constructor(attributes?: GenericAttributes, options?: Object); } interface AttributeAttrs extends dia.TextAttrs { ellipse?: ShapeAttrs; @@ -607,12 +634,16 @@ declare namespace joint { constructor(attributes?: GenericAttributes, options?: Object); } class Multivalued extends Attribute { + constructor(attributes?: GenericAttributes, options?: Object); } class Derived extends Attribute { + constructor(attributes?: GenericAttributes, options?: Object); } class Key extends Attribute { + constructor(attributes?: GenericAttributes, options?: Object); } class Normal extends Attribute { + constructor(attributes?: GenericAttributes, options?: Object); } interface ISAAttrs extends dia.Element { polygon?: ShapeAttrs; @@ -621,19 +652,23 @@ declare namespace joint { constructor(attributes?: GenericAttributes, options?: Object); } class Line extends dia.Link { + constructor(attributes?: dia.LinkAttributes, options?: Object); cardinality(value: string | number): void; } } namespace fsa { class State extends basic.Circle { + constructor(attributes?: GenericAttributes, options?: Object); } class StartState extends dia.Element { constructor(attributes?: GenericAttributes, options?: Object); } class EndState extends dia.Element { + constructor(attributes?: GenericAttributes, options?: Object); } class Arrow extends dia.Link { + constructor(attributes?: dia.LinkAttributes, options?: Object); } } @@ -655,14 +690,19 @@ declare namespace joint { constructor(attributes?: GenericAttributes, options?: Object); } class IO extends Gate { + constructor(attributes?: GenericAttributes, options?: Object); } class Input extends IO { + constructor(attributes?: GenericAttributes, options?: Object); } class Output extends IO { + constructor(attributes?: GenericAttributes, options?: Object); } class Gate11 extends Gate { + constructor(attributes?: GenericAttributes, options?: Object); } class Gate21 extends Gate { + constructor(attributes?: GenericAttributes, options?: Object); } interface Image { 'xlink:href'?: string; @@ -720,11 +760,13 @@ declare namespace joint { constructor(attributes?: GenericAttributes, options?: Object); } class Arrow extends dia.Link { + constructor(attributes?: dia.LinkAttributes, options?: Object); } } namespace pn { class Place extends basic.Generic { + constructor(attributes?: GenericAttributes, options?: Object); } class PlaceView extends dia.ElementView { renderTokens(): void; @@ -733,6 +775,7 @@ declare namespace joint { constructor(attributes?: GenericAttributes, options?: Object); } class Link extends dia.Link { + constructor(attributes?: dia.LinkAttributes, options?: Object); } } @@ -750,36 +793,49 @@ declare namespace joint { class ClassView extends dia.ElementView { } class Abstract extends Class { + constructor(attributes?: ClassAttributes, options?: Object); } class AbstractView extends ClassView { + constructor(attributes?: ClassAttributes, options?: Object); } class Interface extends Class { + constructor(attributes?: ClassAttributes, options?: Object); } class InterfaceView extends ClassView { + constructor(attributes?: ClassAttributes, options?: Object); } class Generalization extends dia.Link { + constructor(attributes?: dia.LinkAttributes, options?: Object); } class Implementation extends dia.Link { + constructor(attributes?: dia.LinkAttributes, options?: Object); } class Aggregation extends dia.Link { + constructor(attributes?: dia.LinkAttributes, options?: Object); } class Composition extends dia.Link { + constructor(attributes?: dia.LinkAttributes, options?: Object); } class Association extends dia.Link { + constructor(attributes?: dia.LinkAttributes, options?: Object); } interface StateAttributes extends GenericAttributes { events?: string[]; } class State extends basic.Generic { + constructor(attributes?: GenericAttributes, options?: Object); updateName(): void; updateEvents(): void; updatePath(): void; } class StartState extends basic.Circle { + constructor(attributes?: GenericAttributes, options?: Object); } class EndState extends basic.Generic { + constructor(attributes?: GenericAttributes, options?: Object); } class Transition extends dia.Link { + constructor(attributes?: dia.LinkAttributes, options?: Object); } } } @@ -833,7 +889,7 @@ declare namespace joint { setLinkVertices?: (link: dia.Link, vertices: Position[]) => void; } - class DirectedGraph { + export class DirectedGraph { static layout(graph: dia.Graph | dia.Cell[], options?: LayoutOptions): dia.BBox; } } diff --git a/js-quantities/js-quantities-tests.ts b/js-quantities/js-quantities-tests.ts index 95819381b5..ed69816dc3 100644 --- a/js-quantities/js-quantities-tests.ts +++ b/js-quantities/js-quantities-tests.ts @@ -1,6 +1,21 @@ -/// import Qty from "js-quantities"; +declare function describe(desc: string, fn: () => void): void; +declare function it(desc: string, fn: () => void): void; +interface Expect { + not: this; + toBe(y: T): void; + toEqual(y: T): void; + toBeTruthy(): void; + toBeNull(): void; + toBeCloseTo(this: Expect, x: number, sigFigs: number): void; + toThrow(this: Expect<() => void>, msg?: string): void; + toContain(this: Expect, x: U): void; +}; +declare function expect(x: T): Expect; +declare function beforeEach(f: () => void): void; +declare function afterEach(f: () => void): void; + // From project readme let qty: Qty; diff --git a/kendo-ui/index.d.ts b/kendo-ui/index.d.ts index ecdbffae66..86f9624227 100644 --- a/kendo-ui/index.d.ts +++ b/kendo-ui/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Kendo UI Professional v2016.3.1029 +// Type definitions for Kendo UI Professional v2017.1.118 // Project: http://www.telerik.com/kendo-ui // Definitions by: Telerik // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -678,8 +678,8 @@ declare namespace kendo.data { static fields: DataSourceSchemaModelFields; id: any; - predecessorId: any; - successorId: any; + predecessorId: number; + successorId: number; type: number; static define(options: DataSourceSchemaModelWithFieldsObject): typeof GanttDependency; @@ -1135,7 +1135,7 @@ declare namespace kendo.data { interface DataSourceFilters extends DataSourceFilter { logic?: string; - filters?: DataSourceFilter[]; + filters?: DataSourceFilter[]; } interface DataSourceGroupItemAggregate { @@ -1656,6 +1656,7 @@ declare namespace kendo.ui { interface AutoCompleteOptions { name?: string; animation?: boolean|AutoCompleteAnimation; + autoWidth?: boolean; dataSource?: any|any|kendo.data.DataSource; clearButton?: boolean; dataTextField?: string; @@ -1790,6 +1791,7 @@ declare namespace kendo.ui { interface CalendarMonth { content?: string; + weekNumber?: string; empty?: string; } @@ -1804,6 +1806,7 @@ declare namespace kendo.ui { max?: Date; min?: Date; month?: CalendarMonth; + weekNumber?: boolean; start?: string; value?: Date; change?(e: CalendarEvent): void; @@ -1898,6 +1901,7 @@ declare namespace kendo.ui { interface ColorPickerOptions { name?: string; buttons?: boolean; + clearButton?: boolean; columns?: number; tileSize?: ColorPickerTileSize; messages?: ColorPickerMessages; @@ -2000,6 +2004,7 @@ declare namespace kendo.ui { name?: string; animation?: ComboBoxAnimation; autoBind?: boolean; + autoWidth?: boolean; cascadeFrom?: string; cascadeFromField?: string; clearButton?: boolean; @@ -2022,6 +2027,7 @@ declare namespace kendo.ui { placeholder?: string; popup?: ComboBoxPopup; suggest?: boolean; + syncValueAndText?: boolean; headerTemplate?: string|Function; template?: string|Function; text?: string; @@ -2159,6 +2165,7 @@ declare namespace kendo.ui { name?: string; alignToAnchor?: boolean; animation?: boolean|ContextMenuAnimation; + appendTo?: string|JQuery; closeOnClick?: boolean; dataSource?: any|any; direction?: string; @@ -2263,6 +2270,7 @@ declare namespace kendo.ui { interface DatePickerMonth { content?: string; + weekNumber?: string; empty?: string; } @@ -2279,6 +2287,7 @@ declare namespace kendo.ui { max?: Date; min?: Date; month?: DatePickerMonth; + weekNumber?: boolean; parseFormats?: any; start?: string; value?: Date; @@ -2353,6 +2362,7 @@ declare namespace kendo.ui { interface DateTimePickerMonth { content?: string; + weekNumber?: string; empty?: string; } @@ -2370,6 +2380,7 @@ declare namespace kendo.ui { max?: Date; min?: Date; month?: DateTimePickerMonth; + weekNumber?: boolean; parseFormats?: any; start?: string; timeFormat?: string; @@ -2558,6 +2569,7 @@ declare namespace kendo.ui { name?: string; animation?: boolean|DropDownListAnimation; autoBind?: boolean; + autoWidth?: boolean; cascadeFrom?: string; cascadeFromField?: string; dataSource?: any|any|kendo.data.DataSource; @@ -2986,6 +2998,7 @@ declare namespace kendo.ui { tooltip?: string; exec?: Function; items?: EditorToolItem[]; + palette?: string|any; template?: string; } @@ -3065,6 +3078,9 @@ declare namespace kendo.ui { clear?: string; filter?: string; info?: string; + additionalValue?: string; + additionalOperator?: string; + logic?: string; isFalse?: string; isTrue?: string; or?: string; @@ -3625,6 +3641,7 @@ declare namespace kendo.ui { } interface GridColumnCommandItem { + visible?: Function; name?: string; text?: GridColumnCommandItemText; className?: string; @@ -3659,6 +3676,7 @@ declare namespace kendo.ui { interface GridColumnSortable { compare?: Function; + initialDirection?: string; } interface GridColumn { @@ -3666,6 +3684,7 @@ declare namespace kendo.ui { attributes?: any; columns?: any; command?: GridColumnCommandItem[]; + editable?: Function; encoded?: boolean; field?: string; filterable?: boolean|GridColumnFilterable; @@ -3680,6 +3699,7 @@ declare namespace kendo.ui { hidden?: boolean; locked?: boolean; lockable?: boolean; + minResizableWidth?: number; minScreenWidth?: number; sortable?: boolean|GridColumnSortable; template?: string|Function; @@ -3779,8 +3799,8 @@ declare namespace kendo.ui { interface GridFilterable { extra?: boolean; messages?: GridFilterableMessages; - operators?: GridFilterableOperators; mode?: string; + operators?: GridFilterableOperators; } interface GridGroupableMessages { @@ -3873,6 +3893,7 @@ declare namespace kendo.ui { interface GridSortable { allowUnsort?: boolean; + initialDirection?: string; mode?: string; } @@ -4428,6 +4449,7 @@ declare namespace kendo.ui { animation?: boolean|MultiSelectAnimation; autoBind?: boolean; autoClose?: boolean; + autoWidth?: boolean; clearButton?: boolean; dataSource?: any|any|kendo.data.DataSource; dataTextField?: string; @@ -4797,15 +4819,30 @@ declare namespace kendo.ui { expand?: PanelBarAnimationExpand; } + interface PanelBarMessages { + loading?: string; + requestFailed?: string; + retry?: string; + } + interface PanelBarOptions { name?: string; animation?: boolean|PanelBarAnimation; + autoBind?: boolean; contentUrls?: any; - dataSource?: any|any; + dataImageUrlField?: string; + dataSource?: any|any|kendo.data.HierarchicalDataSource; + dataSpriteCssClassField?: string; + dataTextField?: string|any; + dataUrlField?: string; expandMode?: string; + loadOnDemand?: boolean; + messages?: PanelBarMessages; + template?: string|Function; activate?(e: PanelBarActivateEvent): void; collapse?(e: PanelBarCollapseEvent): void; contentLoad?(e: PanelBarContentLoadEvent): void; + dataBound?(e: PanelBarDataBoundEvent): void; error?(e: PanelBarErrorEvent): void; expand?(e: PanelBarExpandEvent): void; select?(e: PanelBarSelectEvent): void; @@ -4829,6 +4866,10 @@ declare namespace kendo.ui { contentElement?: Element; } + interface PanelBarDataBoundEvent extends PanelBarEvent { + node?: JQuery; + } + interface PanelBarErrorEvent extends PanelBarEvent { xhr?: JQueryXHR; status?: string; @@ -5629,6 +5670,7 @@ declare namespace kendo.ui { eventTemplate?: string|Function; footer?: boolean|SchedulerFooter; group?: SchedulerGroup; + groupHeaderTemplate?: string|Function; height?: number|string; majorTick?: number; majorTimeHeaderTemplate?: string|Function; @@ -5647,7 +5689,6 @@ declare namespace kendo.ui { timezone?: string; toolbar?: SchedulerToolbarItem[]; views?: SchedulerView[]; - groupHeaderTemplate?: string|Function; width?: number|string; workDayStart?: Date; workDayEnd?: Date; @@ -6021,6 +6062,9 @@ declare namespace kendo.ui { activeSheet(): kendo.spreadsheet.Sheet; activeSheet(sheet?: kendo.spreadsheet.Sheet): void; + cellContextMenu(): kendo.ui.ContextMenu; + rowHeaderContextMenu(): kendo.ui.ContextMenu; + colHeaderContextMenu(): kendo.ui.ContextMenu; sheets(): any; fromFile(blob: Blob): JQueryPromise; fromFile(blob: File): JQueryPromise; @@ -6040,6 +6084,17 @@ declare namespace kendo.ui { } + interface SpreadsheetDefaultCellStyle { + background?: string; + color?: string; + fontFamily?: string; + fontSize?: string; + Italic?: boolean; + bold?: boolean; + underline?: boolean; + wrap?: boolean; + } + interface SpreadsheetExcel { fileName?: string; forceProxy?: boolean; @@ -6209,6 +6264,7 @@ declare namespace kendo.ui { activeSheet?: string; columnWidth?: number; columns?: number; + defaultCellStyle?: SpreadsheetDefaultCellStyle; headerHeight?: number; headerWidth?: number; excel?: SpreadsheetExcel; @@ -6218,6 +6274,20 @@ declare namespace kendo.ui { sheets?: SpreadsheetSheet[]; sheetsbar?: boolean; toolbar?: boolean|SpreadsheetToolbar; + insertSheet?(e: SpreadsheetInsertSheetEvent): void; + removeSheet?(e: SpreadsheetRemoveSheetEvent): void; + renameSheet?(e: SpreadsheetRenameSheetEvent): void; + selectSheet?(e: SpreadsheetSelectSheetEvent): void; + unhideColumn?(e: SpreadsheetUnhideColumnEvent): void; + unhideRow?(e: SpreadsheetUnhideRowEvent): void; + hideColumn?(e: SpreadsheetHideColumnEvent): void; + hideRow?(e: SpreadsheetHideRowEvent): void; + deleteColumn?(e: SpreadsheetDeleteColumnEvent): void; + deleteRow?(e: SpreadsheetDeleteRowEvent): void; + insertColumn?(e: SpreadsheetInsertColumnEvent): void; + insertRow?(e: SpreadsheetInsertRowEvent): void; + select?(e: SpreadsheetSelectEvent): void; + changeFormat?(e: SpreadsheetChangeFormatEvent): void; change?(e: SpreadsheetChangeEvent): void; render?(e: SpreadsheetRenderEvent): void; excelExport?(e: SpreadsheetExcelExportEvent): void; @@ -6230,6 +6300,70 @@ declare namespace kendo.ui { isDefaultPrevented(): boolean; } + interface SpreadsheetInsertSheetEvent extends SpreadsheetEvent { + } + + interface SpreadsheetRemoveSheetEvent extends SpreadsheetEvent { + sheet?: kendo.spreadsheet.Sheet; + } + + interface SpreadsheetRenameSheetEvent extends SpreadsheetEvent { + sheet?: kendo.spreadsheet.Sheet; + newSheetName?: string; + } + + interface SpreadsheetSelectSheetEvent extends SpreadsheetEvent { + sheet?: kendo.spreadsheet.Sheet; + } + + interface SpreadsheetUnhideColumnEvent extends SpreadsheetEvent { + sheet?: kendo.spreadsheet.Sheet; + index?: number; + } + + interface SpreadsheetUnhideRowEvent extends SpreadsheetEvent { + sheet?: kendo.spreadsheet.Sheet; + index?: number; + } + + interface SpreadsheetHideColumnEvent extends SpreadsheetEvent { + sheet?: kendo.spreadsheet.Sheet; + index?: number; + } + + interface SpreadsheetHideRowEvent extends SpreadsheetEvent { + sheet?: kendo.spreadsheet.Sheet; + index?: number; + } + + interface SpreadsheetDeleteColumnEvent extends SpreadsheetEvent { + sheet?: kendo.spreadsheet.Sheet; + index?: number; + } + + interface SpreadsheetDeleteRowEvent extends SpreadsheetEvent { + sheet?: kendo.spreadsheet.Sheet; + index?: number; + } + + interface SpreadsheetInsertColumnEvent extends SpreadsheetEvent { + sheet?: kendo.spreadsheet.Sheet; + index?: number; + } + + interface SpreadsheetInsertRowEvent extends SpreadsheetEvent { + sheet?: kendo.spreadsheet.Sheet; + index?: number; + } + + interface SpreadsheetSelectEvent extends SpreadsheetEvent { + range?: kendo.spreadsheet.Range; + } + + interface SpreadsheetChangeFormatEvent extends SpreadsheetEvent { + range?: kendo.spreadsheet.Range; + } + interface SpreadsheetChangeEvent extends SpreadsheetEvent { range?: kendo.spreadsheet.Range; } @@ -6616,6 +6750,7 @@ declare namespace kendo.ui { options: TooltipOptions; + popup: kendo.ui.Popup; element: JQuery; wrapper: JQuery; @@ -6774,6 +6909,7 @@ declare namespace kendo.ui { interface TouchSwipeEvent extends TouchEvent { touch?: kendo.mobile.ui.TouchEventOptions; event?: JQueryEventObject; + direction?: string; } interface TouchGesturestartEvent extends TouchEvent { @@ -6873,6 +7009,7 @@ declare namespace kendo.ui { interface TreeListColumnCommandItem { className?: string; + imageClass?: string; click?: Function; name?: string; text?: string; @@ -7344,15 +7481,16 @@ declare namespace kendo.ui { clearAllFiles(): void; - clearFile(): void; + clearFile(callback: Function): void; clearFileByUid(uid: string): void; destroy(): void; disable(): void; enable(enable?: boolean): void; + focus(): void; getFiles(): any; removeAllFiles(): void; - removeFile(): void; - removeFileByUid(): void; + removeFile(callback: Function): void; + removeFileByUid(uid: string): void; toggle(enable: boolean): void; upload(): void; @@ -7412,6 +7550,7 @@ declare namespace kendo.ui { template?: string|Function; validation?: UploadValidation; cancel?(e: UploadCancelEvent): void; + clear?(e: UploadClearEvent): void; complete?(e: UploadEvent): void; error?(e: UploadErrorEvent): void; progress?(e: UploadProgressEvent): void; @@ -7427,39 +7566,43 @@ declare namespace kendo.ui { } interface UploadCancelEvent extends UploadEvent { - files?: UploadFile[]; + files?: any[]; + } + + interface UploadClearEvent extends UploadEvent { + e?: any; } interface UploadErrorEvent extends UploadEvent { - files?: UploadFile[]; + files?: any[]; operation?: string; XMLHttpRequest?: any; } interface UploadProgressEvent extends UploadEvent { - files?: UploadFile[]; + files?: any[]; percentComplete?: number; } interface UploadRemoveEvent extends UploadEvent { - files?: UploadFile[]; + files?: any[]; data?: any; } interface UploadSelectEvent extends UploadEvent { e?: any; - files?: UploadFile[]; + files?: any[]; } interface UploadSuccessEvent extends UploadEvent { - files?: UploadFile[]; + files?: any[]; operation?: string; response?: any; XMLHttpRequest?: any; } interface UploadUploadEvent extends UploadEvent { - files?: UploadFile[]; + files?: any[]; data?: any; formData?: any; XMLHttpRequest?: any; @@ -7496,6 +7639,7 @@ declare namespace kendo.ui { rules?: any; validateOnBlur?: boolean; validate?(e: ValidatorValidateEvent): void; + validateInput?(e: ValidatorValidateInputEvent): void; } interface ValidatorEvent { sender: Validator; @@ -7507,6 +7651,11 @@ declare namespace kendo.ui { valid?: boolean; } + interface ValidatorValidateInputEvent extends ValidatorEvent { + input?: JQuery; + valid?: boolean; + } + class Window extends kendo.ui.Widget { @@ -7629,6 +7778,274 @@ declare namespace kendo.ui { } +} +declare namespace kendo.geometry { + class Arc extends Observable { + + + options: ArcOptions; + + anticlockwise: boolean; + center: kendo.geometry.Point; + endAngle: number; + radiusX: number; + radiusY: number; + startAngle: number; + + constructor(center: any|kendo.geometry.Point, options?: ArcOptions); + + + bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; + getAnticlockwise(): boolean; + getCenter(): kendo.geometry.Point; + getEndAngle(): number; + getRadiusX(): number; + getRadiusY(): number; + getStartAngle(): number; + pointAt(angle: number): kendo.geometry.Point; + setAnticlockwise(value: boolean): kendo.geometry.Arc; + setCenter(value: kendo.geometry.Point): kendo.geometry.Arc; + setEndAngle(value: number): kendo.geometry.Arc; + setRadiusX(value: number): kendo.geometry.Arc; + setRadiusY(value: number): kendo.geometry.Arc; + setStartAngle(value: number): kendo.geometry.Arc; + + } + + interface ArcOptions { + name?: string; + } + interface ArcEvent { + sender: Arc; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + + class Circle extends Observable { + + + options: CircleOptions; + + center: kendo.geometry.Point; + radius: number; + + constructor(center: any|kendo.geometry.Point, radius: number); + + + bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; + clone(): kendo.geometry.Circle; + equals(other: kendo.geometry.Circle): boolean; + getCenter(): kendo.geometry.Point; + getRadius(): number; + pointAt(angle: number): kendo.geometry.Point; + setCenter(value: kendo.geometry.Point): kendo.geometry.Point; + setCenter(value: any): kendo.geometry.Point; + setRadius(value: number): kendo.geometry.Circle; + + } + + interface CircleOptions { + name?: string; + } + interface CircleEvent { + sender: Circle; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + + class Matrix extends Observable { + + + options: MatrixOptions; + + a: number; + b: number; + c: number; + d: number; + e: number; + f: number; + + + static rotate(angle: number, x: number, y: number): kendo.geometry.Matrix; + static scale(scaleX: number, scaleY: number): kendo.geometry.Matrix; + static translate(x: number, y: number): kendo.geometry.Matrix; + static unit(): kendo.geometry.Matrix; + + clone(): kendo.geometry.Matrix; + equals(other: kendo.geometry.Matrix): boolean; + round(digits: number): kendo.geometry.Matrix; + multiplyCopy(matrix: kendo.geometry.Matrix): kendo.geometry.Matrix; + toArray(digits: number): any; + toString(digits: number, separator: string): string; + + } + + interface MatrixOptions { + name?: string; + } + interface MatrixEvent { + sender: Matrix; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + + class Point extends Observable { + + + options: PointOptions; + + x: number; + y: number; + + constructor(x: number, y: number); + + static create(x: number, y: number): kendo.geometry.Point; + static create(x: any, y: number): kendo.geometry.Point; + static create(x: kendo.geometry.Point, y: number): kendo.geometry.Point; + static min(): kendo.geometry.Point; + static max(): kendo.geometry.Point; + static minPoint(): kendo.geometry.Point; + static maxPoint(): kendo.geometry.Point; + + clone(): kendo.geometry.Point; + distanceTo(point: kendo.geometry.Point): number; + equals(other: kendo.geometry.Point): boolean; + getX(): number; + getY(): number; + move(x: number, y: number): kendo.geometry.Point; + rotate(angle: number, center: kendo.geometry.Point): kendo.geometry.Point; + rotate(angle: number, center: any): kendo.geometry.Point; + round(digits: number): kendo.geometry.Point; + scale(scaleX: number, scaleY: number): kendo.geometry.Point; + scaleCopy(scaleX: number, scaleY: number): kendo.geometry.Point; + setX(value: number): kendo.geometry.Point; + setY(value: number): kendo.geometry.Point; + toArray(digits: number): any; + toString(digits: number, separator: string): string; + transform(tansformation: kendo.geometry.Transformation): kendo.geometry.Point; + transformCopy(tansformation: kendo.geometry.Transformation): kendo.geometry.Point; + translate(dx: number, dy: number): kendo.geometry.Point; + translateWith(vector: kendo.geometry.Point): kendo.geometry.Point; + translateWith(vector: any): kendo.geometry.Point; + + } + + interface PointOptions { + name?: string; + } + interface PointEvent { + sender: Point; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + + class Rect extends Observable { + + + options: RectOptions; + + origin: kendo.geometry.Point; + size: kendo.geometry.Size; + + constructor(origin: kendo.geometry.Point|any, size: kendo.geometry.Size|any); + + static fromPoints(pointA: kendo.geometry.Point, pointB: kendo.geometry.Point): kendo.geometry.Rect; + static union(rectA: kendo.geometry.Rect, rectB: kendo.geometry.Rect): kendo.geometry.Rect; + + bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; + bottomLeft(): kendo.geometry.Point; + bottomRight(): kendo.geometry.Point; + center(): kendo.geometry.Point; + clone(): kendo.geometry.Rect; + equals(other: kendo.geometry.Rect): boolean; + getOrigin(): kendo.geometry.Point; + getSize(): kendo.geometry.Size; + height(): number; + setOrigin(value: kendo.geometry.Point): kendo.geometry.Rect; + setOrigin(value: any): kendo.geometry.Rect; + setSize(value: kendo.geometry.Size): kendo.geometry.Rect; + setSize(value: any): kendo.geometry.Rect; + topLeft(): kendo.geometry.Point; + topRight(): kendo.geometry.Point; + width(): number; + + } + + interface RectOptions { + name?: string; + } + interface RectEvent { + sender: Rect; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + + class Size extends Observable { + + + options: SizeOptions; + + width: number; + height: number; + + + static create(width: number, height: number): kendo.geometry.Size; + static create(width: any, height: number): kendo.geometry.Size; + static create(width: kendo.geometry.Size, height: number): kendo.geometry.Size; + + clone(): kendo.geometry.Size; + equals(other: kendo.geometry.Size): boolean; + getWidth(): number; + getHeight(): number; + setWidth(value: number): kendo.geometry.Size; + setHeight(value: number): kendo.geometry.Size; + + } + + interface SizeOptions { + name?: string; + } + interface SizeEvent { + sender: Size; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + + class Transformation extends Observable { + + + options: TransformationOptions; + + + + + clone(): kendo.geometry.Transformation; + equals(other: kendo.geometry.Transformation): boolean; + matrix(): kendo.geometry.Matrix; + multiply(transformation: kendo.geometry.Transformation): kendo.geometry.Transformation; + rotate(angle: number, center: any): kendo.geometry.Transformation; + rotate(angle: number, center: kendo.geometry.Point): kendo.geometry.Transformation; + scale(scaleX: number, scaleY: number): kendo.geometry.Transformation; + translate(x: number, y: number): kendo.geometry.Transformation; + + } + + interface TransformationOptions { + name?: string; + } + interface TransformationEvent { + sender: Transformation; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + } declare namespace kendo.drawing { class Arc extends kendo.drawing.Element { @@ -8419,274 +8836,6 @@ declare namespace kendo.drawing { -} -declare namespace kendo.geometry { - class Arc extends Observable { - - - options: ArcOptions; - - anticlockwise: boolean; - center: kendo.geometry.Point; - endAngle: number; - radiusX: number; - radiusY: number; - startAngle: number; - - constructor(center: any|kendo.geometry.Point, options?: ArcOptions); - - - bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; - getAnticlockwise(): boolean; - getCenter(): kendo.geometry.Point; - getEndAngle(): number; - getRadiusX(): number; - getRadiusY(): number; - getStartAngle(): number; - pointAt(angle: number): kendo.geometry.Point; - setAnticlockwise(value: boolean): kendo.geometry.Arc; - setCenter(value: kendo.geometry.Point): kendo.geometry.Arc; - setEndAngle(value: number): kendo.geometry.Arc; - setRadiusX(value: number): kendo.geometry.Arc; - setRadiusY(value: number): kendo.geometry.Arc; - setStartAngle(value: number): kendo.geometry.Arc; - - } - - interface ArcOptions { - name?: string; - } - interface ArcEvent { - sender: Arc; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - - class Circle extends Observable { - - - options: CircleOptions; - - center: kendo.geometry.Point; - radius: number; - - constructor(center: any|kendo.geometry.Point, radius: number); - - - bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; - clone(): kendo.geometry.Circle; - equals(other: kendo.geometry.Circle): boolean; - getCenter(): kendo.geometry.Point; - getRadius(): number; - pointAt(angle: number): kendo.geometry.Point; - setCenter(value: kendo.geometry.Point): kendo.geometry.Point; - setCenter(value: any): kendo.geometry.Point; - setRadius(value: number): kendo.geometry.Circle; - - } - - interface CircleOptions { - name?: string; - } - interface CircleEvent { - sender: Circle; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - - class Matrix extends Observable { - - - options: MatrixOptions; - - a: number; - b: number; - c: number; - d: number; - e: number; - f: number; - - - static rotate(angle: number, x: number, y: number): kendo.geometry.Matrix; - static scale(scaleX: number, scaleY: number): kendo.geometry.Matrix; - static translate(x: number, y: number): kendo.geometry.Matrix; - static unit(): kendo.geometry.Matrix; - - clone(): kendo.geometry.Matrix; - equals(other: kendo.geometry.Matrix): boolean; - round(digits: number): kendo.geometry.Matrix; - multiplyCopy(matrix: kendo.geometry.Matrix): kendo.geometry.Matrix; - toArray(digits: number): any; - toString(digits?: number, separator?: string): string; - - } - - interface MatrixOptions { - name?: string; - } - interface MatrixEvent { - sender: Matrix; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - - class Point extends Observable { - - - options: PointOptions; - - x: number; - y: number; - - constructor(x: number, y: number); - - static create(x: number, y: number): kendo.geometry.Point; - static create(x: any, y: number): kendo.geometry.Point; - static create(x: kendo.geometry.Point, y: number): kendo.geometry.Point; - static min(): kendo.geometry.Point; - static max(): kendo.geometry.Point; - static minPoint(): kendo.geometry.Point; - static maxPoint(): kendo.geometry.Point; - - clone(): kendo.geometry.Point; - distanceTo(point: kendo.geometry.Point): number; - equals(other: kendo.geometry.Point): boolean; - getX(): number; - getY(): number; - move(x: number, y: number): kendo.geometry.Point; - rotate(angle: number, center: kendo.geometry.Point): kendo.geometry.Point; - rotate(angle: number, center: any): kendo.geometry.Point; - round(digits: number): kendo.geometry.Point; - scale(scaleX: number, scaleY: number): kendo.geometry.Point; - scaleCopy(scaleX: number, scaleY: number): kendo.geometry.Point; - setX(value: number): kendo.geometry.Point; - setY(value: number): kendo.geometry.Point; - toArray(digits: number): any; - toString(digits?: number, separator?: string): string; - transform(tansformation: kendo.geometry.Transformation): kendo.geometry.Point; - transformCopy(tansformation: kendo.geometry.Transformation): kendo.geometry.Point; - translate(dx: number, dy: number): kendo.geometry.Point; - translateWith(vector: kendo.geometry.Point): kendo.geometry.Point; - translateWith(vector: any): kendo.geometry.Point; - - } - - interface PointOptions { - name?: string; - } - interface PointEvent { - sender: Point; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - - class Rect extends Observable { - - - options: RectOptions; - - origin: kendo.geometry.Point; - size: kendo.geometry.Size; - - constructor(origin: kendo.geometry.Point|any, size: kendo.geometry.Size|any); - - static fromPoints(pointA: kendo.geometry.Point, pointB: kendo.geometry.Point): kendo.geometry.Rect; - static union(rectA: kendo.geometry.Rect, rectB: kendo.geometry.Rect): kendo.geometry.Rect; - - bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; - bottomLeft(): kendo.geometry.Point; - bottomRight(): kendo.geometry.Point; - center(): kendo.geometry.Point; - clone(): kendo.geometry.Rect; - equals(other: kendo.geometry.Rect): boolean; - getOrigin(): kendo.geometry.Point; - getSize(): kendo.geometry.Size; - height(): number; - setOrigin(value: kendo.geometry.Point): kendo.geometry.Rect; - setOrigin(value: any): kendo.geometry.Rect; - setSize(value: kendo.geometry.Size): kendo.geometry.Rect; - setSize(value: any): kendo.geometry.Rect; - topLeft(): kendo.geometry.Point; - topRight(): kendo.geometry.Point; - width(): number; - - } - - interface RectOptions { - name?: string; - } - interface RectEvent { - sender: Rect; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - - class Size extends Observable { - - - options: SizeOptions; - - width: number; - height: number; - - - static create(width: number, height: number): kendo.geometry.Size; - static create(width: any, height: number): kendo.geometry.Size; - static create(width: kendo.geometry.Size, height: number): kendo.geometry.Size; - - clone(): kendo.geometry.Size; - equals(other: kendo.geometry.Size): boolean; - getWidth(): number; - getHeight(): number; - setWidth(value: number): kendo.geometry.Size; - setHeight(value: number): kendo.geometry.Size; - - } - - interface SizeOptions { - name?: string; - } - interface SizeEvent { - sender: Size; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - - class Transformation extends Observable { - - - options: TransformationOptions; - - - - - clone(): kendo.geometry.Transformation; - equals(other: kendo.geometry.Transformation): boolean; - matrix(): kendo.geometry.Matrix; - multiply(transformation: kendo.geometry.Transformation): kendo.geometry.Transformation; - rotate(angle: number, center: any): kendo.geometry.Transformation; - rotate(angle: number, center: kendo.geometry.Point): kendo.geometry.Transformation; - scale(scaleX: number, scaleY: number): kendo.geometry.Transformation; - translate(x: number, y: number): kendo.geometry.Transformation; - - } - - interface TransformationOptions { - name?: string; - } - interface TransformationEvent { - sender: Transformation; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - } declare namespace kendo.dataviz.ui { class Barcode extends kendo.ui.Widget { @@ -9681,6 +9830,7 @@ declare namespace kendo.dataviz.ui { margin?: ChartSeriesItemLabelsMargin; padding?: ChartSeriesItemLabelsPadding; position?: string|Function; + rotation?: string|number; template?: string|Function; visible?: boolean|Function; visual?: Function; @@ -9833,6 +9983,7 @@ declare namespace kendo.dataviz.ui { aggregate?: string|Function; axis?: string; border?: ChartSeriesItemBorder; + categoryAxis?: string; categoryField?: string; closeField?: string; color?: string|Function; @@ -10009,6 +10160,7 @@ declare namespace kendo.dataviz.ui { format?: string; margin?: ChartSeriesDefaultsLabelsMargin; padding?: ChartSeriesDefaultsLabelsPadding; + rotation?: string|number; template?: string|Function; visible?: boolean; visual?: Function; @@ -14295,7 +14447,7 @@ declare namespace kendo.dataviz.ui { inactiveItems?: StockChartLegendInactiveItems; } - interface StockChartNavigatorCategoryAxisItemAutoBaseUnitSteps { + interface StockChartNavigatorCategoryAxisAutoBaseUnitSteps { seconds?: any; minutes?: any; hours?: any; @@ -14305,45 +14457,45 @@ declare namespace kendo.dataviz.ui { years?: any; } - interface StockChartNavigatorCategoryAxisItemCrosshairTooltipBorder { + interface StockChartNavigatorCategoryAxisCrosshairTooltipBorder { color?: string; dashType?: string; width?: number; } - interface StockChartNavigatorCategoryAxisItemCrosshairTooltipPadding { + interface StockChartNavigatorCategoryAxisCrosshairTooltipPadding { bottom?: number; left?: number; right?: number; top?: number; } - interface StockChartNavigatorCategoryAxisItemCrosshairTooltip { + interface StockChartNavigatorCategoryAxisCrosshairTooltip { background?: string; - border?: StockChartNavigatorCategoryAxisItemCrosshairTooltipBorder; + border?: StockChartNavigatorCategoryAxisCrosshairTooltipBorder; color?: string; font?: string; format?: string; - padding?: StockChartNavigatorCategoryAxisItemCrosshairTooltipPadding; + padding?: StockChartNavigatorCategoryAxisCrosshairTooltipPadding; template?: string|Function; visible?: boolean; } - interface StockChartNavigatorCategoryAxisItemCrosshair { + interface StockChartNavigatorCategoryAxisCrosshair { color?: string; opacity?: number; - tooltip?: StockChartNavigatorCategoryAxisItemCrosshairTooltip; + tooltip?: StockChartNavigatorCategoryAxisCrosshairTooltip; visible?: boolean; width?: number; } - interface StockChartNavigatorCategoryAxisItemLabelsBorder { + interface StockChartNavigatorCategoryAxisLabelsBorder { color?: string; dashType?: string; width?: number; } - interface StockChartNavigatorCategoryAxisItemLabelsDateFormats { + interface StockChartNavigatorCategoryAxisLabelsDateFormats { days?: string; hours?: string; months?: string; @@ -14351,31 +14503,31 @@ declare namespace kendo.dataviz.ui { years?: string; } - interface StockChartNavigatorCategoryAxisItemLabelsMargin { + interface StockChartNavigatorCategoryAxisLabelsMargin { bottom?: number; left?: number; right?: number; top?: number; } - interface StockChartNavigatorCategoryAxisItemLabelsPadding { + interface StockChartNavigatorCategoryAxisLabelsPadding { bottom?: number; left?: number; right?: number; top?: number; } - interface StockChartNavigatorCategoryAxisItemLabels { + interface StockChartNavigatorCategoryAxisLabels { background?: string; - border?: StockChartNavigatorCategoryAxisItemLabelsBorder; + border?: StockChartNavigatorCategoryAxisLabelsBorder; color?: string; culture?: string; - dateFormats?: StockChartNavigatorCategoryAxisItemLabelsDateFormats; + dateFormats?: StockChartNavigatorCategoryAxisLabelsDateFormats; font?: string; format?: string; - margin?: StockChartNavigatorCategoryAxisItemLabelsMargin; + margin?: StockChartNavigatorCategoryAxisLabelsMargin; mirror?: boolean; - padding?: StockChartNavigatorCategoryAxisItemLabelsPadding; + padding?: StockChartNavigatorCategoryAxisLabelsPadding; rotation?: number; skip?: number; step?: number; @@ -14383,14 +14535,14 @@ declare namespace kendo.dataviz.ui { visible?: boolean; } - interface StockChartNavigatorCategoryAxisItemLine { + interface StockChartNavigatorCategoryAxisLine { color?: string; dashType?: string; visible?: boolean; width?: number; } - interface StockChartNavigatorCategoryAxisItemMajorGridLines { + interface StockChartNavigatorCategoryAxisMajorGridLines { color?: string; dashType?: string; visible?: boolean; @@ -14399,7 +14551,7 @@ declare namespace kendo.dataviz.ui { skip?: number; } - interface StockChartNavigatorCategoryAxisItemMajorTicks { + interface StockChartNavigatorCategoryAxisMajorTicks { color?: string; size?: number; visible?: boolean; @@ -14408,7 +14560,7 @@ declare namespace kendo.dataviz.ui { skip?: number; } - interface StockChartNavigatorCategoryAxisItemMinorGridLines { + interface StockChartNavigatorCategoryAxisMinorGridLines { color?: string; dashType?: string; visible?: boolean; @@ -14417,7 +14569,7 @@ declare namespace kendo.dataviz.ui { skip?: number; } - interface StockChartNavigatorCategoryAxisItemMinorTicks { + interface StockChartNavigatorCategoryAxisMinorTicks { color?: string; size?: number; visible?: boolean; @@ -14426,28 +14578,28 @@ declare namespace kendo.dataviz.ui { skip?: number; } - interface StockChartNavigatorCategoryAxisItemNotesDataItemIconBorder { + interface StockChartNavigatorCategoryAxisNotesDataItemIconBorder { color?: string; width?: number; } - interface StockChartNavigatorCategoryAxisItemNotesDataItemIcon { + interface StockChartNavigatorCategoryAxisNotesDataItemIcon { background?: string; - border?: StockChartNavigatorCategoryAxisItemNotesDataItemIconBorder; + border?: StockChartNavigatorCategoryAxisNotesDataItemIconBorder; size?: number; type?: string; visible?: boolean; } - interface StockChartNavigatorCategoryAxisItemNotesDataItemLabelBorder { + interface StockChartNavigatorCategoryAxisNotesDataItemLabelBorder { color?: string; dashType?: string; width?: number; } - interface StockChartNavigatorCategoryAxisItemNotesDataItemLabel { + interface StockChartNavigatorCategoryAxisNotesDataItemLabel { background?: string; - border?: StockChartNavigatorCategoryAxisItemNotesDataItemLabelBorder; + border?: StockChartNavigatorCategoryAxisNotesDataItemLabelBorder; color?: string; font?: string; template?: string|Function; @@ -14458,42 +14610,42 @@ declare namespace kendo.dataviz.ui { position?: string; } - interface StockChartNavigatorCategoryAxisItemNotesDataItemLine { + interface StockChartNavigatorCategoryAxisNotesDataItemLine { width?: number; color?: string; length?: number; } - interface StockChartNavigatorCategoryAxisItemNotesDataItem { + interface StockChartNavigatorCategoryAxisNotesDataItem { value?: any; position?: string; - icon?: StockChartNavigatorCategoryAxisItemNotesDataItemIcon; - label?: StockChartNavigatorCategoryAxisItemNotesDataItemLabel; - line?: StockChartNavigatorCategoryAxisItemNotesDataItemLine; + icon?: StockChartNavigatorCategoryAxisNotesDataItemIcon; + label?: StockChartNavigatorCategoryAxisNotesDataItemLabel; + line?: StockChartNavigatorCategoryAxisNotesDataItemLine; } - interface StockChartNavigatorCategoryAxisItemNotesIconBorder { + interface StockChartNavigatorCategoryAxisNotesIconBorder { color?: string; width?: number; } - interface StockChartNavigatorCategoryAxisItemNotesIcon { + interface StockChartNavigatorCategoryAxisNotesIcon { background?: string; - border?: StockChartNavigatorCategoryAxisItemNotesIconBorder; + border?: StockChartNavigatorCategoryAxisNotesIconBorder; size?: number; type?: string; visible?: boolean; } - interface StockChartNavigatorCategoryAxisItemNotesLabelBorder { + interface StockChartNavigatorCategoryAxisNotesLabelBorder { color?: string; dashType?: string; width?: number; } - interface StockChartNavigatorCategoryAxisItemNotesLabel { + interface StockChartNavigatorCategoryAxisNotesLabel { background?: string; - border?: StockChartNavigatorCategoryAxisItemNotesLabelBorder; + border?: StockChartNavigatorCategoryAxisNotesLabelBorder; color?: string; font?: string; template?: string|Function; @@ -14503,87 +14655,87 @@ declare namespace kendo.dataviz.ui { position?: string; } - interface StockChartNavigatorCategoryAxisItemNotesLine { + interface StockChartNavigatorCategoryAxisNotesLine { width?: number; color?: string; length?: number; } - interface StockChartNavigatorCategoryAxisItemNotes { + interface StockChartNavigatorCategoryAxisNotes { position?: string; - icon?: StockChartNavigatorCategoryAxisItemNotesIcon; - label?: StockChartNavigatorCategoryAxisItemNotesLabel; - line?: StockChartNavigatorCategoryAxisItemNotesLine; - data?: StockChartNavigatorCategoryAxisItemNotesDataItem[]; + icon?: StockChartNavigatorCategoryAxisNotesIcon; + label?: StockChartNavigatorCategoryAxisNotesLabel; + line?: StockChartNavigatorCategoryAxisNotesLine; + data?: StockChartNavigatorCategoryAxisNotesDataItem[]; } - interface StockChartNavigatorCategoryAxisItemPlotBand { + interface StockChartNavigatorCategoryAxisPlotBand { color?: string; from?: number; opacity?: number; to?: number; } - interface StockChartNavigatorCategoryAxisItemTitleBorder { + interface StockChartNavigatorCategoryAxisTitleBorder { color?: string; dashType?: string; width?: number; } - interface StockChartNavigatorCategoryAxisItemTitleMargin { + interface StockChartNavigatorCategoryAxisTitleMargin { bottom?: number; left?: number; right?: number; top?: number; } - interface StockChartNavigatorCategoryAxisItemTitlePadding { + interface StockChartNavigatorCategoryAxisTitlePadding { bottom?: number; left?: number; right?: number; top?: number; } - interface StockChartNavigatorCategoryAxisItemTitle { + interface StockChartNavigatorCategoryAxisTitle { background?: string; - border?: StockChartNavigatorCategoryAxisItemTitleBorder; + border?: StockChartNavigatorCategoryAxisTitleBorder; color?: string; font?: string; - margin?: StockChartNavigatorCategoryAxisItemTitleMargin; - padding?: StockChartNavigatorCategoryAxisItemTitlePadding; + margin?: StockChartNavigatorCategoryAxisTitleMargin; + padding?: StockChartNavigatorCategoryAxisTitlePadding; position?: string; rotation?: number; text?: string; visible?: boolean; } - interface StockChartNavigatorCategoryAxisItem { - autoBaseUnitSteps?: StockChartNavigatorCategoryAxisItemAutoBaseUnitSteps; + interface StockChartNavigatorCategoryAxis { + autoBaseUnitSteps?: StockChartNavigatorCategoryAxisAutoBaseUnitSteps; axisCrossingValue?: any|Date|any; background?: string; baseUnit?: string; baseUnitStep?: any; categories?: any; color?: string; - crosshair?: StockChartNavigatorCategoryAxisItemCrosshair; + crosshair?: StockChartNavigatorCategoryAxisCrosshair; field?: string; justified?: boolean; - labels?: StockChartNavigatorCategoryAxisItemLabels; - line?: StockChartNavigatorCategoryAxisItemLine; - majorGridLines?: StockChartNavigatorCategoryAxisItemMajorGridLines; - majorTicks?: StockChartNavigatorCategoryAxisItemMajorTicks; + labels?: StockChartNavigatorCategoryAxisLabels; + line?: StockChartNavigatorCategoryAxisLine; + majorGridLines?: StockChartNavigatorCategoryAxisMajorGridLines; + majorTicks?: StockChartNavigatorCategoryAxisMajorTicks; max?: any; maxDateGroups?: number; min?: any; - minorGridLines?: StockChartNavigatorCategoryAxisItemMinorGridLines; - minorTicks?: StockChartNavigatorCategoryAxisItemMinorTicks; - plotBands?: StockChartNavigatorCategoryAxisItemPlotBand[]; + minorGridLines?: StockChartNavigatorCategoryAxisMinorGridLines; + minorTicks?: StockChartNavigatorCategoryAxisMinorTicks; + plotBands?: StockChartNavigatorCategoryAxisPlotBand[]; reverse?: boolean; roundToBaseUnit?: boolean; - title?: StockChartNavigatorCategoryAxisItemTitle; + title?: StockChartNavigatorCategoryAxisTitle; visible?: boolean; weekStartDay?: number; - notes?: StockChartNavigatorCategoryAxisItemNotes; + notes?: StockChartNavigatorCategoryAxisNotes; } interface StockChartNavigatorHint { @@ -14781,7 +14933,7 @@ declare namespace kendo.dataviz.ui { } interface StockChartNavigator { - categoryAxis?: StockChartNavigatorCategoryAxisItem[]; + categoryAxis?: StockChartNavigatorCategoryAxis; dataSource?: any; autoBind?: boolean; dateField?: string; @@ -16959,6 +17111,27 @@ declare namespace kendo { } + namespace date { + function setDayOfWeek(targetDate: Date, dayOfWeek: number, direction: number): void; + function dayOfWeek(targetDate: Date, dayOfWeek: number, direction: number): Date; + function weekInYear(date: Date, weekStart?: Date): number; + function getDate(date: Date): Date; + function isInDateRange(targetDate: Date, lowerLimitDate: Date, upperLimitDate: Date): boolean; + function isInTimeRange(targetDate: Date, lowerLimitDate: Date, upperLimitDate: Date): boolean; + function isToday(targetDate: Date): boolean; + function nextDay(targetDate: Date): Date; + function previousDay(targetDate: Date): Date; + function toUtcTime(targetDate: Date): number; + function setTime(targetDate: Date, millisecondsToAdd: number, ignoreDST: boolean): void; + function setHours(targetDate: Date, sourceDate: number): Date; + function addDays(targetDate: Date, numberOfDaysToAdd: number): Date; + function today(): Date; + function toInvariantTime(targetDate: Date): Date; + function firstDayOfMonth(targetDate: Date): Date; + function lastDayOfMonth(targetDate: Date): Date; + function getMilliseconds(targetDate: Date): Date; + } + namespace drawing { function align(elements: any, rect: kendo.geometry.Rect, alignment: string): void; function drawDOM(element: JQuery, options: any): JQueryPromise; @@ -17022,6 +17195,22 @@ declare namespace kendo { function defineFont(map: any): void; } + namespace timezone { + function offset(utcTime: Date, timezone: string): number; + function offset(utcTime: number, timezone: string): number; + function convert(targetDate: Date, fromOffset: number, toOffset: number): Date; + function convert(targetDate: Date, fromOffset: number, toOffset: string): Date; + function convert(targetDate: Date, fromOffset: string, toOffset: number): Date; + function convert(targetDate: Date, fromOffset: string, toOffset: string): Date; + function apply(targetDate: Date, offset: number): Date; + function apply(targetDate: Date, offset: string): Date; + function remove(targetDate: Date, offset: number): Date; + function remove(targetDate: Date, offset: string): Date; + function abbr(targetDate: Date, timezone: string): string; + function toLocalDate(targetDate: Date): Date; + function toLocalDate(targetDate: number): Date; + } + } declare namespace kendo.spreadsheet { class CustomFilter extends Observable { @@ -18306,7 +18495,7 @@ declare namespace kendo.ooxml { interface WorkbookSheetRow { cells?: WorkbookSheetRowCell[]; index?: number; - height?: number; + height?: number; type?: "header" | "footer" | "group-header" | "group-footer" | "data"; } @@ -18337,6 +18526,268 @@ declare namespace kendo.ooxml { } +declare namespace kendo.dataviz.geometry { + class Arc extends Observable { + + + options: ArcOptions; + + anticlockwise: boolean; + center: kendo.geometry.Point; + endAngle: number; + radiusX: number; + radiusY: number; + startAngle: number; + + constructor(center: any|kendo.geometry.Point, options?: ArcOptions); + + + bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; + getAnticlockwise(): boolean; + getCenter(): kendo.geometry.Point; + getEndAngle(): number; + getRadiusX(): number; + getRadiusY(): number; + getStartAngle(): number; + pointAt(angle: number): kendo.geometry.Point; + setAnticlockwise(value: boolean): kendo.geometry.Arc; + setCenter(value: kendo.geometry.Point): kendo.geometry.Arc; + setEndAngle(value: number): kendo.geometry.Arc; + setRadiusX(value: number): kendo.geometry.Arc; + setRadiusY(value: number): kendo.geometry.Arc; + setStartAngle(value: number): kendo.geometry.Arc; + + } + + interface ArcOptions { + name?: string; + } + interface ArcEvent { + sender: Arc; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + + class Circle extends Observable { + + + options: CircleOptions; + + center: kendo.geometry.Point; + radius: number; + + constructor(center: any|kendo.geometry.Point, radius: number); + + + bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; + clone(): kendo.geometry.Circle; + equals(other: kendo.geometry.Circle): boolean; + getCenter(): kendo.geometry.Point; + getRadius(): number; + pointAt(angle: number): kendo.geometry.Point; + setCenter(value: kendo.geometry.Point): kendo.geometry.Point; + setCenter(value: any): kendo.geometry.Point; + setRadius(value: number): kendo.geometry.Circle; + + } + + interface CircleOptions { + name?: string; + } + interface CircleEvent { + sender: Circle; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + + class Matrix extends Observable { + + + options: MatrixOptions; + + a: number; + b: number; + c: number; + d: number; + e: number; + f: number; + + + static rotate(angle: number, x: number, y: number): kendo.geometry.Matrix; + static scale(scaleX: number, scaleY: number): kendo.geometry.Matrix; + static translate(x: number, y: number): kendo.geometry.Matrix; + static unit(): kendo.geometry.Matrix; + + clone(): kendo.geometry.Matrix; + equals(other: kendo.geometry.Matrix): boolean; + round(digits: number): kendo.geometry.Matrix; + multiplyCopy(matrix: kendo.geometry.Matrix): kendo.geometry.Matrix; + toArray(digits: number): any; + toString(digits: number, separator: string): string; + + } + + interface MatrixOptions { + name?: string; + } + interface MatrixEvent { + sender: Matrix; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + + class Point extends Observable { + + + options: PointOptions; + + x: number; + y: number; + + constructor(x: number, y: number); + + static create(x: number, y: number): kendo.geometry.Point; + static create(x: any, y: number): kendo.geometry.Point; + static create(x: kendo.geometry.Point, y: number): kendo.geometry.Point; + static min(): kendo.geometry.Point; + static max(): kendo.geometry.Point; + static minPoint(): kendo.geometry.Point; + static maxPoint(): kendo.geometry.Point; + + clone(): kendo.geometry.Point; + distanceTo(point: kendo.geometry.Point): number; + equals(other: kendo.geometry.Point): boolean; + getX(): number; + getY(): number; + move(x: number, y: number): kendo.geometry.Point; + rotate(angle: number, center: kendo.geometry.Point): kendo.geometry.Point; + rotate(angle: number, center: any): kendo.geometry.Point; + round(digits: number): kendo.geometry.Point; + scale(scaleX: number, scaleY: number): kendo.geometry.Point; + scaleCopy(scaleX: number, scaleY: number): kendo.geometry.Point; + setX(value: number): kendo.geometry.Point; + setY(value: number): kendo.geometry.Point; + toArray(digits: number): any; + toString(digits: number, separator: string): string; + transform(tansformation: kendo.geometry.Transformation): kendo.geometry.Point; + transformCopy(tansformation: kendo.geometry.Transformation): kendo.geometry.Point; + translate(dx: number, dy: number): kendo.geometry.Point; + translateWith(vector: kendo.geometry.Point): kendo.geometry.Point; + translateWith(vector: any): kendo.geometry.Point; + + } + + interface PointOptions { + name?: string; + } + interface PointEvent { + sender: Point; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + + class Rect extends Observable { + + + options: RectOptions; + + origin: kendo.geometry.Point; + size: kendo.geometry.Size; + + constructor(origin: kendo.geometry.Point|any, size: kendo.geometry.Size|any); + + static fromPoints(pointA: kendo.geometry.Point, pointB: kendo.geometry.Point): kendo.geometry.Rect; + static union(rectA: kendo.geometry.Rect, rectB: kendo.geometry.Rect): kendo.geometry.Rect; + + bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; + bottomLeft(): kendo.geometry.Point; + bottomRight(): kendo.geometry.Point; + center(): kendo.geometry.Point; + clone(): kendo.geometry.Rect; + equals(other: kendo.geometry.Rect): boolean; + getOrigin(): kendo.geometry.Point; + getSize(): kendo.geometry.Size; + height(): number; + setOrigin(value: kendo.geometry.Point): kendo.geometry.Rect; + setOrigin(value: any): kendo.geometry.Rect; + setSize(value: kendo.geometry.Size): kendo.geometry.Rect; + setSize(value: any): kendo.geometry.Rect; + topLeft(): kendo.geometry.Point; + topRight(): kendo.geometry.Point; + width(): number; + + } + + interface RectOptions { + name?: string; + } + interface RectEvent { + sender: Rect; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + + class Size extends Observable { + + + options: SizeOptions; + + width: number; + height: number; + + + static create(width: number, height: number): kendo.geometry.Size; + static create(width: any, height: number): kendo.geometry.Size; + static create(width: kendo.geometry.Size, height: number): kendo.geometry.Size; + + clone(): kendo.geometry.Size; + equals(other: kendo.geometry.Size): boolean; + getWidth(): number; + getHeight(): number; + setWidth(value: number): kendo.geometry.Size; + setHeight(value: number): kendo.geometry.Size; + + } + + interface SizeOptions { + name?: string; + } + + class Transformation extends Observable { + + + options: TransformationOptions; + + + + + clone(): kendo.geometry.Transformation; + equals(other: kendo.geometry.Transformation): boolean; + matrix(): kendo.geometry.Matrix; + multiply(transformation: kendo.geometry.Transformation): kendo.geometry.Transformation; + rotate(angle: number, center: any): kendo.geometry.Transformation; + rotate(angle: number, center: kendo.geometry.Point): kendo.geometry.Transformation; + scale(scaleX: number, scaleY: number): kendo.geometry.Transformation; + translate(x: number, y: number): kendo.geometry.Transformation; + + } + + interface TransformationOptions { + name?: string; + } + interface TransformationEvent { + sender: Transformation; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + +} declare namespace kendo.dataviz.drawing { class Arc extends kendo.drawing.Element { @@ -19126,274 +19577,6 @@ declare namespace kendo.dataviz.drawing { -} -declare namespace kendo.dataviz.geometry { - class Arc extends Observable { - - - options: ArcOptions; - - anticlockwise: boolean; - center: kendo.geometry.Point; - endAngle: number; - radiusX: number; - radiusY: number; - startAngle: number; - - constructor(center: any|kendo.geometry.Point, options?: ArcOptions); - - - bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; - getAnticlockwise(): boolean; - getCenter(): kendo.geometry.Point; - getEndAngle(): number; - getRadiusX(): number; - getRadiusY(): number; - getStartAngle(): number; - pointAt(angle: number): kendo.geometry.Point; - setAnticlockwise(value: boolean): kendo.geometry.Arc; - setCenter(value: kendo.geometry.Point): kendo.geometry.Arc; - setEndAngle(value: number): kendo.geometry.Arc; - setRadiusX(value: number): kendo.geometry.Arc; - setRadiusY(value: number): kendo.geometry.Arc; - setStartAngle(value: number): kendo.geometry.Arc; - - } - - interface ArcOptions { - name?: string; - } - interface ArcEvent { - sender: Arc; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - - class Circle extends Observable { - - - options: CircleOptions; - - center: kendo.geometry.Point; - radius: number; - - constructor(center: any|kendo.geometry.Point, radius: number); - - - bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; - clone(): kendo.geometry.Circle; - equals(other: kendo.geometry.Circle): boolean; - getCenter(): kendo.geometry.Point; - getRadius(): number; - pointAt(angle: number): kendo.geometry.Point; - setCenter(value: kendo.geometry.Point): kendo.geometry.Point; - setCenter(value: any): kendo.geometry.Point; - setRadius(value: number): kendo.geometry.Circle; - - } - - interface CircleOptions { - name?: string; - } - interface CircleEvent { - sender: Circle; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - - class Matrix extends Observable { - - - options: MatrixOptions; - - a: number; - b: number; - c: number; - d: number; - e: number; - f: number; - - - static rotate(angle: number, x: number, y: number): kendo.geometry.Matrix; - static scale(scaleX: number, scaleY: number): kendo.geometry.Matrix; - static translate(x: number, y: number): kendo.geometry.Matrix; - static unit(): kendo.geometry.Matrix; - - clone(): kendo.geometry.Matrix; - equals(other: kendo.geometry.Matrix): boolean; - round(digits: number): kendo.geometry.Matrix; - multiplyCopy(matrix: kendo.geometry.Matrix): kendo.geometry.Matrix; - toArray(digits: number): any; - toString(digits?: number, separator?: string): string; - - } - - interface MatrixOptions { - name?: string; - } - interface MatrixEvent { - sender: Matrix; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - - class Point extends Observable { - - - options: PointOptions; - - x: number; - y: number; - - constructor(x: number, y: number); - - static create(x: number, y: number): kendo.geometry.Point; - static create(x: any, y: number): kendo.geometry.Point; - static create(x: kendo.geometry.Point, y: number): kendo.geometry.Point; - static min(): kendo.geometry.Point; - static max(): kendo.geometry.Point; - static minPoint(): kendo.geometry.Point; - static maxPoint(): kendo.geometry.Point; - - clone(): kendo.geometry.Point; - distanceTo(point: kendo.geometry.Point): number; - equals(other: kendo.geometry.Point): boolean; - getX(): number; - getY(): number; - move(x: number, y: number): kendo.geometry.Point; - rotate(angle: number, center: kendo.geometry.Point): kendo.geometry.Point; - rotate(angle: number, center: any): kendo.geometry.Point; - round(digits: number): kendo.geometry.Point; - scale(scaleX: number, scaleY: number): kendo.geometry.Point; - scaleCopy(scaleX: number, scaleY: number): kendo.geometry.Point; - setX(value: number): kendo.geometry.Point; - setY(value: number): kendo.geometry.Point; - toArray(digits: number): any; - toString(digits: number, separator: string): string; - transform(tansformation: kendo.geometry.Transformation): kendo.geometry.Point; - transformCopy(tansformation: kendo.geometry.Transformation): kendo.geometry.Point; - translate(dx: number, dy: number): kendo.geometry.Point; - translateWith(vector: kendo.geometry.Point): kendo.geometry.Point; - translateWith(vector: any): kendo.geometry.Point; - - } - - interface PointOptions { - name?: string; - } - interface PointEvent { - sender: Point; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - - class Rect extends Observable { - - - options: RectOptions; - - origin: kendo.geometry.Point; - size: kendo.geometry.Size; - - constructor(origin: kendo.geometry.Point|any, size: kendo.geometry.Size|any); - - static fromPoints(pointA: kendo.geometry.Point, pointB: kendo.geometry.Point): kendo.geometry.Rect; - static union(rectA: kendo.geometry.Rect, rectB: kendo.geometry.Rect): kendo.geometry.Rect; - - bbox(matrix: kendo.geometry.Matrix): kendo.geometry.Rect; - bottomLeft(): kendo.geometry.Point; - bottomRight(): kendo.geometry.Point; - center(): kendo.geometry.Point; - clone(): kendo.geometry.Rect; - equals(other: kendo.geometry.Rect): boolean; - getOrigin(): kendo.geometry.Point; - getSize(): kendo.geometry.Size; - height(): number; - setOrigin(value: kendo.geometry.Point): kendo.geometry.Rect; - setOrigin(value: any): kendo.geometry.Rect; - setSize(value: kendo.geometry.Size): kendo.geometry.Rect; - setSize(value: any): kendo.geometry.Rect; - topLeft(): kendo.geometry.Point; - topRight(): kendo.geometry.Point; - width(): number; - - } - - interface RectOptions { - name?: string; - } - interface RectEvent { - sender: Rect; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - - class Size extends Observable { - - - options: SizeOptions; - - width: number; - height: number; - - - static create(width: number, height: number): kendo.geometry.Size; - static create(width: any, height: number): kendo.geometry.Size; - static create(width: kendo.geometry.Size, height: number): kendo.geometry.Size; - - clone(): kendo.geometry.Size; - equals(other: kendo.geometry.Size): boolean; - getWidth(): number; - getHeight(): number; - setWidth(value: number): kendo.geometry.Size; - setHeight(value: number): kendo.geometry.Size; - - } - - interface SizeOptions { - name?: string; - } - interface SizeEvent { - sender: Size; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - - class Transformation extends Observable { - - - options: TransformationOptions; - - - - - clone(): kendo.geometry.Transformation; - equals(other: kendo.geometry.Transformation): boolean; - matrix(): kendo.geometry.Matrix; - multiply(transformation: kendo.geometry.Transformation): kendo.geometry.Transformation; - rotate(angle: number, center: any): kendo.geometry.Transformation; - rotate(angle: number, center: kendo.geometry.Point): kendo.geometry.Transformation; - scale(scaleX: number, scaleY: number): kendo.geometry.Transformation; - translate(x: number, y: number): kendo.geometry.Transformation; - - } - - interface TransformationOptions { - name?: string; - } - interface TransformationEvent { - sender: Transformation; - preventDefault: Function; - isDefaultPrevented(): boolean; - } - - } interface HTMLElement { diff --git a/knuddels-userapps-api/index.d.ts b/knuddels-userapps-api/index.d.ts new file mode 100644 index 0000000000..b388301f68 --- /dev/null +++ b/knuddels-userapps-api/index.d.ts @@ -0,0 +1,2692 @@ +// Type definitions for Knuddels UserApps API 1.0 +// Project: https://developer.knuddels.de +// Definitions by: Knuddels GmbH & Co. KG +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// JSON definition +interface Json { + [x: string]: string | number | boolean | Date | Json | JsonArray; +} +interface JsonArray extends Array { } +// serializable objects (for persistence) +type KnuddelsSerializable = string | number | boolean | User | BotUser; +interface KnuddelsJson { + [x: string]: string | number | boolean | Date | KnuddelsJson | KnuddelsJsonArray | KnuddelsSerializable; +} +interface KnuddelsJsonArray extends Array { } +// "data" that may be send between apps and between server and client +type KnuddelsEvent = string | Json | KnuddelsEventArray; +interface KnuddelsEventArray extends Array { } +/** + * App ist die abstrakte Klasse einer konkreten App, die ein Entwickler schreiben kann. + * Im eigenen Javascript-Code muss eine Variable mit dem Namen App vorhanden sein, damit eine App lauffähig ist. + */ +declare interface App { + /** + * Dieses Methode wird aufgerufen, sobald ein Nutzer versucht den Channel zu betreten. + * Die App kann nun entscheiden, ob der Nutzer den Channel betreten darf. + * + * Hinweis: Um ein responsives User Interface für den Nutzer, + * der den Channel betreten möchte zu garantieren, muss die App innerhalb von einer Sekunde auf diese Anfrage reagieren, + * damit ihre Antwort in das Ergebnis einfliesst. + * + * Mit bestimmten Smileyfeatures ist es derzeit trotzdem möglich, den Channel zu betreten. + * Diese Nutzer können nicht ausgesperrt werden: + *
    + *
  • Channelbesitzer
  • + *
  • Channelmoderatoren und HZAs
  • + *
  • Admins (sofern notwendig)
  • + *
  • Sysadmins
  • + *
  • User Apps Team (Mitarbeiter von Knuddels)
  • + *
+ * + * Ist der Channel mit einem Passwort geschützt und der Nutzer, der versucht den Channel zu betreten kennt das Passwort, + * so kann er nicht aus dem Channel ausgeschlossen werden. + */ + mayJoinChannel?(user: User): ChannelJoinPermission; + /** + * Diese Methode wird jedes Mal aufgerufen, sobald ein Nutzer versucht eine öffentliche Nachricht zu senden. + * Die App kann nun entscheiden, ob die Nachricht veröffentlicht werden darf. + * + * Laufen mehrere Apps im selben Channel, so wird die Nachricht veröffentlicht, sofern alle Apps es erlauben. + * + * Dauert das Fragen aller Apps nach Erlaubnis länger als 10 Sekunden, so wird die Antwort genutzt, die bis dahin + * gegeben wurde. + */ + mayShowPublicMessage?(publicMessage: PublicMessage): boolean; + /** + * Diese Methode wird jedes Mal aufgerufen, sobald ein Nutzer versucht eine öffentliche Handlung auszuführen. + * Die App kann nun entscheiden, ob die Handlung ausgeführt werden darf. + * + * Laufen mehrere Apps im selben Channel, so wird die Handlung ausgeführt, sofern alle Apps es erlauben. + * + * Dauert das Fragen aller Apps nach Erlaubnis länger als 10 Sekunden, so wird die Antwort genutzt, die bis dahin + * gegeben wurde. + */ + mayShowPublicActionMessage?(publicActionMessage: PublicActionMessage): boolean; + /** + * Diese Methode wird aufgerufen, sobald die App startet. + * Dies ist der beste Zeipunkt um Werte zu initialisieren und aus der Persistenz zu lesen. + */ + onAppStart?(): void; + /** + * Diese Methode wird aufgerufen, wenn ein User Knuddel an den BotUser gesendet hat. + * Es ist die Aufgabe der App in dieser Methode zu entscheiden, ob sie die Knuddel annimmt oder ablehnt. + * Wird diese Methode von der App nicht implementiert, so werden Knuddel automatisch akzeptiert. + * Ist diese Methode implementiert und es treten Fehler (Exceptions, Timeout,...) auf oder der Entwickler entscheidet nicht, + * was mit den Knuddel geschehen soll, so werden diese vom App-System automatisch an den Absender zurück geschickt. + *
+ * Wichtig: Zum Zeitpunkt des Aufrufs dieser Methode wurden die Knuddel noch nicht an den BotUser übertragen. + */ + onBeforeKnuddelReceived?(knuddelTransfer: KnuddelTransfer): void; + /** + * Diese Methode wird aufgerufen, sobald ein BotUser Knuddel von einem User erhalten hat. + */ + onKnuddelReceived?(sender: User, receiver: BotUser, knuddelAmount: KnuddelAmount, transferReason: string): void; + /** + * Diese Methode wird aufgerufen, wenn die App sich darauf vorbereiten soll heruntergefahren zu werden. + * Als Parameter wird die geschätzte Zeit übergeben, die die App noch hat, bis sie heruntergefahren wird + * und der Aufruf App/onShutdown:event folgt. + * + * App/onPrepareShutdown:event kann dazu benutzt werden das Nutzererlebnis zu verbessern, + * sofern eine App heruntergefahren werden muss (bsp. für Updates). + * Eine Spiele-App könnte z.B. entscheiden, dass sie keine weiteren Spiele eröffnet und den Spielern offener Spiele + * die Information anzeigt, wie lange das Spiel noch läuft, bevor es unentschieden endet. + * + *

Achtung: Die Methode kann im Lebenszyklus einer App mehrfach aufgerufen werden. + */ + onPrepareShutdown?(secondsTillShutdown: number): void; + /** + * Diese Methode wird aufgerufen, wenn ein BotUser privat angeschrieben wird. + */ + onPrivateMessage?(privateMessage: PrivateMessage): void; + /** + * Diese Methode wird aufgerufen, wenn im Channel der App + * eine öffentliche Nachricht geschrieben wird. + * Für Nachrichten von BotUsern wird diese Methode nicht aufgerufen. + */ + onPublicMessage?(publicMessage: PublicMessage): void; + /** + * Diese Methode wird aufgerufen, wenn im Channel der App + * eine Event-Nachricht veröffentlicht wird. + * Für Nachrichten von BotUsern wird diese Methode nicht aufgerufen. + */ + onPublicEventMessage?(publicEventMessage: PublicEventMessage): void; + /** + * Diese Methode wird aufgerufen, wenn im Channel der App + * eine öffentliche Handlung durchgeführt wird. + * Für Handlungen von BotUsern wird diese Methode nicht aufgerufen. + */ + onPublicActionMessage?(publicActionMessage: PublicActionMessage): void; + /** + * Diese Methode wird aufgerufen, wenn eine App beendet wird. + * Sobald diese Methode aufgerufen wird, steht nur noch ein begrenzter Teil der API zur Verfügung. + * Die App sollte den kompletten Zustand in der Persistenz speichern, sodass der Zustand + * beim nächsten App/onAppStart:event wiederhergestellt werden kann. + * + * Während des Shutdowns können asynchrone each-Methoden, wie UserPersistenceNumbers/each:method + * und UserAccess/eachAccessibleUser:method nicht zuverlässig genutzt werden. + */ + onShutdown?(): void; + /** + * Diese Methode wird aufgerufen, wenn ein User im Channel der App + * über die Systemfunktionen (/dice, /diceo) würfelt. + * Die App kann auf das Ergebnis zugreifen und die Daten für die Auswertung und Entscheidungen nutzen. + */ + onUserDiced?(diceEvent: DiceEvent): void; + /** + * Diese Methode wird aufgerufen, wenn ein User den Channel der App betritt. + */ + onUserJoined?(user: User): void; + /** + * Diese Methode wird aufgerufen, wenn ein User den Channel der App verlässt. + */ + onUserLeft?(user: User): void; + /** + * Diese Methode wird aufgerufen, wenn aus einer anderen App ein Event mit sendAppEvent versendet wurde. + */ + onAppEventReceived?(appInstance: AppInstance, type: string, data: KnuddelsEvent): void; + /** + * Diese Methode wird aufgerufen, wenn aus dem HTML User Interface ein Event mit + * sendEvent() gesendet wurde. + */ + onEventReceived?(user: User, type: string, data: KnuddelsEvent, appContentSession: AppContentSession): void; + /** + * Diese Methode wird aufgerufen, wenn ein User Knuddel in seinen KnuddelAccount + * eingezahlt hat. + */ + onAccountReceivedKnuddel?(sender: User, receiver: BotUser, knuddelAmount: KnuddelAmount, transferReason: string, knuddelAccount: KnuddelAccount): void; + /** + * Diese Methode wird aufgerufen, wenn sich die Anzahl der Knuddel auf einem KnuddelAccount eines User + * geändert hat. + */ + onAccountChangedKnuddelAmount?(user: User, knuddelAccount: KnuddelAccount, oldKnuddelAmount: KnuddelAmount, newKnuddelAmount: KnuddelAmount): void; + /** + * Ermöglicht das Registrieren eigener Chatbefehle. + * In einem Channel kann nur eine App laufen, die einen bestimmten Chatbefehl nutzt. + * Versucht eine zweite App einen Chatbefehl zu registrieren, den eine andere + * App bereits nutzt, so wird ein Fehler geloggt und die App startet nicht bzw. fährt herunter. + * + * Die Struktur eines registrierten Chatbefehls ist: + * commandName: function (user, params, command) {} + * + * + *
    + *
  • commandName ist der Name der Funktion, wie sie aufgerufen wird (beispielsweise /commandname)
  • + *
  • user ist der Nutzer, der die Funktion aufgerufen hat
  • + *
  • params sind die Parameter, die der Nutzer hinter dem Befehl eingegeben hat (beispielsweise /commandname params)
  • + *
  • command ist der Name des Befehl selbst (beispielsweise commandName)
  • + *
+ */ + chatCommands?: { [commandName: string]: (user: User, params: string, command: string) => void }; +} + +/** + * Ermöglicht Zugriff auf Informationen zu Apps und Events zwischeneinander. + * + * Die Instanz von AppAccess erhält man über den KnuddelsServer + * mit KnuddelsServer.getAppAccess() + */ +declare class AppAccess { + /** + * Liefert die Instanz der eigenen App. + */ + getOwnInstance(): AppInstance; + /** + * Liefert die Instanzen aller anderen Apps, die gerade in diesem Channel laufen. + * @since AppServer 82904 + */ + getAllRunningAppsInChannel(includeSelf?: boolean): AppInstance[]; + /** + * Liefert die Instanzen aller anderen Apps, die gerade in diesem Channel laufen. + * @since AppServer 82904 + */ + getRunningAppInChannel(appId: string): (AppInstance|null); +} + +/** + * Repräsentiert den visuellen Inhalt einer Applikation, der Usern angezeigt werden soll. + */ +declare class AppContent { + /** + * Liefert den AppViewMode. + */ + getAppViewMode(): AppViewMode; + /** + * Liefert das HTMLFile, das beim Anlegen des AppContents + * genutzt wurde. + */ + getHTMLFile(): HTMLFile; + /** + * Liefert die Breite des AppContent. + */ + getWidth(): number; + /** + * Liefert die Höhe des AppContent. + */ + getHeight(): number; + /** + * Liefert die LoadConfiguration, mit der die Optik beim Laden des HTML User Interface beeinflusst werden kann. + */ + getLoadConfiguration(): LoadConfiguration; + /** + * Liefert einen AppContent, der das HTMLFile als Overlay oben rechts im Channel anzeigt. + */ + static overlayContent(htmlFile: HTMLFile, width: number, height: number): AppContent; + /** + * Liefert einen AppContent, der das HTMLFile als Overlay (200x350) oben rechts im Channel anzeigt. + */ + static overlayContent(htmlFile: HTMLFile): AppContent; + /** + * Liefert einen AppContent, der das HTMLFile im Applet/HTML-Chat + * als Popup (300x400) und auf Android als Fullscreen-View anzeigt. + */ + static popupContent(htmlFile: HTMLFile): AppContent; + /** + * Liefert einen AppContent, der das HTMLFile im Applet/HTML-Chat + * als Popup und auf Android als Fullscreen-View anzeigt. + */ + static popupContent(htmlFile: HTMLFile, width: number, height: number): AppContent; + /** + * Sendet Daten an alle Nutzer, die diesen AppContent geöffnet haben. + */ + sendEvent(type: string, data?: KnuddelsEvent): void; + /** + * Liefert eine Liste aller User, die diesen AppContent + * geöffnet haben. + */ + getUsers(): User[]; + /** + * Liefert eine Liste aller AppContentSessions, die dieses AppContent, + * die User gerade geöffnet haben. + */ + getSessions(): AppContentSession[]; + /** + * Ersetzt den AppContent, bei allen Usern, die diesen AppContent + * geöffnet haben durch den neuen AppContent. + * + *

Hinweis: Es können nur AppContent mit demselben AppViewMode + * zum Ersetzen genutzt werden. + */ + replaceWithAppContent(newAppContent: AppContent): void; + /** + * Entfernt diesen AppContent, bei allen Usern, die diesen AppContent + * geöffnet haben. + */ + remove(): void; + /** + * Fügt einen Listener hinzu, der aufgerufen wird, wenn jemand den AppContent schließt. + */ + addCloseListener(callback: { user: User; appContent: AppContent; }): void; +} + +/** + * Repräsentiert den visuellen Inhalt einer App, der einem User angezeigt wird. + */ +declare class AppContentSession { + /** + * Sendet Daten an den verbundenen Client. + */ + sendEvent(type: string, data?: KnuddelsEvent): void; + /** + * Liefert den AppViewMode. + */ + getAppViewMode(): AppViewMode; + /** + * Entfernt die AppContentSession beim verbundenen User. + */ + remove(): void; + /** + * Liefert den User. + */ + getUser(): User; + /** + * Liefert den verbundenen AppContent. + */ + getAppContent(): AppContent; +} + +/** + * Die Instanz von AppInfo zur laufenden App erhält man über die AppInstance + * mit appInstance.getAppInfo() + */ +declare class AppInfo { + /** + * Liefert die AppUid. + * Diese ist für jede Sub-Channel Instanz der App unterschiedlich. + * Wenn RootAppUid == AppUid dann ist dies die Root-App-Instanz. + */ + getAppUid(): number; + /** + * Liefert die RootAppUid. + * Diese ist für jede Sub-Channel Instanz der App gleich. + * Wenn RootAppUid == AppUid dann ist dies die Root-App-Instanz. + * + * Sie wird für den Link für Auszahlungen aus einem Knuddel-Account benötigt: /knuddelaccount payout:<RootAppUid>:<BETRAG> + */ + getRootAppUid(): number; + /** + * Liefert den in der Konfiguration eingestellten Namen der App. + */ + getAppName(): string; + /** + * Liefert die Version der App, die in der Konfiguration eingestellt wurde. + */ + getAppVersion(): string; + /** + * Liefert die eindeutige Id der App. + * Die appId setzt sich zusammen aus + *
    + *
  • id des Entwicklungsservers
  • + *
  • FTP-Nutzername
  • + *
  • Ordnername der App -> appKey
  • + *
+ */ + getAppId(): string; + /** + * Liefert den eindeutigen Key der App. + * Der appKey ist der Ordnername, in dem die App liegt. + */ + getAppKey(): string; + /** + * Liefert den Entwickler der App, falls die serverId knuddelsDE oder knuddelsDEV ist, ansonsten null. + */ + getAppDeveloper(): User; + /** + * Liefert die Liste der AppManager für diese App. Die Channelbesitzer zählen automatisch auch als AppManager. + */ + getAppManagers(): User[]; + /** + * Liefert den Steuersatz, der bei Auszahlung bereits genutzer Knuddel von einem + * KnuddelAccount an einen User + * anfällt. Die anfallenden Steuern werden bei Auszahlung vom BotUser + * abgezogen. + */ + getTaxRate(): number; + /** + * Liefert den KnuddelAmount, der an Steuern anfallen würde, + * wenn alle User jetzt all ihre Knuddel aus ihrem + * KnuddelAccount abheben würden. + */ + getTotalTaxKnuddelAmount(): KnuddelAmount; + /** + * Liefert den KnuddelAmount, der jetzt noch vom + * BotUser an KnuddelAccounts + * übertragen werden kann, so dass für alle Knuddel noch die Steuern bezahlt werden können. + */ + getMaxPayoutKnuddelAmount(): KnuddelAmount; +} + +/** + * Repräsentiert die Instanz einer App. + * + * Die eigene Instanz von AppInstance erhält man über das AppAccess-Objekt + * mit appAccess.getOwnInstance() + */ +declare class AppInstance { + /** + * Liefert die AppInfo. + */ + getAppInfo(): AppInfo; + /** + * Sendet ein App-Event an diese App-Instanz. + */ + sendAppEvent(type: string, data: KnuddelsEvent): void; + /** + * Informiert, ob die aktuelle AppInstanz eine Root-Instanz ist. + */ + isRootInstance(): boolean; + /** + * Liefert die Root-Instanz der aktuellen App-Instanz. + */ + getRootInstance(): RootAppInstance; + /** + * Liefert alle App-Instanzen dieser App in diesem Channel und Subchannels. + * Mit includeSelf = false kann man die eigene Instanz ausschließen. + */ + getAllInstances(includeSelf?: boolean): AppInstance[]; + /** + * Liefert den Startzeitpunkt dieser AppInstance. + */ + getStartDate(): Date; + /** + * Liefert die Namen der ChatCommands, die diese AppInstnce derzeit registriert hat. + */ + getRegisteredChatCommandNames(): (string[]|null); + /** + * Liefert den Namen des Channels in dem diese AppInstance läuft. + */ + getChannelName(): string; +} + +/** + * Jede App besitzt eine AppPersistence in der global für diese App + * Informationen gespeichert werden können. An die Instanz der AppPersistence gelangt man durch den Aufruf + * KnuddelsServer.getPersistence();. + */ +declare class AppPersistence extends Persistence { +} + +/** + * Eine Instanz eines AppProfileEntry repräsentiert einen von einer App erzeugen Profileintrag in Profilen von Usern. + */ +declare class AppProfileEntry { + /** + * Liefert den key für den die Topliste, die den Profileintrag erzeugt angelegt wurde. + */ + getKey(): string; + /** + * Liefert den getDisplayType + */ + getDisplayType(): ToplistDisplayType; + /** + * Liefert das Toplist-Objekt. + */ + getToplist(): Toplist; +} + +/** + * Mit einer Instanz von AppProfileEntryAccess kann eine App + * AppProfileEntry-Objekte (Profileinträge) erzeugen und verwalten. + * + * Die Instanz für die AppProfileEntryAccess erhält man über das KnuddelsServer-Objekt + * mit KnuddelsServer.getAppProfileEntryAccess() + * + *

Achtung: Derzeit darf eine App bis zu fünf AppProfileEntries haben. + *

Achtung: Profileinträge werden nur dann angezeigt, wenn der Channel sichtbar ist. + */ +declare class AppProfileEntryAccess { + /** + * Liefert die Liste aller AppProfileEntry-Objekte, die diese App erzeugt hat. + */ + getAllProfileEntries(): AppProfileEntry[]; + /** + * Liefert den AppProfileEntry für den übergebenen userPersistenceNumberKey. + */ + getAppProfileEntry(userPersistenceNumberKey: string): AppProfileEntry; + /** + * Erzeugt oder aktualisiert ein AppProfileEntry anhand der übergebenen Toplist + * und dem ToplistDisplayType und liefert den AppProfileEntry im Anschluss zurück. + * + * Profileinträge, die erzeugt werden, sind nur sichtbar, solange die App läuft und werden im Profil ausgeblendet, sofern die App aus ist. + */ + createOrUpdateEntry(toplist: Toplist, toplistDisplayType: ToplistDisplayType): AppProfileEntry; + /** + * Löscht den übergebenen AppProfileEntry. + */ + removeEntry(appProfileEntry: AppProfileEntry): void; +} + +/** + * Liefert Informationen über einen AppServer. + * + * Die Instanz von AppServerInfo erhält man über den KnuddelsServer + * mit KnuddelsServer.getAppServerInfo() + */ +declare class AppServerInfo extends ServerInfo { +} + +/** + * null + */ +declare class AppViewMode { + /** + * + */ + static readonly Overlay: AppViewMode; + /** + * Zum Öffnen eines Popups durch das HTML User Interface + */ + static readonly Popup: AppViewMode; +} + +/** + * Ein BotUser repräsentiert einen Nutzer, der für die App als Nutzer im Channel interagieren kann. + * + * Die Instanz für den Standard-BotUser erhält man über das KnuddelsServer-Objekt + * mit KnuddelsServer.getDefaultBotUser() + */ +declare class BotUser extends User { + /** + * Sendet eine öffentliche Nachricht in den Channel. + */ + sendPublicMessage(message: string): void; + /** + * Sendet eine öffentliche Handlung in den Channel. + * Dies funktioniert so, als ob der BotUser /me TEXT im Chat eingeben würde. + */ + sendPublicActionMessage(actionMessage: string): void; + /** + * Sendet eine private Nachricht an bestimmte Nutzer. + */ + sendPrivateMessage(message: string, users?: User[]): void; + /** + * Sendet eine persistente Nachricht an einen bestimmten Nutzer. + */ + sendPostMessage(topic: string, text: string, receivingUser?: User): void; + /** + * Transferiert eine bestimmte Anzahl Knuddel an einen Zielnutzer oder KnuddelAccount.

+ * Wichtiger Hinweis: Sollte die App versuchen mehr Knuddel zu transferieren, + * als sie besitzt, so wird der onError-Callback aufgerufen und die App transferiert so viele Knuddel, wie möglich. + * Zudem werden die Schulden für den Channelbesitzer gemerkt. Sobald sich der Channelbesitzer einloggt, erhält er einen Hinweis über offene Schulden + * und sollte diese direkt begleichen. + * Hat ein Channelbesitzer eine gewisse Menge Schulden angesammelt, so schalten wir alle Apps in diesem Channel ab. + *
Es können nur Knuddel transferiert werden zu Nutzern mit UserType.Human. + */ + transferKnuddel(receivingUserOrAccount: (User|KnuddelAccount), knuddelAmount: KnuddelAmount, + parameters?: { displayReasonText?: string; transferDisplayType?: KnuddelTransferDisplayType; + onSuccess?: () => void; onError?: (message: string) => void; }): void; +} + +/** + * Ein Channel ist ein Raum in dem die App läuft. + * + * Die Instanz für den Channel erhält man über das KnuddelsServer-Objekt + * mit KnuddelsServer.getChannel() + */ +declare class Channel { + /** + * Gibt Zugriff auf das ChannelConfiguration-Objekt des Channels. + */ + getChannelConfiguration(): ChannelConfiguration; + /** + * Gibt Zugriff auf das ChannelRestrictions-Objekt des Channels. + */ + getChannelRestrictions(): ChannelRestrictions; + /** + * Gibt Zugriff auf das ChannelDesign-Objekt des Channels. + * @since AppServer 87470, ChatServer 87470 + */ + getChannelDesign(): ChannelDesign; + /** + * Gibt Zugriff auf Nutzer, die gerade im Channel online sind. + */ + getOnlineUsers(...userType: UserType[]): User[]; + /** + * Liefert die Information, ob in diesem Channel Videos gestreamt werden können. + */ + isVideoChannel(): boolean; + /** + * Liefert die VideoChannelData des Channels. + */ + getVideoChannelData(): VideoChannelData; + /** + * Liefert den Namen des Channels. + */ + getChannelName(): string; + /** + * Liefert den Namen des Root-Channels (nur relevant, falls die App Tochterchannel haben kann). + */ + getRootChannelName(): string; + /** + * Liefert den ChannelTalkMode, in dem sich der Channel gerade befindet. + */ + getTalkMode(): ChannelTalkMode; + /** + * Liefert alle User, die bestimmte ChannelTalkPermissions haben. + */ + getAllUsersWithTalkPermission(...channelTalkPermission: ChannelTalkPermission[]): User[]; + /** + * Liefert die Information, ob der Channel sichtbar (true) oder unsichtbar (false) ist. + * @since AppServer 82202 + */ + isVisible(): boolean; +} + +/** + * Eine ChannelConfiguration erlaubt Zugriff auf verschiedene Details + * der Konfiguration des Channels, in dem die App läuft. + * + * Die Instanz für die ChannelConfiguration erhält man über das Channel-Objekt + * mit channel.getChannelConfiguration() + */ +declare class ChannelConfiguration { + /** + * Liefert das ChannelRights-Objekt des Channels. + */ + getChannelRights(): ChannelRights; + /** + * Liefert das ChannelInformation-Objekt des Channels. + */ + getChannelInformation(): ChannelInformation; +} + +/** + * Ermöglicht Zugriff auf Designeinstellungen des Channels. + * @since AppServer 87470, ChatServer 87470 + */ +declare class ChannelDesign { + /** + * Liefert die eingestellte Standard-Schriftgröße des Channels. + * @since AppServer 87470, ChatServer 87470 + */ + getDefaultFontSize(): number; + /** + * Liefert die eingestellte Standard-Schriftfarbe des Channels. + * @since AppServer 87470, ChatServer 87470 + */ + getDefaultFontColor(): Color; + /** + * Liefert die eingestellte Hintergrundfarbe des Channels. + * @since AppServer 87470, ChatServer 87470 + */ + getBackgroundColor(): Color; +} + +/** + * Ermöglicht Zugriff auf textuelle Channelinformationen und persistente Änderungen. + */ +declare class ChannelInformation { + /** + * Liefert das eingestellte Thema des Channels. + */ + getTopic(): string; + /** + * Aktualisiert das Thema das Channels. + */ + setTopic(topic: string, showMessage: boolean): void; +} + +/** + * Eine Instanz der Klasse ChannelJoinPermission wird als Rückgabewert + * der Methode App.mayJoinChannel(user) benötigt. + * + * Hiermit wird bestimmt, ob der anfragende Nutzer den Channel betreten darf. + * + * Erlauben mit ChannelJoinPermission.accepted() + * Verbieten mit ChannelJoinPermission.denied(denyReason) + */ +declare class ChannelJoinPermission { + /** + * Erzeugt ein ChannelJoinPermission-Objekt, das den Zugriff in den Channel erlaubt. + */ + static accepted(): ChannelJoinPermission; + /** + * Erzeugt ein ChannelJoinPermission-Objekt, das den Zugriff in den Channel verbietet. + */ + static denied(denyReason: string): ChannelJoinPermission; +} + +/** + * Eine Instanz von ChannelRestrictions ermöglicht es, aktuelle Informationen über Nutzungsbeschränkungen im Channel zu erhalten. + * + * Die Instanz für die ChannelRestrictions erhält man über das Channel-Objekt + * mit channel.getChannelRestrictions() + */ +declare class ChannelRestrictions { + /** + * Liefert alle User die im Channel derzeit für das Schreiben öffentlicher Nachrichten gesperrt sind. + */ + getMutedUsers(): User[]; + /** + * Liefert alle User die im Channel derzeit für das Nutzen + * von Farben, Textformatierung und Smileys in öffentlichen Nachrichten gesperrt sind. + */ + getColorMutedUsers(): User[]; + /** + * Liefert alle User die für das Betreten des Channel derzeit gesperrt sind. + */ + getLockedUsers(): User[]; +} + +/** + * Die Instanz für die ChannelRights erhält man über das ChannelConfiguration-Objekt + * mit channelConfiguration.getChannelRights() + */ +declare class ChannelRights { + /** + * Liefert die Liste aller Channelbesitzer. In öffentlichen Channels sind dies alle hauptzuständigen betreuenden Mitglieder. (HZA/HZE) + */ + getChannelOwners(): User[]; + /** + * Liefert die Liste aller Channel-Moderatoren. + */ + getChannelModerators(): User[]; + /** + * Liefert die Liste aller Event-Moderatoren. + */ + getEventModerators(): User[]; +} + +/** + * ChannelTalkMode repräsentiert das den Gesprächsmodus im Channel. + * + * Die Instanz für die ChannelTalkMode erhält man über das Channel-Objekt + * mit channel.getTalkMode() + */ +declare class ChannelTalkMode { + /** + * Jeder darf gerade im Channel schreiben. + */ + static readonly Everyone: ChannelTalkMode; + /** + * Nur Personen, die besondere Rederechte haben dürfen gerade im Channel schreiben. + */ + static readonly OnlyWithTalkPermission: ChannelTalkMode; + /** + * Nur Personen, die besondere Rederechte haben dürfen gerade im Channel schreiben. + * Die Nachrichten aller anderen Nutzer werden gefiltert und ggf. von den Moderatoren zugelassen. + */ + static readonly FilteredByModerators: ChannelTalkMode; +} + +/** + * ChannelTalkPermission repräsentiert das Rederecht eines User + * im Channel. + */ +declare class ChannelTalkPermission { + /** + * Der User ist gerade nicht im Channel, + * daher ist die ChannelTalkPermission nicht bekannnt. + */ + static readonly NotInChannel: ChannelTalkPermission; + /** + * Der User hat keine speziellen Rederechte. + * Beim ChannelTalkMode Default können diese User + * Nachrichten verfassen: + */ + static readonly Default: ChannelTalkPermission; + /** + * Der User kann eine öffentliche Nachricht verfassen. Danach wechselt die + * ChannelTalkPermission automatisch auf Default. + */ + static readonly TalkOnce: ChannelTalkPermission; + /** + * Der User kann permanent öffentliche Nachrichten verfassen. + */ + static readonly TalkPermanent: ChannelTalkPermission; + /** + * Der User ist VIP und kann öffentliche Nachrichten verfassen, + * die farbig und groß dargestellt werden. + */ + static readonly VIP: ChannelTalkPermission; + /** + * Der User ist VIP und kann öffentliche Nachrichten verfassen, + * die farbig und groß dargestellt werden. Moderatoren haben zudem weitere Möglichkeiten, die in der + * Anleitung zum Moderationssystem + * nachgelesen werden können. + */ + static readonly Moderator: ChannelTalkPermission; +} + +/** + * Liefert Informationen über einen ChatServer. + * + * Die Instanz von ChatServerInfo erhält man über den KnuddelsServer + * mit KnuddelsServer.getChatServerInfo() + */ +declare class ChatServerInfo extends ServerInfo { + /** + * Liefert die Information, ob dieser Chat-Server ein Test-System ist. + */ + isTestSystem(): boolean; +} + +/** + * Klasse, die es ermöglicht den Client innerhalb des HTML User Interface zu steuern und Daten an den Server zu senden. + */ +declare class Client { + /** + * Schließt das HTML User Interface. + */ + static close(): void; + /** + * Sendet ein Event zum Server, das mit dem AppHook onEventReceived in der App + * abgefangen werden kann. + */ + static sendEvent(type: string, data: KnuddelsEvent): void; + /** + * Sagt dem Chatserver, dass dieser Befehl für den Nutzer, der das HTML User Interface sieht, ausgeführt werden soll. + * Ist der Befehl auf einer Whitelist vom Server, so wird er sofort ausgeführt. Im anderen Falle sieht der Nutzer einen + * Link zum Bestätigen, mit dem er die Aktion starten kann. + * + * Derzeit sind diese Befehle auf der Whitelist: w, info, wc, top, h, dice, d, diceo, w2, serverpp, knuddelaccount, + * /tf-insert, /tf-inserts, /tf-insertb, /tf-insertsb, /tf-override, /tf-overrides, /tf-overrideb, /tf-overridesb, /autotype + */ + static executeSlashCommand(command: string): void; + /** + * Bindet eine Javascript-Datei ein und sorgt dafür, dass immer die aktuellste Version vom Server geladen wird. + */ + static includeJS(...files: string[]): void; + /** + * Registriert sich für ein bestimmtes Event, das vom Server mittels User/sendEvent:method oder vom Client via Client/dispatchEvent:method verschickt wurde. + */ + static addEventListener(type: string, callback: (event: {type: string, data: KnuddelsEvent}) => void): void; + /** + * Sendet ein bestimmtes Event, so dass alle mit Client/addEventListener:method registrierten Listener aufgerufen werden. + */ + static dispatchEvent(event: Client.Event): void; + /** + * Entfernt alle Event-Listener für einen bestimmten Event-Typ. + */ + static removeEventListener(type: string): void; + /** + * Bindet eine CSS-Datei ein und sorgt dafür, dass immer die aktuellste Version vom Server geladen wird. + */ + static includeCSS(...files: string[]): void; + /** + * Spielt einen Sound ab. Der angegebene Dateiname kann hierbei entweder absolut oder relativ zur angezeigten HTML-Datei sein. + * Bisher können nur Dateien mit Wave-Format zuverlässig abgespielt werden. + */ + static playSound(fileName: string): void; + /** + * Lädt einen Sound herunter, damit die Datei später ohne Wartezeit abgespielt werden kann. + * (Android only) + * Der angegebene Dateiname kann hierbei entweder absolut oder relativ zur angezeigten HTML-Datei sein. + */ + static prefetchSound(fileName: string): void; + /** + * Gibt einen Sound wieder frei, der in nächster Zeit vom Client nicht mehr gebraucht wird. + * (Android only) + * Der angegebene Dateiname kann hierbei entweder absolut oder relativ zur angezeigten HTML-Datei sein. + */ + static freeSound(fileName: string): void; + /** + * Liefert den HostFrame des aktuellen Inhalts. + */ + static getHostFrame(): Client.HostFrame; + /** + * Liefert den Nicknamen des Users, der gerade dieses HTML User Interface angezeigt bekommt. + */ + static getNick(): string; + /** + * Liefert den aktuellen ClientType des Nutzers, der gerade dieses HTML User Interface angezeigt bekommt. + */ + static getClientType(): ClientType; + /** + * Liefert die Id, die beim Laden von Skripten und Stylesheets an die URL angehängt wird, um sicherzustellen, dass eine neue Version + * der Datei vom Server geholt wird, statt die Datei aus dem Cache zu laden. + * + * Diese Id kann beim Einbinden eigener Ressourcen zum selben Zweck genutzt werden. + */ + static getCacheInvalidationId(): string; + /** + * Beinhaltet die JSON-Daten, die beim Erstellen des HTMLFile übergeben wurden. + */ + static pageData: Json; +} + +/** + * Klasse, mit der clientseitige Farbobjekte erstellt werden können. + */ +declare module Client { + export class Color { + /** + * Erzeugt ein Color-Objekt mit RGB-Werten. + */ + static fromRGB(red: number, green: number, blue: number): Color; + /** + * Erzeugt ein Color-Objekt aus einem HexString. + */ + static fromHexString(colorString: string): Color; + /** + * Liefert den Rot-Anteil der Farbe als Zahl zwischen 0 und 255. + */ + getRed(): number; + /** + * Liefert den Grün-Anteil der Farbe als Zahl zwischen 0 und 255. + */ + getGreen(): number; + /** + * Liefert den Blau-Anteil der Farbe als Zahl zwischen 0 und 255. + */ + getBlue(): number; + /** + * Liefert die Farbe als in CSS nutzbaren HexString. + */ + asHexString(): string; + } +} + +/** + * Klasse, die es ermöglicht ein Event via Client/dispatchEvent:method zu versenden. + */ +declare module Client { + export class Event { + /** + * Erzeugt ein Event. + */ + constructor(type: string, data: KnuddelsEvent); + } +} + +/** + * Klasse, die es ermöglicht den Inhalte zu steuern, die im Bereich liegen, der das HTML User Interface hostet. + */ +declare module Client { + export class HostFrame { + /** + * Setzt den Titel der Seite im gezoomten Modus (nur Android). + */ + setTitle(newTitle: string): void; + /** + * Ändert die sichtbare Hintergrundfarbe des Hostframes animiert. (Android-only) + */ + setBackgroundColor(newColor: Color, durationMillis?: number): void; + /** + * Setzt die Icons, die als Fenster-Icon angezeigt werden sollen. (Applet-only, nur mit AppViewMode.Popup) + * Die Bilder müssen von groß nach klein sortiert sein. Die größeren Bilder werden (je nach System) automatisch dann eingesetzt, + * wenn größere Bilder benötigt werden (z.B. in der Task-Leiste, oder beim Alt+Tab Fenster-Wechsel). + * @since Applet: 9.0bwj, AppServer: 84904 + */ + setIcons(...path: string[]): void; + /** + * Setzt, ob das Fenster resizable ist. (Applet-only, nur mit AppViewMode.Popup) + */ + setResizable(resizable: boolean): void; + /** + * Bringt das Fenster der App (App-Popup bzw. Chat-Fenster) in den Vordergrund. (Applet-only) + * @since Applet: 9.0bwj, AppServer: 84904 + */ + focus(): void; + /** + * Ändert die Größe des App-Fensters (AppViewMode.Popup) bzw. App-Overlays (AppViewMode.Overlay). + * @since Applet: 9.0bwj, AppServer: 84516 + */ + setSize(width: number, height: number): void; + } +} + +/** + * ClientType repräsentiert die Art der Chat-Verbindung des Users. + * + * Eine Instanz von ClientType erhält man über das User-Objekt + * mit user.getClientType() + */ +declare class ClientType { + /** + * Der User ist mit dem Java Applet im Chat. + */ + static readonly Applet: ClientType; + /** + * Der User ist mit dem Browser im Chat (Mini-Chat, HTML-Chat). + */ + static readonly Browser: ClientType; + /** + * Der User ist mit der Android-App im Chat. + */ + static readonly Android: ClientType; + /** + * Der User ist mit der iOS-App im Chat. + */ + static readonly IOS: ClientType; + /** + * Der User ist nicht im Chat. + */ + static readonly Offline: ClientType; +} + +/** + * Klasse, mit der serverseitige Farbobjekte erstellt werden können. + */ +declare class Color { + /** + * Erzeugt ein serverseitiges Color-Objekt mit RGB-Werten. + * Als Alpha-Wert wird automatisch 255 genutzt. + */ + static fromRGB(red: number, green: number, blue: number): Color; + /** + * Erzeugt ein serverseitiges Color-Objekt mit RGBA-Werten. + */ + static fromRGBA(red: number, green: number, blue: number, alpha: number): Color; + /** + * Liefert den Alpha-Wert der Farbe als Zahl zwischen 0 und 255. + */ + getAlpha(): number; + /** + * Liefert den Blau-Anteil der Farbe als Zahl zwischen 0 und 255. + */ + getBlue(): number; + /** + * Liefert den Grün-Anteil der Farbe als Zahl zwischen 0 und 255. + */ + getGreen(): number; + /** + * Liefert den Rot-Anteil der Farbe als Zahl zwischen 0 und 255. + */ + getRed(): number; + /** + * Liefert die Farbe als KCode zurück. + */ + toKCode(): string; + /** + * Liefert die numerische Repräsentation der Farbe zurück. + */ + asNumber(): number; + /** + * Erzeugt ein serverseitiges Color-Objekt aus der numerischen Repräsentation einer Farbe. + */ + static fromNumber(value: number): Color; +} + +/** + * Eine Instanz von Dice repräsentiert die Anzahl an Würfeln von einerm bestimmten Typ. + */ +declare class Dice { + /** + * Erzeugt ein Dice-Objekt mit der übergebenen Anzahl Würfel und Augenzahl. + */ + constructor(count: number /* optional */, value: number); + /** + * Liefert die Anzahl der Würfel. + */ + getAmount(): number; + /** + * Liefert die Anzahl der Seiten der Würfel. + */ + getNumberOfSides(): number; +} + +/** + * Eine Instanz von DiceConfiguration repräsentiert eindeutig eine Konfiguration zum würfeln. + * Wurde gewürfelt, so können die Konfigurationen verglichen werden, um zu prüfen, ob exakt die Würfel + * gewürfelt wurden, die gewürfelt werden sollten. + */ +declare class DiceConfiguration { + /** + * Informiert, ob es sich um einen offenen Würfelwurf handelt. + * Offene Würfelwürfe sind speziell. Falls die Augenzahl des Würfels die Maximalsumme zeigt, + * so wird noch einmal gewürfelt und die neue Zahl dazu addiert, solange bis der Würfel + * nicht mehr die Maximalsumme zeigt. + * + * Beispiel: /diceo 1w4 -> 4 -> 4 -> 3 = 11 + */ + isUsingOpenThrow(): boolean; + /** + * Informiert darüber, ob die Würfel privat geworfen worden sind. + * Würfelwürfe zählen als privat, wenn am Ende des Würfelbefehls ein Ausrufezeichen steht. + * Beispiel: /dice 10w2! + */ + isUsingPrivateThrow(): boolean; + /** + * Liefert ein Array mit Würfeln, mit denen gewürfelt wurde. + */ + getDices(): Dice[]; + /** + * Vergleicht, ob zwei Konfigurationen inhaltlich identisch sind + */ + equals(diceConfiguration: DiceConfiguration): boolean; + /** + * Liefert den Befehl, der im Chat eingegeben werden kann, um einen Wurf auszuführen, + * der zur DiceConfiguration passt. + * @since AppServer 82248 + */ + getChatCommand(): string; +} + +/** + * Eine Instanz einer DiceConfigurationFactory kann zur Unterstützung genutzt werden, um eine + * DiceConfiguration zu erzeugen. + */ +declare class DiceConfigurationFactory { + /** + * Fügt der Konfiguration einen Würfel hinzu. + */ + addDice(dice: Dice): void; + /** + * Liefert die Anzahl der Würfel, die zur Konfiguration gehören. + */ + computeCurrentDiceCount(): number; + /** + * Setzt die Information, ob ein offener Wurf oder ein normaler Wurf stattfinden soll. + * Offene Würfelwürfe sind speziell. Falls die Augenzahl des Würfels die Maximalsumme zeigt, + * so wird noch einmal gewürfelt und die neue Zahl dazu addiert, solange bis der Würfel + * nicht mehr die Maximalsumme zeigt. + * + * Beispiel: /diceo 1w4 -> 4 -> 4 -> 3 = 11 + */ + setUseOpenThrow(shouldUseOpenThrow: boolean): void; + /** + * Setzt die Information, ob der Würfelwurf privat stattfinden soll. + */ + setShouldUsePrivateThrow(shouldUsePrivateThrow: boolean): void; + /** + * Liefert die erzeugte Würfelkonfiguration. + */ + getDiceConfiguration(): DiceConfiguration; + /** + * Erzeugt eine Würfelkonfiguration. + */ + static fromString(diceConfigurationString: string): DiceConfiguration; +} + +/** + * Wird in der App die Methode onUserDiced überschrieben, so erhält diese bei jedem Würfelwurf ein DiceEvent. + * Ein DiceEvent ermöglicht einem detaillierte Informationen rund um diesen Würfelwurf in Erfahrung zu bringen. + */ +declare class DiceEvent { + /** + * Liefert den Nutzer, der gewürfelt hat. + */ + getUser(): User; + /** + * Liefert das DiceResult des Würfelwurfs. + */ + getDiceResult(): DiceResult; +} + +/** + * Ein DiceResult beinhaltet konkrete Informationen über einen Würfelwurf. + */ +declare class DiceResult { + /** + * Liefert die Konfiguration mit der gewürfelt wurde. + */ + getDiceConfiguration(): DiceConfiguration; + /** + * Liefert ein Array mit Details zu den einzelnen Ergebnissen pro Würfeltyp. + */ + getSingleDiceResults(): SingleDiceResult[]; + /** + * Liefert die Summe der Augenzahlen aller Würfel + */ + totalSum(): number; +} + +/** + * Die Instanz einer Domain beinhaltet alle relevanten Informationen zur Domain. + */ +declare class Domain { + /** + * Liefert ein den Domain-Namen der aktuellen Domain. + */ + getDomainName(): string; +} + +/** + * Die Instanz von ExternalServerAccess erhält man über die KnuddelsServer.getExternalServerAccess(). + * Damit der Zugriff auf einen externern Server funktioniert, muss auf dem Server eine Datei knuddelsAccess.txt abgelegt werden, die die FTP-User-ID des Entwicklers enthält. + */ +declare class ExternalServerAccess { + /** + * Liefert eine Liste aller zugreifbaren Domains + */ + getAllAccessibleDomains(): Domain[]; + /** + * Prüft den Zugriff auf eine bestimmte URL. Wird je Kombination von "Protokoll + Host + Port" geprüft.
+ * Beispiel: http://www.example.de:8080 + */ + canAccessURL(urlString: string): boolean; + /** + * Macht einen GET-Request auf die übergebene URL und liefert den Inhalt zurück. + * Diese Methode ist eine Convenience-Methode für externalServerAccess.callURL(). + */ + getURL(urlString: string, parameters?: { onSuccess?: (responseData: string, externalServerResponse: ExternalServerResponse) => void; + onFailure?: (responseData: string, externalServerResponse: ExternalServerResponse) => void; }): void; + /** + * Macht einen POST-Request auf die übergebene URL und liefert den Inhalt zurück. + * Diese Methode ist eine Convenience-Methode für externalServerAccess.callURL(). + */ + postURL(urlString: string, parameters?: { onSuccess?: (responseData: string, externalServerResponse: ExternalServerResponse) => void; + onFailure?: (responseData: string, externalServerResponse: ExternalServerResponse) => void; data?: Json; }): void; + /** + * Macht einen GET-Request auf die übergebene URL. Im Gegensatz zum GET-Request wird der Inhalt der Webseite wird nicht ausgelesen. + * Aus diesem Grund ist diese Methode schneller. + * Diese Methode ist eine Convenience-Methode für externalServerAccess.callURL(). + */ + touchURL(urlString: string, parameters?: { onSuccess?: (responseData: string, externalServerResponse: ExternalServerResponse) => void; + onFailure?: (responseData: string, externalServerResponse: ExternalServerResponse) => void; }): void; + /** + * Macht einen Request auf die übergebene URL. + */ + callURL(urlString: string, parameters?: { onSuccess?: (responseData: string, externalServerResponse: ExternalServerResponse) => void; + onFailure?: (responseData: string, externalServerResponse: ExternalServerResponse) => void; method?: ("GET" | "POST"); data?: Json; }): void; +} + +/** + * Die Instanz von ExternalServerResponse erhält in den onSuccess- und onFailure-Callbacks der Methoden von + * ExternalServerAccess. Es enthält alle notwendigen Daten zum Verarbeiten. + */ +declare class ExternalServerResponse { + /** + * Liefert die abgefragte URL. + */ + getURLString(): string; + /** + * Liefert den HTTP-Statuscode der Seite. + */ + getResponseCode(): number; + /** + * Liefert ein Objekt, das die Headerdaten der Antwort enthält. + */ + getHeaderFields(): { [key: string]: string[] }; +} + +/** + * Gender repräsentiert das Geschlecht eines User. + */ +declare class Gender { + /** + * Das Geschlecht ist männlich. + */ + static readonly Male: Gender; + /** + * Das Geschlecht ist weiblich. + */ + static readonly Female: Gender; + /** + * Das Geschlecht ist nicht bekannt. + */ + static readonly Unknown: Gender; +} + +/** + * Repräsentiert eine HTML-Datei, die auf dem Server im Ordner /www liegt. + */ +declare class HTMLFile { + /** + * + */ + constructor(assetPath: string, pageData?: Json); + /** + * Liefert den Pfad, der beim Anlegen der HTMLFile-Instanz genutzt wurde. + */ + getAssetPath(): string; + /** + * Liefert die pageData, die beim Anlegen der HTMLFile-Instanz genutzt wurden. + */ + getPageData(): Json; +} + +/** + * Eine Instanz von KnuddelAccount ermöglicht den Zugriff auf die freigegebenen Knuddel + * eines bestimmten User. Knuddel können abgezogen und addiert werden. + */ +declare class KnuddelAccount { + /** + * Liefert den KnuddelAmount eines Users, + * über den die App gerade frei verfügen kann. + */ + getKnuddelAmount(): KnuddelAmount; + /** + * Liefert den KnuddelAmount aus dem KnuddelAccount, + * der bereits von der App genutzt wurde. + * Beim Auszahlen dieser Knuddel aus dem KnuddelAccount an den + * User fallen Steuern an. + */ + getKnuddelAmountUsed(): KnuddelAmount; + /** + * Liefert den KnuddelAmount aus dem KnuddelAccount, + * der noch nicht von der App genutzt wurde. + * Beim Auszahlen dieser Knuddel aus dem KnuddelAccount an den + * User fallen keine Steuern an. + */ + getKnuddelAmountUnused(): KnuddelAmount; + /** + * Liefert die Summe aller Transfers, die die App an diesen KnuddelAccount bzw. User überwiesen hat. + */ + getTotalKnuddelAmountAppToUser(): KnuddelAmount; + /** + * Liefert die Summe aller Transfers, die die App von diesem KnuddelAccount bzw. User abgebucht/erhalten hat. + */ + getTotalKnuddelAmountUserToApp(): KnuddelAmount; + /** + * Liefert die Information, ob in diesem Moment genug Knuddel verfügbar sind. + */ + hasEnough(knuddelAmount: KnuddelAmount): boolean; + /** + * Liefert den Nutzer, dem der KnuddelAccount gehört. + */ + getUser(): User; + /** + * Versucht eine bestimmte Menge Knuddel zu verwenden. Dies ist nur möglich, wenn der User auf seinem KnuddelAccount + * genug Knuddel besitzt und online im Channel ist. + * Vom KnuddelAccount des Besitzer des Channel können Knuddel auch abgebucht werden, wenn dieser nicht im Channel online ist. + * + * Ist das Event App.onBeforeKnuddelReceived implementiert, so wird diese direkt nach dem use aufgerufen, + * um zu entscheiden, ob die Knuddel angenommen werden sollen. + * + *

Hinweis: Knuddel an einen Nutzer senden kannst du mit der Methode BotUser/transferKnuddel:method. + */ + use(knuddelAmount: KnuddelAmount, displayReasonText: string, parameters?: { transferReason?: string; onError?: (message: string) => void; onSuccess?: () => void; }): void; +} + +/** + * Eine Instanz von KnuddelAmount repräsentiert eine bestimmte Anzahl von Knuddel. + */ +declare class KnuddelAmount { + /** + * Erzeugt eine Instanz von KnuddelAmount mit der Anzahl Knuddel. + */ + constructor(knuddel: number); + /** + * Erzeugt eine Instanz von KnuddelAmount mit einer bestimmten Cent-Anzahl. + */ + static fromCents(knuddel: number): KnuddelAmount; + /** + * Erzeugt eine Instanz von KnuddelAmount mit einer bestimmten Knuddel-Anzahl. + */ + static fromKnuddel(knuddel: number): KnuddelAmount; + /** + * Liefert die Anzahl der Knuddel in KnuddelCent zurück. + */ + getKnuddelCents(): number; + /** + * Gibt den Wert der Knuddel als Zahl zurück. + */ + asNumber(): number; + /** + * Liefert eine negierte Kopie des KnuddelAmount zurück. + */ + negate(): KnuddelAmount; + /** + * Liefert die Information, ob der Knuddelwert unter 0 ist. + */ + isNegative(): boolean; +} + +/** + * Repräsentiert einen KnuddelPot. + * Ein KnuddelPot kann nur durch Factory-Methoden des KnuddelsServer erzeugt werden: + * KnuddelsServer/createKnuddelPot:method. + * + * Wird die App heruntergefahren, so werden alle KnuddelPots, die nicht gesealt sind automatisch refunded. + */ +declare class KnuddelPot { + /** + * Liefert die id des KnuddelPot. + */ + getId(): number; + /** + * Liefert den Status des KnuddelPot. + */ + getState(): KnuddelPotState; + /** + * Liefert den beim Kreieren des KnuddelPots festgelegten KnuddelAmount, den jeder Teilnehmer zahlen muss. + */ + getKnuddelAmountPerParticipant(): KnuddelAmount; + /** + * Liefert den KnuddelAmount, der bisher insgesamt in den KnuddelPot eingezahlt wurde. + */ + getKnuddelAmountTotal(): KnuddelAmount; + /** + * Liefert die Liste der Teilnehmer, die bisher in den KnuddelPot eingezahlt haben. + */ + getParticipants(): User[]; + /** + * Liefert den höchsten Multiplikator, der gültig ist. + */ + getMaxFeeMultiplier(): number; + /** + * Setzt den BotUser, der den Anteil der Einzahlungen nach dem Spiel erhält + * und den Anteil, vom Gesamtpot, den er erhalten soll. + */ + setFee(feeUser: BotUser, feeMultiplier: number): void; + /** + * Liefert den mit KnuddelPot/setFee:method gesetzten BotUser an den die Gebühr ausbezahlt wird. + */ + getFeeUser(): User; + /** + * Liefert den mit KnuddelPot/setFee:method gesetzten Multiplikator der Gebühr. + */ + getFeeMultiplier(): number; + /** + * Versiegelt den KnuddelPot, sodass keine weiteren Einzahlungen vorgenommen + * werden können und Gewinne ausgeschüttet werden können. + */ + seal(): void; + /** + * Bezahlt alle Einsätze an die Teilnehmer zurück und informiert mit dem übergeben Text über den Grund. + */ + refund(reason?: string): void; + /** + * Fügt einen Gewinner in die Liste der Gewinner hinzu. + * Der zweite Parameter ist die Gewichtung mit der ausgezahlt werden soll. + * Wird der Parameter weggelassen, so ist er automatisch 1. + */ + addWinner(user: User, weight?: number): void; + /** + * Zahlt den KnuddelPot an die mit addWinner gesetzten Gewinner aus. + */ + payout(text?: string): void; +} + +/** + * Repräsentiert den Status eines KnuddelPot. + */ +declare class KnuddelPotState { + /** + * Der KnuddelPot ist geöffnet und kann neue Teilnehmer annehmen. + */ + static readonly Open: KnuddelPotState; + /** + * Der KnuddelPot ist versiegelt und kann keine neuen Teilnehmer annehmen. + */ + static readonly Sealed: KnuddelPotState; + /** + * Der KnuddelPot ist beendet und die Knuddel bereits ausgezahlt. + */ + static readonly Closed: KnuddelPotState; +} + +/** + * Ein KnuddelTransfer ist ein Container-Objekt für die Daten, die bei einer Knuddel-Transaktion von einem User + * an eine App anfallen. + * + * Implementiert man den App-Hook onBeforeKnuddelReceived, so kann man dort entscheiden, ob man den KnuddelTransfer + * annimmt oder ablehnt. + */ +declare class KnuddelTransfer { + /** + * Liefert den User, der den KnuddelTransfer ausgelöst hat. + */ + getSender(): User; + /** + * Liefert den BotUser, der die Knuddel des KnuddelTransfer erhält, + * wenn dieser mit accept() angenommen wurde. + */ + getReceiver(): BotUser; + /** + * Liefert die Anzahl der Knuddel, die mit diesem Transfer überwiesen werden. + */ + getKnuddelAmount(): KnuddelAmount; + /** + * Liefert den Grund für den Transfer, der bei der Überweisung angegeben wurde mit + * /appknuddel BOTNICK:KNUDDEL:GRUND. + */ + getTransferReason(): string; + /** + * Lehnt die Knuddel aus dem KnuddelTransfer ab und sendet sie zurück an den Absender. + * Als Grund sieht der Absender den übergebenen reason. + * + * Diese Methode wirft eine Exception, wenn sie auf einen bereits verarbeiteten Transfer aufgerufen wird. + * Sie kann nur erfolgreich aus dem AppHook onBeforeKnuddelReceived aufgerufen werden. + * + * In der Methode onBeforeKnuddelReceived kann genau ein Aufruf einer dieser drei Methoden gemacht werden: + * KnuddelTransfer/accept:method, + * KnuddelTransfer/addToPot:method, + * KnuddelTransfer/reject:method + */ + reject(reason: string): void; + /** + * Nimmt die Knuddel aus dem KnuddelTransfer an und übergibt sie an den BotUser, + * der mit getReceiver() abgefragt werden kann. + * + * Diese Methode wirft eine Exception, wenn sie auf einen bereits verarbeiteten Transfer aufgerufen wird. + * Sie kann nur erfolgreich aus dem AppHook onBeforeKnuddelReceived aufgerufen werden. + * In der Methode onBeforeKnuddelReceived kann genau ein Aufruf einer dieser drei Methoden gemacht werden: + * + * KnuddelTransfer/accept:method, + * KnuddelTransfer/addToPot:method, + * KnuddelTransfer/reject:method + */ + accept(): void; + /** + * Liefert die Information, ob ein bestimmter KnuddelTransfer zu einem KnuddelPot hinzugefügt werden kann. + */ + canAddToPot(pot: KnuddelPot): boolean; + /** + * Nimmt die Knuddel aus dem KnuddelTransfer an und übergibt sie an den übergebenen KnuddelPot. + * + * Diese Methode funktioniert analog zu KnuddelTransfer/accept:method, nur dass die Knuddel im KnuddelPot statt beim BotUser landen. + * + * Diese Methode wirft eine Exception, wenn sie auf einen bereits verarbeiteten Transfer aufgerufen wird. + * Sie kann nur erfolgreich aus dem AppHook onBeforeKnuddelReceived aufgerufen werden. + * + * In der Methode onBeforeKnuddelReceived kann genau ein Aufruf einer dieser drei Methoden gemacht werden: + * KnuddelTransfer/accept:method, + * KnuddelTransfer/addToPot:method, + * KnuddelTransfer/reject:method + */ + addToPot(knuddelPot: KnuddelPot): void; + /** + * Liefert die Information, ob der KnuddelTransfer bereits verarbeitet wurde. + * Falls die Methode false zurückliefert muss noch entschieden werden, ob der + * KnuddelTransfer angenommen oder abgelehnt wird. + */ + isProcessed(): boolean; +} + +/** + * KnuddelTransferDisplayType repräsentiert die Art der Darstellung einer Knuddel-Überweisung. + */ +declare class KnuddelTransferDisplayType { + /** + * Nachricht wird öffentlich angezeigt. + */ + static readonly Public: KnuddelTransferDisplayType; + /** + * Nachricht wird privat angezeigt. + */ + static readonly Private: KnuddelTransferDisplayType; + /** + * Nachricht wird als /m zugestellt. + */ + static readonly Post: KnuddelTransferDisplayType; +} + +/** + * KnuddelsServer ist die 'Einstiegsklasse'. Mit den statischen Methoden des KnuddelsServer erhält man Zugriff auf viele + * Objekte und Klassen, die im Verlauf der App-Entwicklung benötigt werden. + */ +declare class KnuddelsServer { + /** + * Liefert den BotUser, der standardmäßig zur App gehört. + */ + static getDefaultBotUser(): BotUser; + /** + * Liefert die AppPersistence, mit der sich Zahlen, Strings und Javascript-Objekte langfristig und über die Session einer App hinaus gespeichert werden können. + */ + static getPersistence(): AppPersistence; + /** + * Liefert den Channel in dem die App läuft. + */ + static getChannel(): Channel; + /** + * Liefert das UserAccess-Objekt, über das + * User zugreifbar werden. + */ + static getUserAccess(): UserAccess; + /** + * Liefert ein ExternalServerAccess-Objekt, mit dem + * andere Server angesteuert werden können. + */ + getExternalServerAccess(): ExternalServerAccess; + /** + * Aktualisiert die Liste der genutzten Hooks. Werden zur Laufzeit chatCommands oder App-Hooks (wie mayJoinChannel) dynamisch erzeugt oder gelöscht, so muss danach refreshHooks() + * aufgerufen werden, damit diese Änderung wirksam wird. + */ + static refreshHooks(): void; + /** + * Liefert den Standard-Logger für diese App. Alles, was geloggt wird, wird vom Nutzer "App-Logs" als private Nachricht zugestellt. + */ + static getDefaultLogger(): Logger; + /** + * Liefert den Pfad eines Bildes zur Integration in der eigenen App. + * Alle Bilder, die im Ordner /www in der App abgelegt werden können hier referenziert werden. + */ + static getFullImagePath(imageName: string): string; + /** + * Liefert den Pfad eines Systembildes zur Integration in der eigenen App. + * Alle Bilder, die unter http://apps4.knuddels.biz/kimg/ + * erreichbar sind können hier referenziert werden. + */ + static getFullSystemImagePath(imageName: string): string; + /** + * Liefert die Informationen über den ChatServer auf dem die App läuft. + */ + static getChatServerInfo(): ChatServerInfo; + /** + * Liefert die Informationen über den AppServer auf dem die App läuft. + */ + static getAppServerInfo(): AppServerInfo; + /** + * Liefert das AppAccess-Object. + */ + static getAppAccess(): AppAccess; + /** + * Erzeugt einen KnuddelPot. + * + * Ist ein KnuddelPot 30 Minuten nach dem Erzeugen noch nicht gesealt, + * so wird vom Server automatisch ein KnuddelPot/refund:method ausgelöst. + */ + static createKnuddelPot(knuddelAmount: KnuddelAmount, params?: { payoutTimeoutMinutes?: number; shouldSealPot?: (pot: KnuddelPot) => boolean; onPotSealed?: (pot: KnuddelPot) => void; }): KnuddelPot; + /** + * Liefert den KnuddelPot mit der angegeben id. + */ + static getKnuddelPot(id: number): (KnuddelPot|null); + /** + * Liefert alle für die App noch verwaltbaren KnuddelPot-Objekte. + */ + static getAllKnuddelPots(): KnuddelPot[]; + /** + * Liefert das ToplistAccess-Objekt, über das + * Toplisten erzeugt und verwaltet werden können. + */ + static getToplistAccess(): ToplistAccess; + /** + * Liefert das AppProfileEntryAccess-Objekt, über das + * App-Profileinträge erzeugt und verwaltet werden können. + */ + static getAppProfileEntryAccess(): AppProfileEntryAccess; +} + +/** + * Mit einer Instanz einer LoadConfiguration kann gestaltet werden, wie der Inhalt des HTML User Interface aussieht, bevor es fertig geladen ist. + */ +declare class LoadConfiguration { + /** + * Setzt die Farbe des Hintergrundes vom Loading-View, der angezeigt wird, während das HTML User Interface lädt. (standardmäßig weiß) + */ + setBackgroundColor(color: Color): void; + /** + * Setzt das Hintergrundbild vom Loading-View, das angezeigt wird, während das HTML User Interface lädt. (standardmäßig nicht gesetzt) + */ + setBackgroundImage(imageUrl: string): void; + /** + * Setzt den Text des Ladehinweiseses im Loading-View, der angezeigt wird, während das HTML User Interface lädt. (standardmäßig "Lädt...") + * Hinweis: Wird mit setLoadingIndicatorImage ein Loaading-Indicator-Bild gesetzt, so wird der mit setText gesetzte Texte ignoriert. + */ + setText(text: string): void; + /** + * Setzt ein Loading-Indicator-Bild im Loading-View, das angezeigt wird, während das HTML User Interface lädt. (standardmäßig nicht gesetzt) + * Hinweis: Wird mit setLoadingIndicatorImage ein Loaading-Indicator-Bild gesetzt, so wird der mit setText gesetzte Texte ignoriert. + */ + setLoadingIndicatorImage(imageUrl: string): void; + /** + * Setzt die Farbe des Textes im Loading-View, der angezeigt wird, während das HTML User Interface lädt. (standardmäßig schwarz) + */ + setForegroundColor(color: Color): void; + /** + * Aktiviert/Deaktiviert die Nutzung vom Loading-View. (standardmäßig aktiviert) + * Es kann sinnvoll sein, den Loading-View zu deaktivieren, wenn man selbst einen komplett eigenen Loading-View in seine App einbauen möchte. + */ + setEnabled(enabled: boolean): void; +} + +/** + * Eine Instanz eines Logger ermöglicht das Loggen von Inhalten. + * + * Diese erhält man über das KnuddelsServer-Objekt + * mit KnuddelsServer.getDefaultLogger() + * + * Die Log-Einträge werden je nach Einstellungen im /apps-Fenster an den Besitzer des Channels, + * die App-Manager und den App-Entwickler zugestellt. + */ +declare class Logger { + /** + * Logge einen Text mit Level DEBUG. Dieser wird im Chat allen dafür registrierten AppManagern per /p vom App-Logs-User zugestellt. Siehe: /apps, Tab: Logs. + * + * Die Methode erwartet beliebig viele Strings als Parameter. Diese werden vor dem Logging mit einem Leerzeichen gejoint. + */ + debug(...msg: any[]): void; + /** + * Logge einen Text mit Level INFO. Dieser wird im Chat allen dafür registrierten AppManagern per /p vom App-Logs-User zugestellt. Siehe: /apps, Tab: Logs. + * + * Die Methode erwartet beliebig viele Strings als Parameter. Diese werden vor dem Logging mit einem Leerzeichen gejoint. + */ + info(...msg: any[]): void; + /** + * Logge einen Text mit Level WARN. Dieser wird im Chat allen dafür registrierten AppManagern per /p vom App-Logs-User zugestellt, sowie im /apps Fenster im Log angezeigt. Siehe: /apps, Tab: Logs. + * + * Die Methode erwartet beliebig viele Strings als Parameter. Diese werden vor dem Logging mit einem Leerzeichen gejoint. + */ + warn(...msg: any[]): void; + /** + * Logge einen Text mit Level ERROR. Dieser wird im Chat allen dafür registrierten AppManagern per /p vom App-Logs-User zugestellt, sowie im /apps Fenster im Log angezeigt. Siehe: /apps, Tab: Logs. + * + * Die Methode erwartet beliebig viele Strings als Parameter. Diese werden vor dem Logging mit einem Leerzeichen gejoint. + */ + error(...msg: any[]): void; + /** + * Logge einen Text mit Level FATAL. Dieser wird im Chat allen dafür registrierten AppManagern per /p vom App-Logs-User zugestellt, sowie im /apps Fenster im Log angezeigt. Siehe: /apps, Tab: Logs. + * + * Die Methode erwartet beliebig viele Strings als Parameter. Diese werden vor dem Logging mit einem Leerzeichen gejoint. + */ + fatal(...msg: any[]): void; +} + +/** + * Message ist eine abstrakte Klasse und repräsentiert eine Nachricht im Chat. + */ +declare class Message { + /** + * Liefert den User, der die Nachricht verfasst hat. + */ + getAuthor(): User; + /** + * Liefert den Inhalt der Nachricht. + */ + getText(): string; + /** + * Liefert den genauen Zeitpunkt, zu dem die Nachricht erstellt wurde. + */ + getCreationDate(): Date; +} + +/** + * Repräsentiert die Instanz der konkreten App, auf die dieser Code Zugriff hat. + * + * Die Instanz von OwnAppInstance erhält man über das AppAccess-Objekt + * mit appAccess.getOwnInstance() + */ +declare class OwnAppInstance { + /** + * Gibt Zugriff auf Nutzer, die gerade im Channel dieser AppInstance online sind. + * @since AppServer 82560 + */ + getOnlineUsers(otherAppInstance: AppInstance, ...userType: UserType[]): User[]; +} + +/** + * Eine Instanz von Persistence ermöglicht die persistente Speicherung von Zahlen, Zeichenketten und JSON-Objekten. + * Es gibt die zwei Arten AppPersistence und UserPersistence + * + * Jeder eigene Datentyp hat seinen eigenen Namensraum. + * So kann derselbe key für eine Zahl, Zeichenkette und auch JSON-Objekt genutzt werden. + * + *

Hinweis: Mit der Persistence gespeicherte Informationen überleben + * sogar die Deinstallation und Neuinstallation der App. + */ +declare class Persistence { + /** + * Informiert darüber, ob unter dem key ein String abgespeichert ist. + */ + hasString(key: string): boolean; + /** + * Setzt die Zeichenkette value für den key. + * Falls bereits eine Zeichenkette für den key existiert, so wird diese überschrieben. + */ + setString(key: string, value: string): void; + /** + * Liefert die Zeichenkette, die für den key gespeichert ist. + * Falls für key keine Zeichenkette gespeichert ist, so gibt die Methode + * den defaultValue zurück. + */ + getString(key: string, defaultValue?: string): string; + /** + * Löscht die Zeichenkette, die unter key gespeichert ist. + */ + deleteString(key: string): void; + /** + * Informiert darüber, ob unter dem key eine Zahl abgespeichert ist. + */ + hasNumber(key: string): boolean; + /** + * Setzt die Zahl value für den key. + * Falls bereits eine Zahl für den key existiert, so wird diese überschrieben. + */ + setNumber(key: string, value: number): void; + /** + * Addiert den übergebenen value auf die unter dem Key key vorhandenen Wert drauf. + * Value kann auch negativ sein um eine Subtraktion durchzuführen. + * Falls keine Zahl für den key existiert, so wird der value für key gespeichert. + */ + addNumber(key: string, value: number): number; + /** + * Liefert die Zahl, die für den key gespeichert ist. + * Falls für key keine Zahl gespeichert ist, so gibt die Methode + * den defaultValue zurück. + */ + getNumber(key: string, defaultValue?: number): number; + /** + * Löscht die Zahl, die unter key gespeichert ist. + */ + deleteNumber(key: string): void; + /** + * Informiert darüber, ob unter dem key ein Objekt abgespeichert ist. + */ + hasObject(key: string): boolean; + /** + * Setzt das Objekt value für den key. + * Falls bereits ein Objekt für den key existiert, so wird dieses überschrieben. + * Das als JSON serialisierte Objekt darf maximal 100kb groß sein. + */ + setObject(key: string, object: (KnuddelsJson | KnuddelsJsonArray | KnuddelsSerializable)): void; + /** + * Liefert das Objekt, das für den key gespeichert ist. + * Falls für key kein Objekt gespeichert ist, so gibt die Methode + * den defaultValue zurück. + */ + getObject(key: string, defaultValue?: (KnuddelsJson | KnuddelsJsonArray | KnuddelsSerializable)): (KnuddelsJson | KnuddelsJsonArray | KnuddelsSerializable); + /** + * Löscht das Objekt, das unter key gespeichert ist. + */ + deleteObject(key: string): void; +} + +/** + * Eine Instanz von PrivateMessage repräsentiert eine private Nachricht im Chat. + * Die App erhält sämtliche private Nachrichten, die an einen ihrer BotUser + * geschickt werden. + * + *

Hinweis: Eine App hat keinen Zugriff auf private Nachrichten, + * die Nutzer untereinander schreiben, ohne dass ein BotUser als Empfänger involviert ist. + */ +declare class PrivateMessage extends Message { + /** + * Liefert die Liste der Empfänger der Nachricht. + */ + getReceivingUsers(): User[]; + /** + * Sendet eine private Nachricht an alle Beteiligten des Gespräches. + */ + sendReply(text: string): void; +} + +/** + * Eine Instanz von PublicActionMessage repräsentiert eine öffentliche Handlung im Chat. + * Die App erhält die öffentlichen Handlungen. + */ +declare class PublicActionMessage extends Message { +} + +/** + * Eine Instanz von PublicEventMessage repräsentiert ein öffentliches Event im Chat. + * Die App erhält die öffentlichen Events. + */ +declare class PublicEventMessage extends Message { +} + +/** + * Eine Instanz von PublicMessage repräsentiert eine öffentliche Nachricht im Chat. + * Die App erhält die öffentlichen Nachrichten, die geschrieben werden. + */ +declare class PublicMessage extends Message { +} + +/** + * Eine Quest ist eine konkrete Aufgabe, die ein User in der App zu erledigen hat. + * + * Im Blog findest du Informationen darüber, wie man eine Quest für seine App erhält: + * https://blog.developer.knuddels.de/2015/10/29/how-to-get-a-quest/ + */ +declare class Quest { + /** + * Löst ein Quest-Event aus. + * @since AppServer 82290, ChatServer 82290 + */ + setSolved(count?: number): void; + /** + * Liefert den Key der Quest. + * @since AppServer 82290, ChatServer 82290 + */ + getQuestKey(): string; +} + +/** + * Ein QuestAccess-Objekt ermöglicht den Zugriff auf die Quests, die ein Nutzer des Chats, für die laufende App hat. + * + * Im Blog findest du Informationen darüber, wie man eine Quest für seine App erhält: + * https://blog.knuddels.de/2015/10/29/how-to-get-a-quest/ + */ +declare class QuestAccess { + /** + * Liefert die Quests + * für diesen Nutzer in dieser App. + * @since AppServer 82290, ChatServer 82290 + */ + getQuests(): Quest[]; + /** + * Liefert die Information, ob eine bestimmte Quest offen ist. + * @since AppServer 82290, ChatServer 82290 + */ + hasQuest(questKey: string): boolean; + /** + * Liefert eine bestimmte Quest, falls vorhanden. + * @since AppServer 82290, ChatServer 82290 + */ + getQuest(questKey: string): (Quest|null); + /** + * Liefert den User, der zu diesem QuestAccess-Objekt gehört. + * @since AppServer 82290, ChatServer 82290 + */ + getUser(): User; +} + +/** + * RandomOperations bietet eine Sammlung verschiedener Zufallsoperationen, die man für Glücksspiele und Ähnliches nutzen kann. + */ +declare class RandomOperations { + /** + * Liefert eine Zufallszahl zwischen minValue (inklusiv) und maxValue (exklusiv). + */ + static nextInt(minValue: number /* optional */, maxValue: number): number; + /** + * Liefert ein Array mit Zufallszahlen zwischen minValue (inklusiv) und n (exklusiv). + */ + static nextInts(minValue: number /* optional */, maxValue: number, count: number, onlyDifferentNumbers: boolean): number[]; + /** + * Liefert true in truePropability/1 Fällen + */ + static flipTrue(truePropability: number): boolean; + /** + * Liefert ein zufälliges Objekt aus einem Array. + * Falls das Array leer ist, wird null zurückgeliefert. + */ + static getRandomObject(objects: T[]): T; + /** + * Mischt das Array der übergebenen Objekte und liefert es zurück. + */ + static shuffleObjects(objects: T[]): T[]; + /** + * Liefert einen zufälligen String zurück. + * @since AppServer 92699 + */ + static getRandomString(length: number, allowedCharacters?: string): string; +} + +/** + * Repräsentiert die Root-Instanz einer App, die im Hauptchannel läuft. + * + * Die Instanz für die RootAppInstance erhält man über das AppInstance-Objekt + * mit appInstance.getRootInstance() + */ +declare class RootAppInstance extends AppInstance { + /** + * Aktualisiert diese App im Channel (und ggf. vorhandenen Tochterchanneln) auf die neueste Version. + */ + updateApp(message: string /* optional */, logMessage?: string): void; + /** + * Stoppt diese App. + */ + stopApp(message: string /* optional */, logMessage?: string): void; +} + +/** + * Liefert Informationen über einen Server. + */ +declare class ServerInfo { + /** + * Liefert die interne ServerId des Servers. + */ + getServerId(): string; + /** + * Liefert die Code-Revision des Servers. + */ + getRevision(): number; +} + +/** + * Ein SingleDiceResult enthält das Ergebnis aller Würfel desselben Typs. + * Würfelt man beispielsweise mit der Konfiguration "1w2 + 10w5" so gibt es im DiceResult + * zwei SingleDiceResult-Objekte. Eines für "1w2" und eines für "10w5". + */ +declare class SingleDiceResult { + /** + * Liefert den Würfel zurück, durch den dieses SingleDiceResult erzeugt wurde. + */ + getDice(): Dice; + /** + * Liefert die Ziffern, die gewürfelt wurden. + */ + valuesRolled(): number[]; + /** + * Liefert die Summe der Augenzahlen des SingleDiceResult. + */ + sum(): number; +} + +/** + * Diese Dokumentation beschreibt, welche Erweiterungen am serverseitigen String-Objekt vorgenommen wurden. + */ +declare interface String { + /** + * Die Methode liefert den String zurück, auf dem sie aufgerufen wurde mit KCode escaped. + */ + escapeKCode(): string; + /** + * Entfernt jeglichen KCode aus dem String und gibt ihn zurück. + */ + stripKCode(): string; + /** + * Diese Methode liefert die Information, ob der String auf dem die Methode aufgerufen wurde + * mit einem bestimmten Prefix beginnt. + */ + startsWith(prefix: string): boolean; + /** + * Diese Methode liefert die Information, ob der String auf dem die Methode aufgerufen wurde + * mit einem bestimmten Suffix endet. + */ + endsWith(suffix: string): boolean; + /** + * Liefert die Breite des Strings in der Schriftart Arial mit der gegeben Schriftgröße und Information, ob Text fett dargestellt werden soll. + */ + getPixelWidth(fontSize: number, isBold: boolean): number; + /** + * Liefert einen String, der in der Schriftart Arial mit der gegeben Schriftgröße und Information, ob Text fett dargestellt werden soll + * maximal maxPixelWidth breit ist. Wird der Text dafür gekürzt, so wird an das Ende abbreviationMarker angehangen. + * Falls abbreviationMarker nicht übergeben wurde, so ist es automatisch '...'. + */ + limitString(fontSize: number, isBold: boolean, maxPixelWidth: number, abbreviationMarker?: string): string; + /** + * Liefert die Information, ob ein bestimmter String in diesem String vorhanden ist. + */ + contains(needle: string): boolean; + /** + * Liefert die Levenshtein-Distanz zum übergebenen String. + * Levenshtein-Distanz: Minimale Anzahl von Einfüge-, Lösch- und Ersetz-Operationen, um die erste Zeichenkette in die zweite umzuwandeln. + * @since AppServer 82271 + */ + minimalConversionCost(otherString: string): number; + /** + * Liefert die Information, ob der String nur aus Zeichen besteht, die in einem Nicknamen + * vorkommen dürfen. + * @since AppServer 82271 + */ + hasOnlyNicknameCharacters(): boolean; + /** + * Liefert die Information, ob der String nur aus Zeichen besteht, die Nummern sind. + * @since AppServer 82271 + */ + hasOnlyDigits(): boolean; + /** + * Liefert die Information, ob der String nur aus Zeichen besteht, die alphanumerisch + Whitespaces sind. + * @since AppServer 82271 + */ + hasOnlyAlphanumericalAndWhitespaceCharacters(): boolean; + /** + * Liefert die Information, ob der String leer oder null ist. + * @since AppServer 92695 + */ + isEmpty(): boolean; + /** + * Liefert den String in CamelCase. + * @since AppServer 92695 + */ + toCamelCase(): string; + /** + * Liefert den String mit dem ersten Buchstaben als Großbuchstaben. + * @since AppServer 92695 + */ + capitalize(): string; + /** + * Erstellt eine Kopie des String, in dem alle Vorkommnisse des String search in replacement + * ersetzt werden und liefert diesen zurück. + */ + replaceAll(search: string | RegExp, replacement: string): string; + /** + * Prüft primitiv, ob der String laut Knuddels-Filterregeln ok ist. + * @since ChatServer 82262, AppServer 82262 + */ + isOk(): boolean; +} + +/** + * Eine Instanz einer Toplist repräsentiert eine eigene Topliste für einen bestimmten userPersistenceNumberKey. + */ +declare class Toplist { + /** + * Liefert den userPersistenceNumberKey mit dem die Topliste erzeugt wurde. + */ + getUserPersistenceNumberKey(): string; + /** + * Liefert den Anzeigenamen der Topliste. + */ + getDisplayName(): string; + /** + * Liefert den Befehl, der im Chat eingegeben werden kann, um diese Topliste zu öffnen. + * Wird ein User oder eine userId übergeben, so öffnet sich die Topliste mit diesem Nutzer im Fokus. + */ + getChatCommand(user_or_userId?: (User|number)): string; + /** + * Liefert den Anzeigenamen für den übergebenen User oder eine userId. + */ + getLabel(user_or_userId: (User|number)): string; + /** + * Legt einen Change-Listener an, der jedes mal aufgerufen wird, wenn ein User + * einen neuen Anzeigenamen erhält. + */ + addLabelChangeListener(listener: (labelChangeEvent: ToplistLabelChangeEvent) => void): void; + /** + * Löscht einen LabelChangeListener, der mit Toplist/addLabelChangeListener:method erzeugt wurde. + */ + removeLabelChangeListener(listener: (labelChangeEvent: ToplistLabelChangeEvent) => void): void; + /** + * Legt einen Change-Listener an, der jedes mal aufgerufen wird, wenn ein sich der Rang User eines Nutzers ändert. + */ + addRankChangeListener(listener: (rankChangeEvent: ToplistRankChangeEvent) => void): void; + /** + * Löscht einen RankChangeListener, der mit Toplist/addRankChangeListener:method erzeugt wurde. + */ + removeRankChangeListener(listener: (rankChangeEvent: ToplistRankChangeEvent) => void): void; +} + +/** + * Mit einer Instanz von ToplistAccess kann eine App + * Toplist erzeugen und verwalten. + * + * Die Instanz für die ToplistAccess erhält man über das KnuddelsServer-Objekt + * mit KnuddelsServer.getToplistAccess() + */ +declare class ToplistAccess { + /** + * Liefert die Liste aller Toplisten, die diese App erzeugt hat. + */ + getAllToplists(): Toplist[]; + /** + * Liefert die Toplist mit dem Persistenz-Key zurück. + */ + getToplist(userPersistenceNumberKey: string): Toplist; + /** + * Löscht die übergebene Toplist oder die Toplist mit dem Persistenz-Key. + */ + removeToplist(toplist: Toplist): void; + /** + * Erzeugt oder aktualisiert die Toplist für den übergebenen userPersistenceNumberKey. + */ + createOrUpdateToplist(userPersistenceNumberKey: string, displayName: string, parameters?: { labelMapping?: { [minValue: string]: string }; ascending?: boolean; }): Toplist; +} + +/** + * ToplistDisplayType repräsentiert den Anzeigetyp eines Toplisteneintrags im Profil vonUsern. + */ +declare class ToplistDisplayType { + /** + * Nur Anzeigename anzeigen. + */ + static readonly Label: ToplistDisplayType; + /** + * Gespeicherten Wert anzeigen. + */ + static readonly Value: ToplistDisplayType; + /** + * Anzeigename und Rang anzeigen. + */ + static readonly LabelAndRank: ToplistDisplayType; + /** + * Wert und Rang anzeigen. + */ + static readonly ValueAndRank: ToplistDisplayType; +} + +/** + * ToplistLabelChangeEvents erhalten EventListener die bei einer + * Toplist mit der Methode Toplist/addLabelChangeListener:method + * erzeugt wurden, nachdem sich der Anzeigename für einen User geändert hat. + * + * Das ToplistLabelChangeEvent enthält alle wichtigen Daten, um auf die Änderung zu reagieren + * und dem User beispielsweise für den Aufstieg zu gratulieren. + */ +declare class ToplistLabelChangeEvent { + /** + * Liefert die zugehörige Toplist. + */ + getToplist(): Toplist; + /** + * Liefert den vorherigen Anzeigenamen. Hatte der User vorher keinen + * Anzeigenamen, so ist dieser Wert null. + */ + getOldLabel(): string; + /** + * Liefert den neuen Anzeigenamen. Hatte der User nun keinen + * Anzeigenamen mehr, so ist dieser Wert null. + */ + getNewLabel(): string; + /** + * Liefert den User für den das Event ausgelöst wurde. + */ + getUser(): User; + /** + * Liefert den Wert, der vor der Änderung gespeichert war. + */ + getOldValue(): number; + /** + * Liefert den neuen Wert. + */ + getNewValue(): number; +} + +/** + * ToplistRankChangeEvents erhalten EventListener die bei einer + * Toplist mit der Methode Toplist/addRankChangeListener:method + * erzeugt wurden, nachdem sich der Rang für einen User geändert hat. + * + * Das ToplistRankChangeEvent enthält alle wichtigen Daten, um auf die Änderung zu reagieren + * und den überholten Usern eine Nachricht zu senden. + */ +declare class ToplistRankChangeEvent { + /** + * Liefert die zugehörige Toplist. + */ + getToplist(): Toplist; + /** + * Liefert den Toplisten-Rang, den der User vor der Änderung hatte. + */ + getOldRank(): number; + /** + * Liefert den neuen Toplisten-Rang, des Users. + */ + getNewRank(): number; + /** + * Liefert den User für den das Event ausgelöst wurde. + */ + getUser(): User; + /** + * Liefert die User, die bei dieser Änderung überholt worden sind. + *

Achtung: Wenn mehr als 10 User + * überholt wurden, so liefert die Methode die besten 10 überholten User. + */ + getUsersOvertook(): User[]; + /** + * Liefert den Wert, der vor der Änderung gespeichert war. + */ + getOldValue(): number; + /** + * Liefert den neuen Wert. + */ + getNewValue(): number; +} + +/** + * Ein User ist ein Nutzer des Chats, in dem die App läuft. + */ +declare class User { + /** + * Liefert die eindeutige Nutzerkennung des Nutzers. + */ + getUserId(): number; + /** + * Liefert den Nicknamen des Nutzers. + */ + getNick(): string; + /** + * Liefert das Alter des Nutzers. Bei Nutzern, die bereits sehr lange in der Plattform sind kann es vorkommen, dass kein Alter angegeben wurde. In diesem Fall ist das Alter 0. + */ + getAge(): number; + /** + * Liefert das Geschlecht des Nutzers. + */ + getGender(): Gender; + /** + * Liefert den Zeitpunkt der Registrierung des Nutzers. + */ + getRegDate(): Date; + /** + * Liefert den UserStatus des Nutzers. + */ + getUserStatus(): UserStatus; + /** + * Liefert den UserType des Nutzers. + */ + getUserType(): UserType; + /** + * Liefert den aktuellen ClientType des Nutzers oder Offline wenn er nicht im Chat online ist. + */ + getClientType(): ClientType; + /** + * Prüft ob der Client des Users den übergebenen AppViewMode (für User/sendAppContent:method) anzeigen kann. + */ + canShowAppViewMode(mode: AppViewMode): boolean; + /** + * Prüft ob der Client des User's den übergebenen AppContent anzeigen kann. + */ + canSendAppContent(appContent: AppContent): boolean; + /** + * Prüft, ob der User in dem angegebenen Team ist. + * Dies funktioniert derzeit nur für Teams, die eine eigene /fa haben. + * + * Achtung: Bei Nutzern, die neu in ein Team kommen, funktioniert die Abfrage erst dann korrekt, + * wenn er sich neu in den Channel eingeloggt hat. + */ + isInTeam(teamName: string, subTeamName?: string): boolean; + /** + * Liefert ein UserPersistence-Objekt für diesen Nutzer. Mit diesem Objekt kann eine App sich Dinge über diesen speziellen Nutzer merken. + */ + getPersistence(): UserPersistence; + /** + * Shortcut-Funktion um mit dem DefaultBotUser eine private Nachricht zu versenden. + */ + sendPrivateMessage(message: string): void; + /** + * Shortcut-Funktion um mit dem DefaultBotUser eine /m zu versenden. + */ + sendPostMessage(topic: string, text: string): void; + /** + * Liefert die Information, ob dieser Nutzer Channelbesitzer im Channel der App ist. + */ + isChannelOwner(): boolean; + /** + * Liefert die Information, ob der Channel der App + * ein Lieblingschannel des Nutzers ist. + */ + isLikingChannel(): boolean; + /** + * Liefert die Information, ob der Nutzer im harten Kern des Channels der App ist. + * @since AppServer 92701, ChatServer 92701 + */ + isChannelCoreUser(): boolean; + /** + * Liefert die Information, ob dieser Nutzer ein AppManager für diese App ist. Die Channelbesitzer zählen automatisch auch als AppManager. + */ + isAppManager(): boolean; + /** + * Liefert Information, ob dieser Nutzer derzeit für das Schreiben öffentlicher Nachrichten im Channel gesperrt ist. + */ + isMuted(): boolean; + /** + * Liefert Information, ob dieser Nutzer beim Schreiben öffentlicher Nachrichten im Channel + * derzeit für die Verwendung von Textformatierungen, Farben und Smileys gesperrt ist. + */ + isColorMuted(): boolean; + /** + * Liefert Information, ob dieser Nutzer derzeit für das Betreten des Channel gesperrt ist. + */ + isLocked(): boolean; + /** + * Liefert Information, ob dieser Nutzer Channelmoderator im Channel der App ist. + */ + isChannelModerator(): boolean; + /** + * Liefert Information, ob dieser Nutzer Eventmoderator im Channel der App ist. + */ + isEventModerator(): boolean; + /** + * Liefert Information, ob dieser Nutzers der Entwickler der App ist. + */ + isAppDeveloper(): boolean; + /** + * Liefert einen Link zum Profil des Nutzers, den man im Chat anzeigen kann. + */ + getProfileLink(displayText?: string): string; + /** + * Liefert die Information, ob der Nutzer online im Channel der App ist. + */ + isOnlineInChannel(): boolean; + /** + * Liefert die Anzahl der Knuddel, die der Nutzer besitzt. + */ + getKnuddelAmount(): KnuddelAmount; + /** + * Liefert die Information, ob der Nutzer irgendwo im Chat online ist. + */ + isOnline(): boolean; + /** + * Liefert die Readme des Nutzers, die er mit /readme TEXT in sein Profil gesetzt hat. + */ + getReadme(): string; + /** + * Liefert die vom Nutzer verbrachte Zeit im gesamten Chatsystem In Minuten. + * Hinweis: Die Minutenzahl wird derzeit immer nur zu dem Zeitpunkt aktualisiert, + * wenn der Nutzer offline geht. + */ + getOnlineMinutes(): number; + /** + * Liefert die Information, ob der Nutzer sich mittels /away-Funktion kurz abgemeldet hat. + */ + isAway(): boolean; + /** + * Liefert die Information, ob der Nutzer ein Profilfoto hat. + */ + hasProfilePhoto(): boolean; + /** + * (Er)setzt den übergebenen AppContent beim Nutzer. + */ + sendAppContent(appContent: AppContent): AppContentSession; + /** + * Liefert alle AppContentSession, die der User + * aktuell geöffnet hat. + */ + getAppContentSessions(): AppContentSession[]; + /** + * Liefert die AppContentSession, die der User + * mit einem bestimmten AppViewMode aktuell geöffnet hat. + */ + getAppContentSession(appViewMode: AppViewMode): AppContentSession; + /** + * Vergleicht den übergebenen Nutzer und liefert true, falls der übergebene Nutzer + * identisch ist mit dem aktuellen Nutzer. + */ + equals(user: User): boolean; + /** + * Liefert die URL zum Profilfoto des Nutzers. Die übergebene Breite und Höhe + * liefern dem Server einen Anhaltswert, um das bestmögliche Foto zu finden, + * sind aber keine Garantie, dass das Foto diese Ausmaße haben wird. + */ + getProfilePhoto(width: number, height: number): string; + /** + * Liefert das QuestAccess-Objekt + * für diesen Nutzer in dieser App. + * @since AppServer 82290, ChatServer 82290 + */ + getQuestAccess(): QuestAccess; + /** + * Liefert die Information, ob der Nutzer gerade sein Video streamt. + */ + isStreamingVideo(): boolean; + /** + * Liefert den KnuddelAccount des Nutzers. + */ + getKnuddelAccount(): KnuddelAccount; + /** + * Liefert die ChannelTalkPermission für diesen Nutzer in diesem + * Channel. + */ + getChannelTalkPermission(): ChannelTalkPermission; + /** + * Liefert die Information, ob der User ein verifiziertes Profilbild hat. + */ + isProfilePhotoVerified(): boolean; + /** + * Liefert die Information, ob das Alter des Users verifiziert ist. + */ + isAgeVerified(): boolean; + /** + * Setzt dem Nutzer ein Icon in die Nickliste, das auf der rechten Seite seines Nicks angezeigt wird. + * Der Eintrag wird automatisch entfernt, sobald der Nutzer den Channel verlässt, + * kann aber auch mit User/removeNicklistIcon:method + * entfernt werden. + */ + addNicklistIcon(imagePath: string, imageWidth: number): void; + /** + * Entfernt dem Nutzer ein über die API gesetztes Icon in die Nickliste. + */ + removeNicklistIcon(imagePath: string): void; + /** + * Startet einen Würfelwurf für den Nutzer, falls er online im Channel ist und er nicht gemuted ist. + * @since AppServer 89159, ChatServer 89159 + */ + triggerDice(diceConfiguration: DiceConfiguration): void; +} + +/** + * Mit einer Instanz von UserAccess kann eine App + * auf User zugreifen, die bereits einmal im Channel waren, + * als die App lief. Für alle nicht zugreifbaren User kann man via UserAccess den korrekt geschriebenen Nicknamen erhalten. + * + * Die Instanz für die UserAccess erhält man über das KnuddelsServer-Objekt + * mit KnuddelsServer.getUserAccess() + */ +declare class UserAccess { + /** + * Liefert die userId des Nutzers mit dem übergebenen Nicknamen. + */ + getUserId(nick: string): number; + /** + * Informiert darüber, ob ein Nutzer mit dem übergebenen Nicknamen existiert. + */ + exists(nick: string): boolean; + /** + * Informiert darüber, ob der Nutzer mit der übergebenen userId geladen werden darf. Neben dem AppDeveloper können nur Nutzer geladen werden, die sich einmal im Channel befanden, als die App + * lief. + */ + mayAccess(userId: number): boolean; + /** + * Liefert den Nutzer mit der übergebenen userId. Neben dem AppDeveloper können nur Nutzer geladen werden, die sich einmal im Channel befanden, als die App lief. Es wird empfohlen vor der + * Abfrage von getUserById(userId) mit UserAccess/mayAccess:method abzufragen, ob dies funktionieren wird. + */ + getUserById(userId: number): User; + /** + * Liefert den Nicknamen des Nutzers mit der übergebenen userId in der korrekten Schreibweise. + */ + getNick(userId: number): string; + /** + * Loopt über alle zugreifbaren User sortiert nach Registrierzeitpunkt und + * führt für jeden User das übergebene Callback aus. + */ + eachAccessibleUser(callback: (user: User, index: number, accessibleUserCount: number, key?: string) => boolean, + parameters?: { onStart?: (accessibleUserCount: number, key?: string) => void; + onEnd?: (accessibleUserCount: number, key?: string) => void; }): void; +} + +/** + * Für jeden User kann eine UserPersistence angefordert werden, um sich + * für einen bestimmten Nutzer Dinge persistent zu merken. + */ +declare class UserPersistence extends Persistence { + /** + * Löscht alle Zahlenwerte, die in dieser UserPersistence gespeichert sind. + * @since AppServer 88569 + */ + deleteAllNumbers(): number; + /** + * Löscht alle Objekte, die in dieser UserPersistence gespeichert sind. + * @since AppServer 88569 + */ + deleteAllObjects(): number; + /** + * Löscht alle Zeichenketten, die in dieser UserPersistence gespeichert sind. + * @since AppServer 88569 + */ + deleteAllStrings(): number; + /** + * Löscht alle Daten, die in dieser UserPersistence gespeichert sind. + * @since AppServer 88569 + */ + deleteAll(): number; +} + +/** + * Diese Klasse repräsentiert einen Eintrag der Persistenz. + */ +declare class UserPersistenceNumberEntry { + /** + * Liefert den Nutzer. + */ + getUser(): User; + /** + * Liefert den Wert. + */ + getValue(): number; + /** + * Liefert den Rang des Elements in der Persistenz. + */ + getRank(): number; + /** + * Liefert die Position des Elements in der Persistenz. + */ + getPosition(): number; +} + +/** + * Mit dieser Klasse ist es möglich nicht User-spezifische Abfragen auf die UserPersistence auszuführen. + */ +declare class UserPersistenceNumbers { + /** + * Liefert die Summe aller via UserPersistence gespeicherten Zahlen für den übergebenen key. + */ + static getSum(key: string): number; + /** + * Löscht alle gespeicherten Zahlen-Werte für den übergebenen key. + */ + static deleteAll(key: string): number; + /** + * Liefert die Anzahl aller unterschiedlichen Nutzer, die Werte für einen bestimmten key gespeichert haben. + * Hierbei kann optional der Wertebereich über die parameters eingegrenzt werden. + */ + static getCount(key: string, parameters?: { minimumValue?: number; maximumValue?: number; }): number; + /** + * Ändert einen bestimmten key bei allen UserPersistence. + */ + static updateKey(oldKeyName: string, newKeyName: string): number; + /** + * Ändert alle Werte für einen bestimmten key, die vorher einen bestimmten anderen Wert hatten in der UserPersistence. + *
Hinweis: Da diese Methode ein Batch-Update ist werden keine Change-Listener (ToplistRankChangeEvent, ToplistLabelChangeEvent) ausgelöst. + */ + static updateValue(key: string, oldValue: number, newValue: number): number; + /** + * Addiert einen Wert für Einträge mit einem bestimmten key in der UserPersistence. + *
Hinweis: Da diese Methode ein Batch-Update ist werden keine Change-Listener (ToplistRankChangeEvent, ToplistLabelChangeEvent) ausgelöst. + */ + static addNumber(key: string, value: number, parameters?: { minimumValue?: number; maximumValue?: number; targetUsers?: User[]; }): number; + /** + * Liefert ein Array mit UserPersistenceNumberEntry-Objekten für einen bestimmten key. + * Hierdurch kann beispielsweise eine blätterbare Topliste abgebildet werden. + */ + static getSortedEntries(key: string, parameters?: { ascending?: boolean; count?: number; page?: number; minimumValue?: number; maximumValue?: number; }): UserPersistenceNumberEntry[]; + /** + * Liefert ein Array mit UserPersistenceNumberEntry-Objekten für einen bestimmten key. Hierbei werden die nähesten Elemente gewählt, + * die am übergebenen User/UserId liegen. + * + * Beispiel: Der Nutzer ist in der Liste auf Position 20, dann werden die Resultate von 14-24 bei einem Count von 10 ausgegeben. + * Beispiel: Der Nutzer ist in der Liste auf Position 3, dann werden die Resultate von 1-10 bei einem Count von 10 ausgegeben. + */ + static getSortedEntriesAdjacent(key: string, user_or_userId: (User|number), parameters?: { ascending?: boolean; count?: number; }): UserPersistenceNumberEntry[]; + /** + * Liefert die absolute Position des Nutzers in der Liste. Die Position ist im Gegensatz zum Rang immer eindeutig. + * + * Bei gleichem Wert hat der Nutzer die höhere Position, der zuerst einen Eintrag in der Persistenz hatte. + * + * Mit der Methode UserPersistenceNumbers/getRank:method kann man den Rang des Nutzers herausfinden. Dieser ist identisch, wenn + * unterschiedliche Nutzer denselben Wert haben. + */ + static getPosition(key: string, user_or_userId: (User|number), parameters?: { ascending?: boolean; minimumValue?: number; }): number; + /** + * Liefert den Rang des Nutzers. Der Rang ist nicht eindeutig. Bei gleicher Punktzahl haben Nutzer denselben Rang. + * Mit der Methode UserPersistenceNumbers/getPosition:method kann man die Position eindeutige Position, statt des Ranges herausfinden. + */ + static getRank(key: string, user_or_userId: (User|number), parameters?: { ascending?: boolean; minimumValue?: number; }): number; + /** + * Ruft eine Funktion für alle Nutzer auf, die einen bestimmten key in der UserPersistence gesetzt haben. + * Hierbei greifen die übergebenen Filter. + */ + static each(key: string, callback: { user: User; value: number; index: number; totalCount: number; key: string; }, + parameters?: { ascending?: boolean; minimumValue?: number; maximumValue?: number; maximumCount?: number; + onStart?: (totalCount: number, key: string) => void; onEnd?: (totalCount: number, key: string) => void; }): void; + /** + * Liefert alle keys, die für User in der Persistence + * gespeichert wurden. + * @since AppServer 82483 + */ + static getAllKeys(filterKey?: string): string[]; +} + +/** + * Mit dieser Klasse ist es möglich nicht User-spezifische Abfragen auf die UserPersistence auszuführen. + */ +declare class UserPersistenceObjects { + /** + * Löscht alle gespeicherten Objekte für den übergebenen key. + * @since AppServer 82478 + */ + static deleteAll(key: string): number; + /** + * Liefert alle keys, die für User in der Persistence + * gespeichert wurden. + * @since AppServer 82483 + */ + static getAllKeys(filterKey?: string): string[]; +} + +/** + * Mit dieser Klasse ist es möglich nicht User-spezifische Abfragen auf die UserPersistence auszuführen. + */ +declare class UserPersistenceStrings { + /** + * Liefert die Information, ob für einen bestimmten key und value bei einem beliebigen Nutzer eine Paarung existiert. + * @since AppServer 88571 + */ + static exists(key: string, value: string, ignoreCase?: boolean): boolean; + /** + * Löscht alle gespeicherten Strings für den übergebenen key. + * @since AppServer 82478 + */ + static deleteAll(key: string): number; + /** + * Liefert alle keys, die für User in der Persistence + * gespeichert wurden. + * @since AppServer 82483 + */ + static getAllKeys(filterKey?: string): string[]; +} + +/** + * Repräsentiert den Status eines User. + */ +declare class UserStatus { + /** + * Liefert den numerischen Wert das UserStatus. + */ + getNumericStatus(): number; + /** + * Liefert die Information ob der aktuelle UserStatus mindestens so hoch ist, wie der übergebene UserStatus. + */ + isAtLeast(otherUserStatus: UserStatus): boolean; + /** + * + */ + static readonly Newbie: UserStatus; + /** + * + */ + static readonly Family: UserStatus; + /** + * + */ + static readonly Stammi: UserStatus; + /** + * + */ + static readonly HonoryMember: UserStatus; + /** + * + */ + static readonly Admin: UserStatus; + /** + * + */ + static readonly SystemBot: UserStatus; + /** + * + */ + static readonly Sysadmin: UserStatus; +} + +/** + * Repräsentiert den Typ eines User. + */ +declare class UserType { + /** + * Bot der App. + */ + static readonly AppBot: UserType; + /** + * Bot des Knuddels-Chatsystems. + */ + static readonly SystemBot: UserType; + /** + * Menschlicher User. + */ + static readonly Human: UserType; +} + +/** + * VideoChannelData hält Informationen zu laufenden Video-Streams im Channel bereit. + */ +declare class VideoChannelData { + /** + * Liefert alle User die im Channel derzeit ihr Video streamen. + */ + getStreamingVideoUsers(): User[]; +} + diff --git a/knuddels-userapps-api/knuddels-userapps-api-tests.ts b/knuddels-userapps-api/knuddels-userapps-api-tests.ts new file mode 100644 index 0000000000..1faaa193e5 --- /dev/null +++ b/knuddels-userapps-api/knuddels-userapps-api-tests.ts @@ -0,0 +1,137 @@ +/// + +class Server implements App { + + private usersPlaying: { [nick: string]: number } = {}; + private isShuttingDown: boolean = false; + + private htmlFile: HTMLFile = new HTMLFile('start.html'); + private appContent: AppContent = AppContent.overlayContent(this.htmlFile, 243, 266); + + onAppStart() { + KnuddelsServer.getChannel() + .getOnlineUsers(UserType.Human) + .forEach((user) => { + this.onUserJoined(user) + }); + }; + + onUserJoined(user: User) { + const botNick = KnuddelsServer.getDefaultBotUser() + .getNick() + .escapeKCode(); + user.sendPrivateMessage('Lust auf ne Runde Ziegenphobie? Mit nur _°BB>_h1 Knuddel|/appknuddel ' + botNick + '<°°°_ bist du dabei!'); + }; + + onUserLeft(user: User) { + if (this.usersPlaying[user.getNick()] == 1) { + KnuddelsServer.getDefaultBotUser() + .transferKnuddel(user, new KnuddelAmount(1), 'Du hast den Channel verlassen.'); + + delete this.usersPlaying[user.getNick()]; + } + }; + + onPrepareShutdown() { + if (!this.isShuttingDown) { + this.isShuttingDown = true; + + for (let key in this.usersPlaying) { + const userId = KnuddelsServer.getUserAccess() + .getUserId(key); + const user = KnuddelsServer.getUserAccess() + .getUserById(userId); + + KnuddelsServer.getDefaultBotUser() + .transferKnuddel(user, new KnuddelAmount(1), 'Die App fährt gleich herunter.'); + user.getAppContentSessions() + .forEach((session: AppContentSession) => { + session.remove(); + }); + + delete this.usersPlaying[key]; + } + } + } + + onBeforeKnuddelReceived(knuddelTransfer: KnuddelTransfer) { + const sender = knuddelTransfer.getSender(); + + if (!sender.canSendAppContent(this.appContent)) { + knuddelTransfer.reject('Sorry, mit diesem Gerät kannst du gerade nicht spielen.'); + } else if (sender.isChannelOwner() && knuddelTransfer.getKnuddelAmount() + .asNumber() != 1) { + knuddelTransfer.accept(); + } else if (this.isShuttingDown) { + knuddelTransfer.reject('Du App nimmt gerade keine neuen Spieler an.'); + } else if (this.usersPlaying[sender.getNick()]) { + knuddelTransfer.reject('Du spielst bereits.'); + } else if (knuddelTransfer.getKnuddelAmount() + .asNumber() != 1) { + const botNick = KnuddelsServer.getDefaultBotUser() + .getNick() + .escapeKCode(); + knuddelTransfer.reject('Du musst genau _°BB>_h1 Knuddel senden|/appknuddel ' + botNick + '<°°°_...'); + } else { + knuddelTransfer.accept(); + } + }; + + onKnuddelReceived(user: User, receiver: User, knuddelAmount: KnuddelAmount) { + if (knuddelAmount.asNumber() == 1) { + this.usersPlaying[user.getNick()] = 1; + user.sendAppContent(this.appContent); + } else { + user.sendPrivateMessage('Vielen Dank für die Einzahlung.'); + } + }; + + onEventReceived(user: User, key: string, data: string) { + if (key == 'selectedEntry' && this.usersPlaying[user.getNick()] == 1) { + this.usersPlaying[user.getNick()] = 2; + + setTimeout(() => { + + let doorNumber = parseInt(data[data.length - 1], 10); + + let winningDoorNumber = RandomOperations.nextInt(0, 2) + 1; + + let hasWon = winningDoorNumber == doorNumber; + + let text = hasWon + ? 'Richtig getippt' + : 'Knapp daneben'; + + user.getAppContentSession(AppViewMode.Overlay) + .getAppContent() + .sendEvent('openDoor', { + 'door': doorNumber, + 'winningDoor': winningDoorNumber, + 'text': text, + }); + + if (hasWon) { + KnuddelsServer.getDefaultBotUser() + .transferKnuddel(user, new KnuddelAmount(2), 'Richtig getippt...'); + } + + setTimeout(() => { + const botNick = KnuddelsServer.getDefaultBotUser() + .getNick() + .escapeKCode(); + user.sendPrivateMessage('Na, Lust auf _°BB>_hnoch eine Runde|/appknuddel ' + botNick + '<°°°_?'); + user.getAppContentSessions() + .forEach((session: AppContentSession) => { + session.remove(); + }); + delete this.usersPlaying[user.getNick()]; + }, 4000); + }, 1500); + } + }; + +} + +declare let App: Server; // tell the compiler that "App" will be available + +App = new Server(); diff --git a/knuddels-userapps-api/tsconfig.json b/knuddels-userapps-api/tsconfig.json new file mode 100644 index 0000000000..21fec51518 --- /dev/null +++ b/knuddels-userapps-api/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "knuddels-userapps-api-tests.ts" + ] +} \ No newline at end of file diff --git a/knuddels-userapps-api/tslint.json b/knuddels-userapps-api/tslint.json new file mode 100644 index 0000000000..785a601162 --- /dev/null +++ b/knuddels-userapps-api/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "../tslint.json" +} \ No newline at end of file diff --git a/leaflet/index.d.ts b/leaflet/index.d.ts index de463ae997..7f57c1dfd9 100644 --- a/leaflet/index.d.ts +++ b/leaflet/index.d.ts @@ -1466,7 +1466,7 @@ declare namespace L { export function divIcon(options?: DivIconOptions): DivIcon; export interface MarkerOptions extends InteractiveLayerOptions { - icon?: Icon; + icon?: Icon | DivIcon; clickable?: boolean; draggable?: boolean; keyboard?: boolean; @@ -1483,7 +1483,7 @@ declare namespace L { getLatLng(): LatLng; setLatLng(latlng: LatLngExpression): this; setZIndexOffset(offset: number): this; - setIcon(icon: Icon): this; + setIcon(icon: Icon | DivIcon): this; setOpacity(opacity: number): this; getElement(): HTMLElement; diff --git a/leaflet/leaflet-tests.ts b/leaflet/leaflet-tests.ts index cce5565851..dcdba8a6e8 100644 --- a/leaflet/leaflet-tests.ts +++ b/leaflet/leaflet-tests.ts @@ -448,6 +448,17 @@ L.marker([1, 2], { }) }).bindPopup('

Hi

'); +L.marker([1, 2], { + icon: L.divIcon({ + className: 'my-icon-class' + }) +}).setIcon(L.icon({ + iconUrl: 'my-icon.png' +})).setIcon(L.divIcon({ + className: 'my-div-icon' +}));; + + L.Util.extend({}); L.Util.create({}); L.Util.bind(() => {}, {}); @@ -466,3 +477,4 @@ L.Util.indexOf([], {}); L.Util.requestAnimFrame(() => {}); L.Util.cancelAnimFrame(1); L.Util.emptyImageUrl; + diff --git a/lodash/index.d.ts b/lodash/index.d.ts index 4671a672f3..e473545d33 100644 --- a/lodash/index.d.ts +++ b/lodash/index.d.ts @@ -10387,6 +10387,13 @@ declare namespace _ { * @param funcs Functions to invoke. * @return Returns the new function. */ + // 0-argument first function + flow(f1: () => R1, f2: (a: R1) => R2): () => R2; + flow(f1: () => R1, f2: (a: R1) => R2, f3: (a: R2) => R3): () => R3; + flow(f1: () => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): () => R4; + flow(f1: () => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): () => R5; + flow(f1: () => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): () => R6; + flow(f1: () => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): () => R7; // 1-argument first function flow(f1: (a1: A1) => R1, f2: (a: R1) => R2): (a1: A1) => R2; flow(f1: (a1: A1) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3): (a1: A1) => R3; diff --git a/loopback/index.d.ts b/loopback/index.d.ts index ccfc270e10..2d4af5caa9 100644 --- a/loopback/index.d.ts +++ b/loopback/index.d.ts @@ -245,7 +245,7 @@ declare namespace l { * @header app.middleware(name, handler */ - middleware(name: string, paths?: any[]|string|RegExp, handler?: () => void): any; + middleware(name: string, paths?: any[]|string|RegExp, handler?: core.Handler): any; } // interface CookieOptions extends core.CookieOptions { } @@ -1067,7 +1067,7 @@ declare namespace l { * @class PersistedModel */ - class PersistedModel { + class PersistedModel extends Model { /** * Apply an update list @@ -1270,7 +1270,7 @@ declare namespace l { * @param {Array} model First model instance that matches the filter or null if none found */ - static findOne(filter?: {fields: string|any|any[]; include: string|any|any[]; order: string; skip: number; where: any; }, callback?: (err: Error, model: any[]) => void): void; + static findOne(filter?: {fields?: string|any|any[]; include?: string|any|any[]; order?: string; skip?: number; where?: any; }, callback?: (err: Error, model: any) => void): void; /** * Finds one record matching the optional filter object. If not found, creates @@ -1741,7 +1741,7 @@ declare namespace l { created: Date; /** Extends the `Model.settings` object. */ - settings: { http: { path: string }; acls: ACL, accessTokenIdLength: number}; + settings: { http: { path: string }; acls: ACL[], accessTokenIdLength: number}; /** * Create a cryptographically random access token id @@ -1838,7 +1838,7 @@ declare namespace l { principalId: string; /** settings Extends the `Model.settings` object. */ - settings: { http: { path: string }; acls: ACL, defaultPermission: 'DENY'}; + settings: { http: { path: string }; acls: ACL[], defaultPermission: 'DENY'}; /** * Check if the request has the permission to access. @@ -2125,7 +2125,7 @@ declare namespace l { * settings.ignoreErrors By default, when changes are rectified, an error will throw an exception. * However, if this setting is true, then errors will not throw exceptions. */ - settings: { http: { path: string }; acls: ACL; hashAlgorithm: string; ignoreErrors: boolean; }; + settings: { http: { path: string }; acls: ACL[]; hashAlgorithm: string; ignoreErrors: boolean; }; /** * Are both changes deletes? @@ -2800,7 +2800,7 @@ declare namespace l { */ settings: { http: { path: string }; - acls: ACL; + acls: ACL[]; emailVerificationRequired: boolean; ttl: number; maxTTL: number; diff --git a/maker.js/index.d.ts b/maker.js/index.d.ts index ad06d7eb91..ff6a7bd69e 100644 --- a/maker.js/index.d.ts +++ b/maker.js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Maker.js 0.9.31 +// Type definitions for Maker.js 0.9.33 // Project: https://github.com/Microsoft/maker.js // Definitions by: Dan Marshall // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -66,6 +66,17 @@ declare namespace MakerJs { * @returns String of the flattened array. */ function createRouteKey(route: string[]): string; + /** + * Travel along a route inside of a model to extract a specific node in its tree. + * + * @param modelContext Model to travel within. + * @param routeKeyOrRoute String of a flattened route, or a string array of route segments. + * @returns Model or Path object within the modelContext tree. + */ + function travel(modelContext: IModel, routeKeyOrRoute: string | string[]): { + path: IPath | IModel; + offset: IPoint; + }; /** * Clone an object. * @@ -139,6 +150,15 @@ declare namespace MakerJs { */ high: IPoint; } + /** + * A measurement of extents, with a center point. + */ + interface IMeasureWithCenter extends IMeasure { + /** + * The center point of the rectangle containing the item being measured. + */ + center: IPoint; + } /** * A map of measurements. */ @@ -926,7 +946,7 @@ declare namespace MakerJs.path { * * @param pathToMove The path to move. * @param origin The new origin for the path. - * @returns The original path (for chaining). + * @returns The original path (for cascading). */ function move(pathToMove: IPath, origin: IPoint): IPath; /** @@ -935,7 +955,7 @@ declare namespace MakerJs.path { * @param pathToMove The path to move. * @param delta The x & y adjustments as a point object. * @param subtract Optional boolean to subtract instead of add. - * @returns The original path (for chaining). + * @returns The original path (for cascading). */ function moveRelative(pathToMove: IPath, delta: IPoint, subtract?: boolean): IPath; /** @@ -952,7 +972,7 @@ declare namespace MakerJs.path { * @param pathToRotate The path to rotate. * @param angleInDegrees The amount of rotation, in degrees. * @param rotationOrigin The center point of rotation. - * @returns The original path (for chaining). + * @returns The original path (for cascading). */ function rotate(pathToRotate: IPath, angleInDegrees: number, rotationOrigin?: IPoint): IPath; /** @@ -960,7 +980,7 @@ declare namespace MakerJs.path { * * @param pathToScale The path to scale. * @param scaleValue The amount of scaling. - * @returns The original path (for chaining). + * @returns The original path (for cascading). */ function scale(pathToScale: IPath, scaleValue: number): IPath; /** @@ -1215,11 +1235,11 @@ declare namespace MakerJs.model { */ function mirror(modelToMirror: IModel, mirrorX: boolean, mirrorY: boolean): IModel; /** - * Move a model to an absolute point. Note that this is also accomplished by directly setting the origin property. This function exists for chaining. + * Move a model to an absolute point. Note that this is also accomplished by directly setting the origin property. This function exists for cascading. * * @param modelToMove The model to move. * @param origin The new position of the model. - * @returns The original model (for chaining). + * @returns The original model (for cascading). */ function move(modelToMove: IModel, origin: IPoint): IModel; /** @@ -1227,7 +1247,7 @@ declare namespace MakerJs.model { * * @param modelToMove The model to move. * @param delta The x & y adjustments as a point object. - * @returns The original model (for chaining). + * @returns The original model (for cascading). */ function moveRelative(modelToMove: IModel, delta: IPoint): IModel; /** @@ -1235,7 +1255,7 @@ declare namespace MakerJs.model { * * @param modelToPrefix The model to prefix. * @param prefix The prefix to prepend on paths ids. - * @returns The original model (for chaining). + * @returns The original model (for cascading). */ function prefixPathIds(modelToPrefix: IModel, prefix: string): IModel; /** @@ -1244,7 +1264,7 @@ declare namespace MakerJs.model { * @param modelToRotate The model to rotate. * @param angleInDegrees The amount of rotation, in degrees. * @param rotationOrigin The center point of rotation. - * @returns The original model (for chaining). + * @returns The original model (for cascading). */ function rotate(modelToRotate: IModel, angleInDegrees: number, rotationOrigin?: IPoint): IModel; /** @@ -1253,7 +1273,7 @@ declare namespace MakerJs.model { * @param modelToScale The model to scale. * @param scaleValue The amount of scaling. * @param scaleOrigin Optional boolean to scale the origin point. Typically false for the root model. - * @returns The original model (for chaining). + * @returns The original model (for cascading). */ function scale(modelToScale: IModel, scaleValue: number, scaleOrigin?: boolean): IModel; /** @@ -1261,7 +1281,7 @@ declare namespace MakerJs.model { * * @param modeltoConvert The model to convert. * @param destUnitType The unit system. - * @returns The scaled model (for chaining). + * @returns The scaled model (for cascading). */ function convertUnits(modeltoConvert: IModel, destUnitType: string): IModel; /** @@ -1373,7 +1393,7 @@ declare namespace MakerJs.model { * * @param modelContext The originated model to search for similar paths. * @param options Optional options object. - * @returns The simplified model (for chaining). + * @returns The simplified model (for cascading). */ function simplify(modelToSimplify: IModel, options?: ISimplifyOptions): IModel; } @@ -1478,7 +1498,7 @@ declare namespace MakerJs.measure { * @param baseMeasure The measurement to increase. * @param addMeasure The additional measurement. * @param addOffset Optional offset point of the additional measurement. - * @returns The increased original measurement (for chaining). + * @returns The increased original measurement (for cascading). */ function increase(baseMeasure: IMeasure, addMeasure: IMeasure): IMeasure; /** @@ -1583,7 +1603,7 @@ declare namespace MakerJs.measure { * @param atlas Optional atlas to save measurements. * @returns object with low and high points. */ - function modelExtents(modelToMeasure: IModel, atlas?: measure.Atlas): IMeasure; + function modelExtents(modelToMeasure: IModel, atlas?: measure.Atlas): IMeasureWithCenter; /** * A list of maps of measurements. * @@ -1612,6 +1632,22 @@ declare namespace MakerJs.measure { constructor(modelContext: IModel); measureModels(): void; } + /** + * A hexagon which surrounds a model. + */ + interface IBoundingHex extends IModel { + /** + * Radius of the hexagon, which is also the length of a side. + */ + radius: number; + } + /** + * Measures the minimum bounding hexagon surrounding a model. The hexagon is oriented such that the right and left sides are vertical, and the top and bottom are pointed. + * + * @param modelToMeasure The model to measure. + * @returns IBoundingHex object which is a hexagon model, with an additional radius property. + */ + function boundingHexagon(modelToMeasure: IModel): IBoundingHex; } declare namespace MakerJs.exporter { /** @@ -1787,6 +1823,29 @@ declare namespace MakerJs.model { function findChains(modelContext: IModel, callback: IChainCallback, options?: IFindChainsOptions): void; } declare namespace MakerJs.chain { + /** + * Shift the links of an endless chain. + * + * @param chainContext Chain to cycle through. Must be endless. + * @param amount Optional number of links to shift. May be negative to cycle backwards. + * @returns The chainContext for cascading. + */ + function cycle(chainContext: IChain, amount?: number): IChain; + /** + * Reverse the links of a chain. + * + * @param chainContext Chain to reverse. + * @returns The chainContext for cascading. + */ + function reverse(chainContext: IChain): IChain; + /** + * Set the beginning of an endless chain to a known routeKey of a path. + * + * @param chainContext Chain to cycle through. Must be endless. + * @param routeKey RouteKey of the desired path to start the chain with. + * @returns The chainContext for cascading. + */ + function startAt(chainContext: IChain, routeKey: string): IChain; /** * Get points along a chain of paths. * @@ -1825,7 +1884,7 @@ declare namespace MakerJs.model { * * @param modelContext The model to search for dead ends. * @param options Optional options object. - * @returns The input model (for chaining). + * @returns The input model (for cascading). */ function removeDeadEnds(modelContext: IModel, pointMatchingDistance?: any, keep?: IWalkPathBooleanCallback): IModel; } @@ -2123,6 +2182,18 @@ declare namespace MakerJs.models { * @param numericList String containing a list of numbers which can be delimited by spaces, commas, or anything non-numeric (Note: [exponential notation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toExponential) is allowed). */ constructor(numericList: string); + /** + * Create a model by connecting points designated in a string. The model will be 'closed' - i.e. the last point will connect to the first point. + * + * Example: + * ``` + * var c = new makerjs.models.ConnectTheDots(false, '-10 0 10 0 0 20'); // 3 coordinates to form a polyline + * ``` + * + * @param isClosed Flag to specify if last point should connect to the first point. + * @param numericList String containing a list of numbers which can be delimited by spaces, commas, or anything non-numeric (Note: [exponential notation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toExponential) is allowed). + */ + constructor(isClosed: boolean, numericList: string); /** * Create a model by connecting points designated in a numeric array. The model will be 'closed' - i.e. the last point will connect to the first point. * @@ -2134,6 +2205,18 @@ declare namespace MakerJs.models { * @param coords Array of coordinates. */ constructor(coords: number[]); + /** + * Create a model by connecting points designated in a numeric array. The model will be 'closed' - i.e. the last point will connect to the first point. + * + * Example: + * ``` + * var c = new makerjs.models.ConnectTheDots(false, [-10, 0, 10, 0, 0, 20]); // 3 coordinates to form a polyline + * ``` + * + * @param isClosed Flag to specify if last point should connect to the first point. + * @param coords Array of coordinates. + */ + constructor(isClosed: boolean, coords: number[]); /** * Create a model by connecting points designated in an array of points. The model may be closed, or left open. * diff --git a/maker.js/maker.js-tests.ts b/maker.js/maker.js-tests.ts index 4c7dbc25f0..f5f9d9db16 100644 --- a/maker.js/maker.js-tests.ts +++ b/maker.js/maker.js-tests.ts @@ -51,6 +51,7 @@ function test() { makerjs.isPoint([]); makerjs.pathType.Circle; makerjs.round(44.44444, .01); + makerjs.travel(model, ''); makerjs.unitType.Millimeter; new makerjs.Collector(); } @@ -105,6 +106,7 @@ function test() { } function testMeasure() { + makerjs.measure.boundingHexagon(model).radius; makerjs.measure.increase(mp, mm); makerjs.measure.isPointEqual(p1, p2); makerjs.measure.isPathEqual(paths.line, paths.circle, 4); @@ -123,6 +125,7 @@ function test() { makerjs.measure.pointDistance([0,0], [9,9]); new makerjs.measure.Atlas(model); mm.low[0]; + mm.center; mp.high[1]; var s = makerjs.measure.lineSlope(paths.line); makerjs.measure.isPointOnSlope([], s); @@ -172,6 +175,10 @@ function test() { new makerjs.models.BoltCircle(7, 7, 7, 7), new makerjs.models.BoltRectangle(2, 2, 2), new makerjs.models.ConnectTheDots(true, [ [0,0], [1,1] ]), + new makerjs.models.ConnectTheDots([0, 0, 1, 1]), + new makerjs.models.ConnectTheDots(true, [0, 0, 1, 1]), + new makerjs.models.ConnectTheDots(true, '0, 0, 1, 1'), + new makerjs.models.ConnectTheDots('0, 0, 1, 1'), new makerjs.models.Dogbone(1,1,1), new makerjs.models.Dome(5, 7), new makerjs.models.Ellipse(2,2), @@ -255,7 +262,10 @@ function test() { } function testChain() { + makerjs.chain.cycle(chain, 7); makerjs.chain.fillet(chain, 1); + makerjs.chain.reverse(chain); + makerjs.chain.startAt(chain, ''); makerjs.chain.toKeyPoints(chain); makerjs.chain.toPoints(chain, 1); } diff --git a/material-ui/index.d.ts b/material-ui/index.d.ts index c399116482..529b9fe9fe 100644 --- a/material-ui/index.d.ts +++ b/material-ui/index.d.ts @@ -533,7 +533,7 @@ declare namespace __MaterialUI { type cornersAndCenter = 'bottom-center' | 'bottom-left' | 'bottom-right' | 'top-center' | 'top-left' | 'top-right'; } - interface AutoCompleteProps { + interface AutoCompleteProps extends TextFieldProps { anchorOrigin?: propTypes.origin; animated?: boolean; animation?: React.ComponentClass; @@ -723,6 +723,7 @@ declare namespace __MaterialUI { className?: string; disableTouchRipple?: boolean; disabled?: boolean; + hoveredStyle?: React.CSSProperties; iconClassName?: string; iconStyle?: React.CSSProperties; onBlur?: React.FocusEventHandler<{}>; @@ -1331,6 +1332,9 @@ declare namespace __MaterialUI { className?: string; maxHeight?: number; menuStyle?: any; + listStyle?: React.CSSProperties; + menuItemStyle?: React.CSSProperties; + selectedMenuItemStyle?: React.CSSProperties; openImmediately?: boolean; } export class SelectField extends React.Component { diff --git a/meteor/README.md b/meteor/README.md index 7c8aa5cb1d..f560dd005e 100644 --- a/meteor/README.md +++ b/meteor/README.md @@ -1,15 +1,8 @@ -# Meteor Type Definitions [DEPRECATED] - -## Deprecated - -These definitions for Meteor are now deprecated. They should still work for versions of Meteor up to 1.2.1. - -The canonical TypeScript definitions for Meteor can now be found using the NPM [Typings definition manager](https://www.npmjs.com/package/typings). If you prefer to view the definitions directly, or contribute to them, they can be found here: . - +# Meteor Type Definitions ## Description -These are the definitions for version 1.3 of Meteor. These definitions were generated from the from the same [Meteor data.js file] (https://github.com/meteor/meteor/blob/devel/docs/client/data.js) that is used to generate the official [Meteor docs] (http://docs.meteor.com/). The code that generates these definitions can be found [here](https://github.com/meteor-typescript/meteor-typescript-libs/). +These are the definitions for version 1.4 of Meteor. These definitions were generated from the from the same [Meteor data.js file] (https://github.com/meteor/meteor/blob/devel/docs/client/data.js) that is used to generate the official [Meteor docs] (http://docs.meteor.com/). The code that generates these definitions can be found [here](https://github.com/meteor-typescript/meteor-typescript-libs/). ## Upcoming Meteor `typescript` package diff --git a/meteor/index.d.ts b/meteor/index.d.ts index 0eb949e57b..b33973f943 100644 --- a/meteor/index.d.ts +++ b/meteor/index.d.ts @@ -1,915 +1,2143 @@ -// Type definitions for Meteor 1.3 +// Type definitions for Meteor 1.4 // Project: http://www.meteor.com/ -// Definitions by: Dave Allen +// Definitions by: Alex Borodach , Dave Allen , Olivier Refalo , Daniel Neveux , Birk Skyum // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/** - * These are the common (for client and server) modules and interfaces that can't be automatically generated from the Meteor data.js file - */ +interface URLS { + resetPassword: (token: string) => string; + verifyEmail: (token: string) => string; + enrollAccount: (token: string) => string; +} +declare module Accounts { + var urls: URLS; + + function user(): Meteor.User; + + function userId(): string; + + function createUser(options: { + username?: string; + email?: string; + password?: string; + profile?: Object; + }, callback?: Function): string; + + function config(options: { + sendVerificationEmail?: boolean; + forbidClientAccountCreation?: boolean; + restrictCreationByEmailDomain?: string | Function; + loginExpirationInDays?: number; + oauthSecretKey?: string; + }): void; + + function onLogin(func: Function): { + stop: () => void + }; + + function onLoginFailure(func: Function): { + stop: () => void + }; + + function loginServicesConfigured(): boolean; + + function onPageLoadLogin(func: Function): void; +} + +declare module "meteor/accounts-base" { + interface URLS { + resetPassword: (token: string) => string; + verifyEmail: (token: string) => string; + enrollAccount: (token: string) => string; + } + + module Accounts { + var urls: URLS; + + function user(): Meteor.User; + + function userId(): string; + + function createUser(options: { + username?: string; + email?: string; + password?: string; + profile?: Object; + }, callback?: Function): string; + + function config(options: { + sendVerificationEmail?: boolean; + forbidClientAccountCreation?: boolean; + restrictCreationByEmailDomain?: string | Function; + loginExpirationInDays?: number; + oauthSecretKey?: string; + }): void; + + function onLogin(func: Function): { + stop: () => void + }; + + function onLoginFailure(func: Function): { + stop: () => void + }; + + function loginServicesConfigured(): boolean; + + function onPageLoadLogin(func: Function): void; + } +} + +declare module Accounts { + function changePassword(oldPassword: string, newPassword: string, callback?: Function): void; + + function forgotPassword(options: { + email?: string; + }, callback?: Function): void; + + function resetPassword(token: string, newPassword: string, callback?: Function): void; + + function verifyEmail(token: string, callback?: Function): void; + + function onEmailVerificationLink(callback: Function): void; + + function onEnrollmentLink(callback: Function): void; + + function onResetPasswordLink(callback: Function): void; + + function loggingIn(): boolean; + + function logout(callback?: Function): void; + + function logoutOtherClients(callback?: Function): void; + + var ui: { + config(options: { + requestPermissions?: Object; + requestOfflineToken?: Object; + forceApprovalPrompt?: Object; + passwordSignupFields?: string; + }): void; + }; +} + +declare module "meteor/accounts-base" { + module Accounts { + function changePassword(oldPassword: string, newPassword: string, callback?: Function): void; + + function forgotPassword(options: { + email?: string; + }, callback?: Function): void; + + function resetPassword(token: string, newPassword: string, callback?: Function): void; + + function verifyEmail(token: string, callback?: Function): void; + + function onEmailVerificationLink(callback: Function): void; + + function onEnrollmentLink(callback: Function): void; + + function onResetPasswordLink(callback: Function): void; + + function loggingIn(): boolean; + + function logout(callback?: Function): void; + + function logoutOtherClients(callback?: Function): void; + + var ui: { + config(options: { + requestPermissions?: Object; + requestOfflineToken?: Object; + forceApprovalPrompt?: Object; + passwordSignupFields?: string; + }): void; + }; + } +} + +interface EmailFields { + from?: () => string; + subject?: (user: Meteor.User) => string; + text?: (user: Meteor.User, url: string) => string; + html?: (user: Meteor.User, url: string) => string; +} + +interface Header { + [id: string]: string; +} + +interface EmailTemplates { + from: string; + siteName: string; + headers?: Header; + resetPassword: EmailFields; + enrollAccount: EmailFields; + verifyEmail: EmailFields; +} + +declare module Accounts { + var emailTemplates: EmailTemplates; + + function addEmail(userId: string, newEmail: string, verified?: boolean): void; + + function removeEmail(userId: string, email: string): void; + + function onCreateUser(func: Function): void; + + function findUserByEmail(email: string): Object; + + function findUserByUsername(username: string): Object; + + function sendEnrollmentEmail(userId: string, email?: string): void; + + function sendResetPasswordEmail(userId: string, email?: string): void; + + function sendVerificationEmail(userId: string, email?: string): void; + + function setUsername(userId: string, newUsername: string): void; + + function setPassword(userId: string, newPassword: string, options?: { + logout?: Object; + }): void; + + function validateNewUser(func: Function): boolean; + + function validateLoginAttempt(func: Function): { + stop: () => void + }; + + function _hashPassword(password: string): { digest: string; algorithm: string; }; + + interface IValidateLoginAttemptCbOpts { + type: string; + allowed: boolean; + error: Meteor.Error; + user: Meteor.User; + connection: Meteor.Connection; + methodName: string; + methodArguments: any[]; + } +} + +declare module "meteor/accounts-base" { + interface EmailFields { + from?: () => string; + subject?: (user: Meteor.User) => string; + text?: (user: Meteor.User, url: string) => string; + html?: (user: Meteor.User, url: string) => string; + } + + interface Header { + [id: string]: string; + } + + interface EmailTemplates { + from: string; + siteName: string; + headers?: Header; + resetPassword: EmailFields; + enrollAccount: EmailFields; + verifyEmail: EmailFields; + } + + module Accounts { + var emailTemplates: EmailTemplates; + + function addEmail(userId: string, newEmail: string, verified?: boolean): void; + + function removeEmail(userId: string, email: string): void; + + function onCreateUser(func: Function): void; + + function findUserByEmail(email: string): Object; + + function findUserByUsername(username: string): Object; + + function sendEnrollmentEmail(userId: string, email?: string): void; + + function sendResetPasswordEmail(userId: string, email?: string): void; + + function sendVerificationEmail(userId: string, email?: string): void; + + function setUsername(userId: string, newUsername: string): void; + + function setPassword(userId: string, newPassword: string, options?: { + logout?: Object; + }): void; + + function validateNewUser(func: Function): boolean; + + function validateLoginAttempt(func: Function): { + stop: () => void + }; + + function _hashPassword(password: string): { digest: string; algorithm: string; }; + + interface IValidateLoginAttemptCbOpts { + type: string; + allowed: boolean; + error: Meteor.Error; + user: Meteor.User; + connection: Meteor.Connection; + methodName: string; + methodArguments: any[]; + } + } +} + +declare module Blaze { + var View: ViewStatic; + + interface ViewStatic { + new (name?: string, renderFunction?: Function): View; + } + + interface View { + name: string; + parentView: View; + isCreated: boolean; + isRendered: boolean; + isDestroyed: boolean; + renderCount: number; + autorun(runFunc: (computation: Tracker.Computation) => void): Tracker.Computation; + onViewCreated(func: Function): void; + onViewReady(func: Function): void; + onViewDestroyed(func: Function): void; + firstNode(): Node; + lastNode(): Node; + template: Template; + templateInstance(): TemplateInstance; + } + var currentView: View; + + function isTemplate(value: any): boolean; + + interface HelpersMap { + [key: string]: Function; + } + + interface EventsMap { + [key: string]: Function; + } + + var Template: TemplateStatic; + + interface TemplateStatic { + new (viewName?: string, renderFunction?: Function): Template; + + registerHelper(name: string, func: Function): void; + instance(): TemplateInstance; + currentData(): any; + parentData(numLevels: number): any; + } + + interface Template { + viewName: string; + renderFunction: Function; + constructView(): View; + head: Template; + find(selector: string): HTMLElement; + findAll(selector: string): HTMLElement[]; + $: any; + onCreated(cb: Function): void; + onRendered(cb: Function): void; + onDestroyed(cb: Function): void; + created: Function; + rendered: Function; + destroyed: Function; + helpers(helpersMap: HelpersMap): void; + events(eventsMap: EventsMap): void; + } + + var TemplateInstance: TemplateInstanceStatic; + + interface TemplateInstanceStatic { + new (view: View): TemplateInstance; + } + + interface TemplateInstance { + $(selector: string): any; + autorun(runFunc: (computation: Tracker.Computation) => void): Tracker.Computation; + data: Object; + find(selector: string): HTMLElement; + findAll(selector: string): HTMLElement[]; + firstNode: Object; + lastNode: Object; + subscribe(name: string, ...args: any[]): Meteor.SubscriptionHandle; + subscriptionsReady(): boolean; + view: Object; + } + + function Each(argFunc: Function, contentFunc: Function, elseFunc?: Function): View; + + function Unless(conditionFunc: Function, contentFunc: Function, elseFunc?: Function): View; + + function If(conditionFunc: Function, contentFunc: Function, elseFunc?: Function): View; + + function Let(bindings: Function, contentFunc: Function): View; + + function With(data: Object | Function, contentFunc: Function): View; + + function getData(elementOrView?: HTMLElement | View): Object; + + function getView(element?: HTMLElement): View; + + function remove(renderedView: View): void; + + function render(templateOrView: Template | View, parentNode: Node, nextNode?: Node, parentView?: View): View; + + function renderWithData(templateOrView: Template | View, data: Object | Function, parentNode: Node, nextNode?: Node, parentView?: View): View; + + function toHTML(templateOrView: Template | View): string; + + function toHTMLWithData(templateOrView: Template | View, data: Object | Function): string; +} + +declare module "meteor/blaze" { + module Blaze { + var View: ViewStatic; + + interface ViewStatic { + new (name?: string, renderFunction?: Function): View; + } + + interface View { + name: string; + parentView: View; + isCreated: boolean; + isRendered: boolean; + isDestroyed: boolean; + renderCount: number; + autorun(runFunc: (computation: Tracker.Computation) => void): Tracker.Computation; + onViewCreated(func: Function): void; + onViewReady(func: Function): void; + onViewDestroyed(func: Function): void; + firstNode(): Node; + lastNode(): Node; + template: Template; + templateInstance(): TemplateInstance; + } + var currentView: View; + + function isTemplate(value: any): boolean; + + interface HelpersMap { + [key: string]: Function; + } + + interface EventsMap { + [key: string]: Function; + } + + var Template: TemplateStatic; + + interface TemplateStatic { + new (viewName?: string, renderFunction?: Function): Template; + + registerHelper(name: string, func: Function): void; + instance(): TemplateInstance; + currentData(): any; + parentData(numLevels: number): any; + } + + interface Template { + viewName: string; + renderFunction: Function; + constructView(): View; + head: Template; + find(selector: string): HTMLElement; + findAll(selector: string): HTMLElement[]; + $: any; + onCreated(cb: Function): void; + onRendered(cb: Function): void; + onDestroyed(cb: Function): void; + created: Function; + rendered: Function; + destroyed: Function; + helpers(helpersMap: HelpersMap): void; + events(eventsMap: EventsMap): void; + } + + var TemplateInstance: TemplateInstanceStatic; + + interface TemplateInstanceStatic { + new (view: View): TemplateInstance; + } + + interface TemplateInstance { + $(selector: string): any; + autorun(runFunc: (computation: Tracker.Computation) => void): Tracker.Computation; + data: Object; + find(selector: string): HTMLElement; + findAll(selector: string): HTMLElement[]; + firstNode: Object; + lastNode: Object; + subscribe(name: string, ...args: any[]): Meteor.SubscriptionHandle; + subscriptionsReady(): boolean; + view: Object; + } + + function Each(argFunc: Function, contentFunc: Function, elseFunc?: Function): View; + + function Unless(conditionFunc: Function, contentFunc: Function, elseFunc?: Function): View; + + function If(conditionFunc: Function, contentFunc: Function, elseFunc?: Function): View; + + function Let(bindings: Function, contentFunc: Function): View; + + function With(data: Object | Function, contentFunc: Function): View; + + function getData(elementOrView?: HTMLElement | View): Object; + + function getView(element?: HTMLElement): View; + + function remove(renderedView: View): void; + + function render(templateOrView: Template | View, parentNode: Node, nextNode?: Node, parentView?: View): View; + + function renderWithData(templateOrView: Template | View, data: Object | Function, parentNode: Node, nextNode?: Node, parentView?: View): View; + + function toHTML(templateOrView: Template | View): string; + + function toHTMLWithData(templateOrView: Template | View, data: Object | Function): string; + } +} + +declare module BrowserPolicy { + var framing: { + disallow(): void; + restrictToOrigin(origin: string): void; + allowAll(): void; + }; + + var content: { + allowEval(): void; + allowInlineStyles(): void; + allowInlineScripts(): void; + allowSameOriginForAll(): void; + allowDataUrlForAll(): void; + allowOriginForAll(origin: string): void; + allowImageOrigin(origin: string): void; + allowMediaOrigin(origin: string): void; + allowFontOrigin(origin: string): void; + allowStyleOrigin(origin: string): void; + allowScriptOrigin(origin: string): void; + allowFrameOrigin(origin: string): void; + allowContentTypeSniffing(): void; + allowAllContentOrigin(): void; + allowAllContentDataUrl(): void; + allowAllContentSameOrigin(): void; + + disallowAll(): void; + disallowInlineStyles(): void; + disallowEval(): void; + disallowInlineScripts(): void; + disallowFont(): void; + disallowObject(): void; + disallowAllContent(): void; + }; +} + +declare module "meteor/browser-policy-common" { + module BrowserPolicy { + var framing: { + disallow(): void; + restrictToOrigin(origin: string): void; + allowAll(): void; + }; + + var content: { + allowEval(): void; + allowInlineStyles(): void; + allowInlineScripts(): void; + allowSameOriginForAll(): void; + allowDataUrlForAll(): void; + allowOriginForAll(origin: string): void; + allowImageOrigin(origin: string): void; + allowMediaOrigin(origin: string): void; + allowFontOrigin(origin: string): void; + allowStyleOrigin(origin: string): void; + allowScriptOrigin(origin: string): void; + allowFrameOrigin(origin: string): void; + allowContentTypeSniffing(): void; + allowAllContentOrigin(): void; + allowAllContentDataUrl(): void; + allowAllContentSameOrigin(): void; + + disallowAll(): void; + disallowInlineStyles(): void; + disallowEval(): void; + disallowInlineScripts(): void; + disallowFont(): void; + disallowObject(): void; + disallowAllContent(): void; + }; + } +} + +declare module Match { + var Any: any; + var String: any; + var Integer: any; + var Boolean: any; + var undefined: any; + var Object: any; + + function Optional(pattern: any): boolean; + + function ObjectIncluding(dico: any): boolean; + + function OneOf(...patterns: any[]): any; + + function Where(condition: any): any; + + function test(value: any, pattern: any): boolean; +} + +declare function check(value: any, pattern: any): void; + +declare module "meteor/check" { + module Match { + var Any: any; + var String: any; + var Integer: any; + var Boolean: any; + var undefined: any; + var Object: any; + + function Optional(pattern: any): boolean; + + function ObjectIncluding(dico: any): boolean; + + function OneOf(...patterns: any[]): any; + + function Where(condition: any): any; + + function test(value: any, pattern: any): boolean; + } + + function check(value: any, pattern: any): void; +} + +declare module DDPRateLimiter { + interface Matcher { + type?: string | ((type: string) => boolean); + name?: string | ((name: string) => boolean); + userId?: string | ((userId: string) => boolean); + connectionId?: string | ((connectionId: string) => boolean); + clientAddress?: string | ((clientAddress: string) => boolean); + } + + function addRule(matcher: Matcher, numRequests: number, timeInterval: number): string; + + function removeRule(ruleId: string): boolean; +} + +declare module "meteor/ddp-rate-limiter" { + module DDPRateLimiter { + interface Matcher { + type?: string | ((type: string) => boolean); + name?: string | ((name: string) => boolean); + userId?: string | ((userId: string) => boolean); + connectionId?: string | ((connectionId: string) => boolean); + clientAddress?: string | ((clientAddress: string) => boolean); + } + + function addRule(matcher: Matcher, numRequests: number, timeInterval: number): string; + + function removeRule(ruleId: string): boolean; + } +} + +declare module DDP { + interface DDPStatic { + subscribe(name: string, ...rest: any[]): Meteor.SubscriptionHandle; + call(method: string, ...parameters: any[]): void; + apply(method: string, ...parameters: any[]): void; + methods(IMeteorMethodsDictionary: any): any; + status(): DDPStatus; + reconnect(): void; + disconnect(): void; + onReconnect(): void; + } + + function _allSubscriptionsReady(): boolean; + + type Status = 'connected' | 'connecting' | 'failed' | 'waiting' | 'offline'; + + interface DDPStatus { + connected: boolean; + status: Status; + retryCount: number; + retryTime?: number; + reason?: string; + } + + function connect(url: string): DDPStatic; +} + +declare module DDPCommon { + interface MethodInvocation { + new (options: {}): MethodInvocation; + + unblock(): void; + + setUserId(userId: number): void; + } +} + +declare module "meteor/ddp" { + module DDP { + interface DDPStatic { + subscribe(name: string, ...rest: any[]): Meteor.SubscriptionHandle; + call(method: string, ...parameters: any[]): void; + apply(method: string, ...parameters: any[]): void; + methods(IMeteorMethodsDictionary: any): any; + status(): DDPStatus; + reconnect(): void; + disconnect(): void; + onReconnect(): void; + } + + function _allSubscriptionsReady(): boolean; + + type Status = 'connected' | 'connecting' | 'failed' | 'waiting' | 'offline'; + + interface DDPStatus { + connected: boolean; + status: Status; + retryCount: number; + retryTime?: number; + reason?: string; + } + + function connect(url: string): DDPStatic; + } + + module DDPCommon { + interface MethodInvocation { + new (options: {}): MethodInvocation; + + unblock(): void; + + setUserId(userId: number): void; + } + } +} + +interface EJSONableCustomType { + clone(): EJSONableCustomType; + equals(other: Object): boolean; + toJSONValue(): JSONable; + typeName(): string; +} interface EJSONable { - [key: string]: number | string | boolean | Object | number[] | string[] | Object[] | Date | Uint8Array | EJSON.CustomType; + [key: string]: number | string | boolean | Object | number[] | string[] | Object[] | Date | Uint8Array | EJSONableCustomType; } interface JSONable { - [key: string]: number | string | boolean | Object | number[] | string[] | Object[]; + [key: string]: number | string | boolean | Object | number[] | string[] | Object[]; } -interface EJSON extends EJSONable {} +interface EJSON extends EJSONable { } -declare namespace Match { - var Any: any; - var String: any; - var Integer: any; - var Boolean: any; - var undefined: any; - //function null(); // not allowed in TypeScript - var Object: any; - function Optional(pattern: any):boolean; - function ObjectIncluding(dico: any):boolean; - function OneOf(...patterns: any[]): any; - function Where(condition: any): any; +declare module EJSON { + function addType(name: string, factory: (val: JSONable) => EJSONableCustomType): void; + + function clone(val: T): T; + + function equals(a: EJSON, b: EJSON, options?: { + keyOrderSensitive?: boolean; + }): boolean; + + function fromJSONValue(val: JSONable): any; + + function isBinary(x: Object): boolean; + var newBinary: any; + + function parse(str: string): EJSON; + + function stringify(val: EJSON, options?: { + indent?: boolean | number | string; + canonical?: boolean; + }): string; + + function toJSONValue(val: EJSON): JSONable; } -declare namespace Meteor { - interface UserEmail { - address:string; - verified:boolean; - } +declare module "meteor/ejson" { + interface EJSONableCustomType { + clone(): EJSONableCustomType; + equals(other: Object): boolean; + toJSONValue(): JSONable; + typeName(): string; + } + interface EJSONable { + [key: string]: number | string | boolean | Object | number[] | string[] | Object[] | Date | Uint8Array | EJSONableCustomType; + } + interface JSONable { + [key: string]: number | string | boolean | Object | number[] | string[] | Object[]; + } + interface EJSON extends EJSONable { } - interface User { - _id?:string; - username?:string; - emails?:Meteor.UserEmail[]; - createdAt?: number; - profile?: any; - services?: any; - } + module EJSON { + function addType(name: string, factory: (val: JSONable) => EJSONableCustomType): void; - enum StatusEnum { - connected, - connecting, - failed, - waiting, - offline - } + function clone(val: T): T; - interface LiveQueryHandle { - stop(): void; - } + function equals(a: EJSON, b: EJSON, options?: { + keyOrderSensitive?: boolean; + }): boolean; + + function fromJSONValue(val: JSONable): any; + + function isBinary(x: Object): boolean; + var newBinary: any; + + function parse(str: string): EJSON; + + function stringify(val: EJSON, options?: { + indent?: boolean | number | string; + canonical?: boolean; + }): string; + + function toJSONValue(val: EJSON): JSONable; + } } -declare namespace DDP { - interface DDPStatic { - subscribe(name: string, ...rest: any[]): Meteor.SubscriptionHandle; - call(method: string, ...parameters: any[]):void; - apply(method: string, ...parameters: any[]):void; - methods(IMeteorMethodsDictionary: any): any; - status():DDPStatus; - reconnect(): void; - disconnect(): void; - onReconnect(): void; - } - - interface DDPStatus { - connected: boolean; - status: Meteor.StatusEnum; - retryCount: number; - //To turn this into an interval until the next reconnection, use retryTime - (new Date()).getTime() - retryTime?: number; - reason?: string; - } -} - -declare namespace Mongo { - interface Selector { - [key: string]:any; - } - interface Selector extends Object {} - interface Modifier {} - interface SortSpecifier {} - interface FieldSpecifier { - [id: string]: Number; - } -} - -declare namespace HTTP { - - interface HTTPRequest { - content?:string; - data?:any; - query?:string; - params?:{[id:string]:string}; - auth?:string; - headers?:{[id:string]:string}; - timeout?:number; - followRedirects?:boolean; - } - - interface HTTPResponse { - statusCode?:number; - headers?:{[id:string]: string}; - content?:string; - data?:any; - } - - function call(method: string, url: string, options?: HTTP.HTTPRequest, asyncCallback?:Function):HTTP.HTTPResponse; - function del(url: string, callOptions?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; - function get(url: string, callOptions?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; - function post(url: string, callOptions?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; - function put(url: string, callOptions?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; -} - -declare namespace Random { - function id(numberOfChars?: number): string; - function secret(numberOfChars?: number): string; - function fraction():number; - function hexString(numberOfDigits:number):string; // @param numberOfDigits, @returns a random hex string of the given length - function choice(array:any[]):string; // @param array, @return a random element in array - function choice(str:string):string; // @param str, @return a random char in str -} - -declare namespace Accounts { - function loginServicesConfigured(): boolean; - - function onPageLoadLogin(func: Function): void; -} -/** - * These are the client modules and interfaces that can't be automatically generated from the Meteor data.js file - */ - -declare namespace Meteor { - /** Start definitions for Template **/ - export interface Event { - type:string; - target:HTMLElement; - currentTarget:HTMLElement; - which: number; - stopPropagation():void; - stopImmediatePropagation():void; - preventDefault():void; - isPropagationStopped():boolean; - isImmediatePropagationStopped():boolean; - isDefaultPrevented():boolean; - } - - interface EventHandlerFunction extends Function { - (event?:Meteor.Event, templateInstance?: Blaze.TemplateInstance):void; - } - - interface EventMap { - [id:string]:Meteor.EventHandlerFunction; - } - /** End definitions for Template **/ - - interface LoginWithExternalServiceOptions { - requestPermissions?: string[]; - requestOfflineToken?: boolean; - loginUrlParameters?: {[param: string]: any} - loginHint?: string; - loginStyle?: string; - redirectUrl?: "popup" | "redirect"; - profile?: any; - email?: string; - } - - function loginWithMeteorDeveloperAccount(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; - function loginWithFacebook(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; - function loginWithGithub(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; - function loginWithGoogle(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; - function loginWithMeetup(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; - function loginWithTwitter(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; - function loginWithWeibo(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; - function _sleepForMs(milliseconds: number): void; - - interface SubscriptionHandle { - stop(): void; - ready(): boolean; - } -} - -declare namespace Blaze { - interface View { - name: string; - parentView: Blaze.View; - isCreated: boolean; - isRendered: boolean; - isDestroyed: boolean; - renderCount: number; - autorun(runFunc: Function): void; - onViewCreated(func: Function): void; - onViewReady(func: Function): void; - onViewDestroyed(func: Function): void; - firstNode(): Node; - lastNode(): Node; - template: Blaze.Template; - templateInstance(): any; - } - interface Template { - viewName: string; - renderFunction: Function; - constructView(): Blaze.View; - } -} - -declare namespace BrowserPolicy { - - interface framing { - disallow():void; - restrictToOrigin(origin:string):void; - allowAll():void; - } - interface content { - allowEval():void; - allowInlineStyles():void; - allowInlineScripts():void; - allowSameOriginForAll():void; - allowDataUrlForAll():void; - allowOriginForAll(origin:string):void; - allowImageOrigin(origin:string):void; - allowFrameOrigin(origin:string):void; - allowContentTypeSniffing():void; - allowAllContentOrigin():void; - allowAllContentDataUrl():void; - allowAllContentSameOrigin():void; - - disallowAll():void; - disallowInlineStyles():void; - disallowEval():void; - disallowInlineScripts():void; - disallowFont():void; - disallowObject():void; - disallowAllContent():void; - //TODO: add the basic content types - // allowOrigin(origin) - // allowDataUrl() - // allowSameOrigin() - // disallow() - } -} - - -/** - * These are the server modules and interfaces that can't be automatically generated from the Meteor data.js file - */ - -declare namespace Meteor { - interface EmailFields { - from?: () => string; - subject?: (user: Meteor.User) => string; - text?: (user: Meteor.User, url: string) => string; - html?: (user: Meteor.User, url: string) => string; - } - - interface EmailTemplates { - from?: string; - siteName?: string; - headers?: { [id: string]: string }; // TODO: should define IHeaders interface - resetPassword?: Meteor.EmailFields; - enrollAccount?: Meteor.EmailFields; - verifyEmail?: Meteor.EmailFields; - } - - interface Connection { - id: string; - close: Function; - onClose: Function; - clientAddress: string; - httpHeaders: Object; - } - - interface IValidateLoginAttemptCbOpts { - type: string; - allowed: boolean; - error: Error; - user: Meteor.User; - connection: Meteor.Connection; - methodName: string; - methodArguments: any[]; - } -} - -declare namespace Mongo { - interface AllowDenyOptions { - insert?: (userId: string, doc: any) => boolean; - update?: (userId: string, doc: any, fieldNames: string[], modifier: any) => boolean; - remove?: (userId: string, doc: any) => boolean; - fetch?: string[]; - transform?: Function; - } -} - -declare namespace Accounts { - interface IValidateLoginAttemptCbOpts { - type?: string; - allowed?: boolean; - error?: Meteor.Error; - user?: Meteor.User; - connection?: Meteor.Connection; - methodName?: string; - methodArguments?: any[]; - } +declare module Email { + function send(options: { + from?: string; + to?: string | string[]; + cc?: string | string[]; + bcc?: string | string[]; + replyTo?: string | string[]; + subject?: string; + text?: string; + html?: string; + headers?: Object; + attachments?: Object[]; + mailComposer?: MailComposer; + }): void; } interface MailComposerOptions { - escapeSMTP: boolean; - encoding: string; - charset: string; - keepBcc: boolean; - forceEmbeddedImages: boolean; + escapeSMTP: boolean; + encoding: string; + charset: string; + keepBcc: boolean; + forceEmbeddedImages: boolean; } declare var MailComposer: MailComposerStatic; interface MailComposerStatic { - new(options: MailComposerOptions): MailComposer; + new (options: MailComposerOptions): MailComposer; } interface MailComposer { - addHeader(name: string, value: string): void; - setMessageOption(from: string, to: string, body: string, html: string): void; - streamMessage(): void; - pipe(stream: any /** fs.WriteStream **/): void; -} -/** - * These are the modules and interfaces for packages that can't be automatically generated from the Meteor data.js file - */ - -interface ILengthAble { - length: number; + addHeader(name: string, value: string): void; + setMessageOption(from: string, to: string, body: string, html: string): void; + streamMessage(): void; + pipe(stream: any /** fs.WriteStream **/): void; } -interface ITinytestAssertions { - ok(doc: Object): void; - expect_fail(): void; - fail(doc: Object): void; - runId(): string; - equal(actual: T, expected: T, message?: string, not?: boolean): void; - notEqual(actual: T, expected: T, message?: string): void; - instanceOf(obj : Object, klass: Function, message?: string): void; - notInstanceOf(obj : Object, klass: Function, message?: string): void; - matches(actual : any, regexp: RegExp, message?: string): void; - notMatches(actual : any, regexp: RegExp, message?: string): void; - throws(f: Function, expected?: string|RegExp): void; - isTrue(v: boolean, msg?: string): void; - isFalse(v: boolean, msg?: string): void; - isNull(v: any, msg?: string): void; - isNotNull(v: any, msg?: string): void; - isUndefined(v: any, msg?: string): void; - isNotUndefined(v: any, msg?: string): void; - isNan(v: any, msg?: string): void; - isNotNan(v: any, msg?: string): void; - include(s: Array|Object|string, value: any, msg?: string, not?: boolean): void; +declare module "meteor/email" { + module Email { + function send(options: { + from?: string; + to?: string | string[]; + cc?: string | string[]; + bcc?: string | string[]; + replyTo?: string | string[]; + subject?: string; + text?: string; + html?: string; + headers?: Object; + attachments?: Object[]; + mailComposer?: MailComposer; + }): void; + } - notInclude(s: Array|Object|string, value: any, msg?: string, not?: boolean): void; - length(obj: ILengthAble, expected_length: number, msg?: string): void; - _stringEqual(actual: string, expected: string, msg?: string): void; + interface MailComposerOptions { + escapeSMTP: boolean; + encoding: string; + charset: string; + keepBcc: boolean; + forceEmbeddedImages: boolean; + } + + var MailComposer: MailComposerStatic; + interface MailComposerStatic { + new (options: MailComposerOptions): MailComposer; + } + interface MailComposer { + addHeader(name: string, value: string): void; + setMessageOption(from: string, to: string, body: string, html: string): void; + streamMessage(): void; + pipe(stream: any /** fs.WriteStream **/): void; + } } -declare namespace Tinytest { - function add(description : string , func : (test : ITinytestAssertions) => void) : void; - function addAsync(description : string , func : (test : ITinytestAssertions) => void) : void; +declare module HTTP { + interface HTTPRequest { + content?: string; + data?: any; + query?: string; + params?: { + [id: string]: string + }; + auth?: string; + headers?: { + [id: string]: string + }; + timeout?: number; + followRedirects?: boolean; + } + + interface HTTPResponse { + statusCode?: number; + headers?: { + [id: string]: string + }; + content?: string; + data?: any; + } + + function call(method: string, url: string, options?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; + + function del(url: string, callOptions?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; + + function get(url: string, callOptions?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; + + function post(url: string, callOptions?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; + + function put(url: string, callOptions?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; + + function call(method: string, url: string, options?: { + content?: string; + data?: Object; + query?: string; + params?: Object; + auth?: string; + headers?: Object; + timeout?: number; + followRedirects?: boolean; + npmRequestOptions?: Object; + beforeSend?: Function; + }, asyncCallback?: Function): HTTP.HTTPResponse; } -// Kept in for backwards compatibility -declare namespace Meteor { - interface Tinytest { - add(description : string , func : (test : ITinytestAssertions) => void) : void; - addAsync(description : string , func : (test : ITinytestAssertions) => void) : void; - } +declare module "meteor/http" { + module HTTP { + interface HTTPRequest { + content?: string; + data?: any; + query?: string; + params?: { + [id: string]: string + }; + auth?: string; + headers?: { + [id: string]: string + }; + timeout?: number; + followRedirects?: boolean; + } + + interface HTTPResponse { + statusCode?: number; + headers?: { + [id: string]: string + }; + content?: string; + data?: any; + } + + function call(method: string, url: string, options?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; + + function del(url: string, callOptions?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; + + function get(url: string, callOptions?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; + + function post(url: string, callOptions?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; + + function put(url: string, callOptions?: HTTP.HTTPRequest, asyncCallback?: Function): HTTP.HTTPResponse; + + function call(method: string, url: string, options?: { + content?: string; + data?: Object; + query?: string; + params?: Object; + auth?: string; + headers?: Object; + timeout?: number; + followRedirects?: boolean; + npmRequestOptions?: Object; + beforeSend?: Function; + }, asyncCallback?: Function): HTTP.HTTPResponse; + } } -declare namespace Accounts { - function addEmail(userId: string, newEmail: string, verified?: boolean): void; - function changePassword(oldPassword: string, newPassword: string, callback?: Function): void; - function createUser(options: { - username?: string; - email?: string; - password?: string; - profile?: Object; - }, callback?: Function): string; - var emailTemplates: Meteor.EmailTemplates; - function findUserByEmail(email: string): Object; - function findUserByUsername(username: string): Object; - function forgotPassword(options: { - email?: string; - }, callback?: Function): void; - function onEmailVerificationLink(callback: Function): void; - function onEnrollmentLink(callback: Function): void; - function onResetPasswordLink(callback: Function): void; - function removeEmail(userId: string, email: string): void; - function resetPassword(token: string, newPassword: string, callback?: Function): void; - function sendEnrollmentEmail(userId: string, email?: string): void; - function sendResetPasswordEmail(userId: string, email?: string): void; - function sendVerificationEmail(userId: string, email?: string): void; - function setPassword(userId: string, newPassword: string, options?: { - logout?: Object; - }): void; - function setUsername(userId: string, newUsername: string): void; - var ui: { - config(options: { - requestPermissions?: Object; - requestOfflineToken?: Object; - forceApprovalPrompt?: Object; - passwordSignupFields?: string; - }): void; - }; - function verifyEmail(token: string, callback?: Function): void; - function config(options: { - sendVerificationEmail?: boolean; - forbidClientAccountCreation?: boolean; - restrictCreationByEmailDomain?: string | Function; - loginExpirationInDays?: number; - oauthSecretKey?: string; - }): void; - function onLogin(func: Function): { stop: () => void }; - function onLoginFailure(func: Function): { stop: () => void }; - function user(): Meteor.User; - function userId(): string; - function loggingIn(): boolean; - function logout(callback?: Function): void; - function logoutOtherClients(callback?: Function): void; - function onCreateUser(func: Function): void; - function validateLoginAttempt(cb: (params: Accounts.IValidateLoginAttemptCbOpts) => boolean): { stop: () => void }; - function validateNewUser(func: Function): boolean; - function _hashPassword(password: string): { digest: string; algorithm: string; }; +declare module Meteor { + /** Global props **/ + var isClient: boolean; + var isCordova: boolean; + var isServer: boolean; + var isProduction: boolean; + var release: string; + /** Global props **/ + + /** Settings **/ + interface Settings { + public: { + [id: string]: any + }, [id: string]: any + } + var settings: Settings; + /** Settings **/ + + /** User **/ + interface UserEmail { + address: string; + verified: boolean; + } + interface User { + _id?: string; + username?: string; + emails?: UserEmail[]; + createdAt?: number; + profile?: any; + services?: any; + } + + function user(): User; + + function userId(): string; + var users: Mongo.Collection; + /** User **/ + + /** Error **/ + var Error: ErrorStatic; + interface ErrorStatic { + new (error: string | number, reason?: string, details?: string): Error; + } + interface Error { + error: string | number; + reason?: string; + details?: string; + } + /** Error **/ + + /** Method **/ + function methods(methods: Object): void; + + function call(name: string, ...args: any[]): any; + + function apply(name: string, args: EJSONable[], options?: { + wait?: boolean; + onResultReceived?: Function; + }, asyncCallback?: Function): any; + /** Method **/ + + /** Url **/ + function absoluteUrl(path?: string, options?: { + secure?: boolean; + replaceLocalhost?: boolean; + rootUrl?: string; + }): string; + /** Url **/ + + /** Timeout **/ + function setInterval(func: Function, delay: number): number; + + function setTimeout(func: Function, delay: number): number; + + function clearInterval(id: number): void; + + function clearTimeout(id: number): void; + + function defer(func: Function): void; + /** Timeout **/ + + /** utils **/ + function startup(func: Function): void; + + function wrapAsync(func: Function, context?: Object): any; + + function bindEnvironment(func: Function): any; + /** utils **/ + + /** Pub/Sub **/ + interface SubscriptionHandle { + stop(): void; + ready(): boolean; + } + interface LiveQueryHandle { + stop(): void; + } + /** Pub/Sub **/ } -declare namespace App { - function accessRule(pattern: string, options?: { - type?: string; - launchExternal?: boolean; - }): void; - function configurePlugin(id: string, config: Object): void; - function icons(icons: Object): void; - function info(options: { - id?: string; - version?: string; - name?: string; - description?: string; - author?: string; - email?: string; - website?: string; - }): void; - function launchScreens(launchScreens: Object): void; - function setPreference(name: string, value: string, platform?: string): void; +declare module "meteor/meteor" { + module Meteor { + /** Global props **/ + var isClient: boolean; + var isCordova: boolean; + var isServer: boolean; + var isProduction: boolean; + var release: string; + /** Global props **/ + + /** Settings **/ + interface Settings { + public: { + [id: string]: any + }, [id: string]: any + } + var settings: Settings; + /** Settings **/ + + /** User **/ + interface UserEmail { + address: string; + verified: boolean; + } + interface User { + _id?: string; + username?: string; + emails?: UserEmail[]; + createdAt?: number; + profile?: any; + services?: any; + } + + function user(): User; + + function userId(): string; + var users: Mongo.Collection; + /** User **/ + + /** Error **/ + var Error: ErrorStatic; + interface ErrorStatic { + new (error: string | number, reason?: string, details?: string): Error; + } + interface Error { + error: string | number; + reason?: string; + details?: string; + } + /** Error **/ + + /** Method **/ + function methods(methods: Object): void; + + function call(name: string, ...args: any[]): any; + + function apply(name: string, args: EJSONable[], options?: { + wait?: boolean; + onResultReceived?: Function; + }, asyncCallback?: Function): any; + /** Method **/ + + /** Url **/ + function absoluteUrl(path?: string, options?: { + secure?: boolean; + replaceLocalhost?: boolean; + rootUrl?: string; + }): string; + /** Url **/ + + /** Timeout **/ + function setInterval(func: Function, delay: number): number; + + function setTimeout(func: Function, delay: number): number; + + function clearInterval(id: number): void; + + function clearTimeout(id: number): void; + + function defer(func: Function): void; + /** Timeout **/ + + /** utils **/ + function startup(func: Function): void; + + function wrapAsync(func: Function, context?: Object): any; + + function bindEnvironment(func: Function): any; + /** utils **/ + + /** Pub/Sub **/ + interface SubscriptionHandle { + stop(): void; + ready(): boolean; + } + interface LiveQueryHandle { + stop(): void; + } + /** Pub/Sub **/ + } } -declare namespace Assets { - function getBinary(assetPath: string, asyncCallback?: Function): EJSON; - function getText(assetPath: string, asyncCallback?: Function): string; +declare module Meteor { + /** Login **/ + interface LoginWithExternalServiceOptions { + requestPermissions?: string[]; + requestOfflineToken?: Boolean; + forceApprovalPrompt?: Boolean; + loginUrlParameters?: Object; + redirectUrl?: string; + loginHint?: string; + loginStyle?: string; + } + + function loginWithMeteorDeveloperAccount(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + + function loginWithFacebook(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + + function loginWithGithub(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + + function loginWithGoogle(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + + function loginWithMeetup(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + + function loginWithTwitter(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + + function loginWithWeibo(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + + function loggingIn(): boolean; + + function loginWith(options?: { + requestPermissions?: string[]; + requestOfflineToken?: boolean; + loginUrlParameters?: Object; + userEmail?: string; + loginStyle?: string; + redirectUrl?: string; + }, callback?: Function): void; + + function loginWithPassword(user: Object | string, password: string, callback?: Function): void; + + function loginWithToken(token: string, callback?: Function): void; + + function logout(callback?: Function): void; + + function logoutOtherClients(callback?: Function): void; + /** Login **/ + + /** Event **/ + interface Event { + type: string; + target: HTMLElement; + currentTarget: HTMLElement; + which: number; + stopPropagation(): void; + stopImmediatePropagation(): void; + preventDefault(): void; + isPropagationStopped(): boolean; + isImmediatePropagationStopped(): boolean; + isDefaultPrevented(): boolean; + } + interface EventHandlerFunction extends Function { + (event?: Meteor.Event, templateInstance?: Blaze.TemplateInstance): void; + } + interface EventMap { + [id: string]: Meteor.EventHandlerFunction; + } + /** Event **/ + + /** Connection **/ + function reconnect(): void; + + function disconnect(): void; + /** Connection **/ + + /** Status **/ + function status(): DDP.DDPStatus; + /** Status **/ + + /** Pub/Sub **/ + function subscribe(name: string, ...args: any[]): Meteor.SubscriptionHandle; + /** Pub/Sub **/ } -declare namespace Blaze { - function Each(argFunc: Function, contentFunc: Function, elseFunc?: Function): Blaze.View; - function If(conditionFunc: Function, contentFunc: Function, elseFunc?: Function): Blaze.View; - function Let(bindings: Function, contentFunc: Function): Blaze.View; - var Template: TemplateStatic; - interface TemplateStatic { - new(viewName?: string, renderFunction?: Function): Template; - // It should be [templateName: string]: TemplateInstance but this is not possible -- user will need to cast to TemplateInstance - [templateName: string]: any | Template; // added "any" to make it work - head: Template; - find(selector:string):Blaze.Template; - findAll(selector:string):Blaze.Template[]; - $:any; - } - interface Template { - } +declare module "meteor/meteor" { + module Meteor { + /** Login **/ + interface LoginWithExternalServiceOptions { + requestPermissions?: string[]; + requestOfflineToken?: Boolean; + forceApprovalPrompt?: Boolean; + loginUrlParameters?: Object; + redirectUrl?: string; + loginHint?: string; + loginStyle?: string; + } - var TemplateInstance: TemplateInstanceStatic; - interface TemplateInstanceStatic { - new(view: Blaze.View): TemplateInstance; - } - interface TemplateInstance { - $(selector: string): any; - autorun(runFunc: Function): Object; - data: Object; - find(selector?: string): Blaze.TemplateInstance; - findAll(selector: string): Blaze.TemplateInstance[]; - firstNode: Object; - lastNode: Object; - subscribe(name: string, ...args: any[]): Meteor.SubscriptionHandle; - subscriptionsReady(): boolean; - view: Object; - } + function loginWithMeteorDeveloperAccount(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; - function Unless(conditionFunc: Function, contentFunc: Function, elseFunc?: Function): Blaze.View; - var View: ViewStatic; - interface ViewStatic { - new(name?: string, renderFunction?: Function): View; - } - interface View { - } + function loginWithFacebook(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; - function With(data: Object | Function, contentFunc: Function): Blaze.View; - var currentView: Blaze.View; - function getData(elementOrView?: HTMLElement | Blaze.View): Object; - function getView(element?: HTMLElement): Blaze.View; - function isTemplate(value: any): boolean; - function remove(renderedView: Blaze.View): void; - function render(templateOrView: Template | Blaze.View, parentNode: Node, nextNode?: Node, parentView?: Blaze.View): Blaze.View; - function renderWithData(templateOrView: Template | Blaze.View, data: Object | Function, parentNode: Node, nextNode?: Node, parentView?: Blaze.View): Blaze.View; - function toHTML(templateOrView: Template | Blaze.View): string; - function toHTMLWithData(templateOrView: Template | Blaze.View, data: Object | Function): string; + function loginWithGithub(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + + function loginWithGoogle(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + + function loginWithMeetup(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + + function loginWithTwitter(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + + function loginWithWeibo(options?: Meteor.LoginWithExternalServiceOptions, callback?: Function): void; + + function loggingIn(): boolean; + + function loginWith(options?: { + requestPermissions?: string[]; + requestOfflineToken?: boolean; + loginUrlParameters?: Object; + userEmail?: string; + loginStyle?: string; + redirectUrl?: string; + }, callback?: Function): void; + + function loginWithPassword(user: Object | string, password: string, callback?: Function): void; + + function loginWithToken(token: string, callback?: Function): void; + + function logout(callback?: Function): void; + + function logoutOtherClients(callback?: Function): void; + /** Login **/ + + /** Event **/ + interface Event { + type: string; + target: HTMLElement; + currentTarget: HTMLElement; + which: number; + stopPropagation(): void; + stopImmediatePropagation(): void; + preventDefault(): void; + isPropagationStopped(): boolean; + isImmediatePropagationStopped(): boolean; + isDefaultPrevented(): boolean; + } + interface EventHandlerFunction extends Function { + (event?: Meteor.Event, templateInstance?: Blaze.TemplateInstance): void; + } + interface EventMap { + [id: string]: Meteor.EventHandlerFunction; + } + /** Event **/ + + /** Connection **/ + function reconnect(): void; + + function disconnect(): void; + /** Connection **/ + + /** Status **/ + function status(): DDP.DDPStatus; + /** Status **/ + + /** Pub/Sub **/ + function subscribe(name: string, ...args: any[]): Meteor.SubscriptionHandle; + /** Pub/Sub **/ + } } -declare namespace Cordova { - function depends(dependencies:{[id:string]:string}): void; +declare module Meteor { + /** Connection **/ + interface Connection { + id: string; + close: Function; + onClose: Function; + clientAddress: string; + httpHeaders: Object; + } + + function onConnection(callback: Function): void; + /** Connection **/ + + function publish(name: string, func: Function): void; + + function _debug(...args: any[]): void; } -declare namespace DDP { - function connect(url: string): DDP.DDPStatic; +interface Subscription { + added(collection: string, id: string, fields: Object): void; + changed(collection: string, id: string, fields: Object): void; + connection: Meteor.Connection; + error(error: Error): void; + onStop(func: Function): void; + ready(): void; + removed(collection: string, id: string): void; + stop(): void; + userId: string; } -declare namespace DDPCommon { - function MethodInvocation(options: { - }): any; +declare module "meteor/meteor" { + module Meteor { + /** Connection **/ + interface Connection { + id: string; + close: Function; + onClose: Function; + clientAddress: string; + httpHeaders: Object; + } + + function onConnection(callback: Function): void; + /** Connection **/ + + function publish(name: string, func: Function): void; + + function _debug(...args: any[]): void; + } + + interface Subscription { + added(collection: string, id: string, fields: Object): void; + changed(collection: string, id: string, fields: Object): void; + connection: Meteor.Connection; + error(error: Error): void; + onStop(func: Function): void; + ready(): void; + removed(collection: string, id: string): void; + stop(): void; + userId: string; + } } -declare namespace EJSON { - var CustomType: CustomTypeStatic; - interface CustomTypeStatic { - new(): CustomType; - } - interface CustomType { - clone(): EJSON.CustomType; - equals(other: Object): boolean; - toJSONValue(): JSONable; - typeName(): string; - } +declare module Mongo { + interface Selector { + [key: string]: any; + } + interface Selector extends Object { } + interface Modifier { } + interface SortSpecifier { } + interface FieldSpecifier { + [id: string]: Number; + } - function addType(name: string, factory: (val: JSONable) => EJSON.CustomType): void; - function clone(val:T): T; - function equals(a: EJSON, b: EJSON, options?: { - keyOrderSensitive?: boolean; - }): boolean; - function fromJSONValue(val: JSONable): any; - function isBinary(x: Object): boolean; - var newBinary: any; - function parse(str: string): EJSON; - function stringify(val: EJSON, options?: { - indent?: boolean | number | string; - canonical?: boolean; - }): string; - function toJSONValue(val: EJSON): JSONable; + var Collection: CollectionStatic; + interface CollectionStatic { + new (name: string, options?: { + connection?: Object; + idGeneration?: string; + transform?: Function; + }): Collection; + } + interface Collection { + allow(options: { + insert?: (userId: string, doc: T) => boolean; + update?: (userId: string, doc: T, fieldNames: string[], modifier: any) => boolean; + remove?: (userId: string, doc: T) => boolean; + fetch?: string[]; + transform?: Function; + }): boolean; + deny(options: { + insert?: (userId: string, doc: T) => boolean; + update?: (userId: string, doc: T, fieldNames: string[], modifier: any) => boolean; + remove?: (userId: string, doc: T) => boolean; + fetch?: string[]; + transform?: Function; + }): boolean; + find(selector?: Selector | ObjectID | string, options?: { + sort?: SortSpecifier; + skip?: number; + limit?: number; + fields?: FieldSpecifier; + reactive?: boolean; + transform?: Function; + }): Cursor; + findOne(selector?: Selector | ObjectID | string, options?: { + sort?: SortSpecifier; + skip?: number; + fields?: FieldSpecifier; + reactive?: boolean; + transform?: Function; + }): T; + insert(doc: T, callback?: Function): string; + rawCollection(): any; + rawDatabase(): any; + remove(selector: Selector | ObjectID | string, callback?: Function): number; + update(selector: Selector | ObjectID | string, modifier: Modifier, options?: { + multi?: boolean; + upsert?: boolean; + }, callback?: Function): number; + upsert(selector: Selector | ObjectID | string, modifier: Modifier, options?: { + multi?: boolean; + }, callback?: Function): { + numberAffected?: number; insertedId?: string; + }; + _ensureIndex(keys: { + [key: string]: number | string + } | string, options?: { + [key: string]: any + }): void; + _dropIndex(keys: { + [key: string]: number | string + } | string): void; + } + + var Cursor: CursorStatic; + interface CursorStatic { + new (): Cursor; + } + interface ObserveCallbacks { + added?(document: Object): void; + addedAt?(document: Object, atIndex: number, before: Object): void; + changed?(newDocument: Object, oldDocument: Object): void; + changedAt?(newDocument: Object, oldDocument: Object, indexAt: number): void; + removed?(oldDocument: Object): void; + removedAt?(oldDocument: Object, atIndex: number): void; + movedTo?(document: Object, fromIndex: number, toIndex: number, before: Object): void; + } + interface ObserveChangesCallbacks { + added?(id: string, fields: Object): void; + addedBefore?(id: string, fields: Object, before: Object): void; + changed?(id: string, fields: Object): void; + movedBefore?(id: string, before: Object): void; + removed?(id: string): void; + } + interface Cursor { + count(applySkipLimit?: boolean): number; + fetch(): Array; + forEach(callback: < T > (doc: T, index: number, cursor: Cursor) => void, thisArg?: any): void; + map(callback: (doc: T, index: number, cursor: Cursor) => U, thisArg?: any): Array; + observe(callbacks: ObserveCallbacks): Meteor.LiveQueryHandle; + observeChanges(callbacks: ObserveChangesCallbacks): Meteor.LiveQueryHandle; + } + + var ObjectID: ObjectIDStatic; + interface ObjectIDStatic { + new (hexString?: string): ObjectID; + } + interface ObjectID { } } -declare namespace Match { - function test(value: any, pattern: any): boolean; +declare module "meteor/mongo" { + module Mongo { + interface Selector { + [key: string]: any; + } + interface Selector extends Object { } + interface Modifier { } + interface SortSpecifier { } + interface FieldSpecifier { + [id: string]: Number; + } + + var Collection: CollectionStatic; + interface CollectionStatic { + new (name: string, options?: { + connection?: Object; + idGeneration?: string; + transform?: Function; + }): Collection; + } + interface Collection { + allow(options: { + insert?: (userId: string, doc: T) => boolean; + update?: (userId: string, doc: T, fieldNames: string[], modifier: any) => boolean; + remove?: (userId: string, doc: T) => boolean; + fetch?: string[]; + transform?: Function; + }): boolean; + deny(options: { + insert?: (userId: string, doc: T) => boolean; + update?: (userId: string, doc: T, fieldNames: string[], modifier: any) => boolean; + remove?: (userId: string, doc: T) => boolean; + fetch?: string[]; + transform?: Function; + }): boolean; + find(selector?: Selector | ObjectID | string, options?: { + sort?: SortSpecifier; + skip?: number; + limit?: number; + fields?: FieldSpecifier; + reactive?: boolean; + transform?: Function; + }): Cursor; + findOne(selector?: Selector | ObjectID | string, options?: { + sort?: SortSpecifier; + skip?: number; + fields?: FieldSpecifier; + reactive?: boolean; + transform?: Function; + }): T; + insert(doc: T, callback?: Function): string; + rawCollection(): any; + rawDatabase(): any; + remove(selector: Selector | ObjectID | string, callback?: Function): number; + update(selector: Selector | ObjectID | string, modifier: Modifier, options?: { + multi?: boolean; + upsert?: boolean; + }, callback?: Function): number; + upsert(selector: Selector | ObjectID | string, modifier: Modifier, options?: { + multi?: boolean; + }, callback?: Function): { + numberAffected?: number; insertedId?: string; + }; + _ensureIndex(keys: { + [key: string]: number | string + } | string, options?: { + [key: string]: any + }): void; + _dropIndex(keys: { + [key: string]: number | string + } | string): void; + } + + var Cursor: CursorStatic; + interface CursorStatic { + new (): Cursor; + } + interface ObserveCallbacks { + added?(document: Object): void; + addedAt?(document: Object, atIndex: number, before: Object): void; + changed?(newDocument: Object, oldDocument: Object): void; + changedAt?(newDocument: Object, oldDocument: Object, indexAt: number): void; + removed?(oldDocument: Object): void; + removedAt?(oldDocument: Object, atIndex: number): void; + movedTo?(document: Object, fromIndex: number, toIndex: number, before: Object): void; + } + interface ObserveChangesCallbacks { + added?(id: string, fields: Object): void; + addedBefore?(id: string, fields: Object, before: Object): void; + changed?(id: string, fields: Object): void; + movedBefore?(id: string, before: Object): void; + removed?(id: string): void; + } + interface Cursor { + count(applySkipLimit?: boolean): number; + fetch(): Array; + forEach(callback: < T > (doc: T, index: number, cursor: Cursor) => void, thisArg?: any): void; + map(callback: (doc: T, index: number, cursor: Cursor) => U, thisArg?: any): Array; + observe(callbacks: ObserveCallbacks): Meteor.LiveQueryHandle; + observeChanges(callbacks: ObserveChangesCallbacks): Meteor.LiveQueryHandle; + } + + var ObjectID: ObjectIDStatic; + interface ObjectIDStatic { + new (hexString?: string): ObjectID; + } + interface ObjectID { } + } } -declare namespace Meteor { - var Error: ErrorStatic; - interface ErrorStatic { - new(error: string | number, reason?: string, details?: string): Error; - } - interface Error { - error: string | number; - reason?: string; - details?: string; - } - function absoluteUrl(path?: string, options?: { - secure?: boolean; - replaceLocalhost?: boolean; - rootUrl?: string; - }): string; - function apply(name: string, args: EJSONable[], options?: { - wait?: boolean; - onResultReceived?: Function; - }, asyncCallback?: Function): any; - function call(name: string, ...args: any[]): any; - function clearInterval(id: number): void; - function clearTimeout(id: number): void; - function disconnect(): void; - var isClient: boolean; - var isCordova: boolean; - var isDevelopment: boolean; - var isProduction: boolean; - var isServer: boolean; - var isTest: boolean; - function loggingIn(): boolean; - function loginWith(options?: { - requestPermissions?: string[]; - requestOfflineToken?: boolean; - loginUrlParameters?: Object; - loginHint?: string; - loginStyle?: string; - redirectUrl?: string; - }, callback?: Function): void; - function loginWithPassword(user: Object | string, password: string, callback?: Function): void; - function logout(callback?: Function): void; - function logoutOtherClients(callback?: Function): void; - function methods(methods: Object): void; - function onConnection(callback: Function): void; - function publish(name: string, func: Function): void; - function reconnect(): void; - var release: string; - function setInterval(func: Function, delay: number): number; - function setTimeout(func: Function, delay: number): number; - var settings: { public: {[id:string]: any}, private: {[id:string]: any}, [id:string]: any}; - function startup(func: Function): void; - function status(): Meteor.StatusEnum; - function subscribe(name: string, ...args: any[]): Meteor.SubscriptionHandle; - function user(): Meteor.User; - function userId(): string; - var users: Mongo.Collection; - function wrapAsync(func: Function, context?: Object): any; +declare module Mongo { + interface AllowDenyOptions { + insert?: (userId: string, doc: any) => boolean; + update?: (userId: string, doc: any, fieldNames: string[], modifier: any) => boolean; + remove?: (userId: string, doc: any) => boolean; + fetch?: string[]; + transform?: Function; + } } -declare namespace Mongo { - var Collection: CollectionStatic; - interface CollectionStatic { - new(name: string, options?: { - connection?: Object; - idGeneration?: string; - transform?: Function; - }): Collection; - } - interface Collection { - allow(options: { - insert?: (userId: string, doc: T) => boolean; - update?: (userId: string, doc: T, fieldNames: string[], modifier: any) => boolean; - remove?: (userId: string, doc: T) => boolean; - fetch?: string[]; - transform?: Function; - }): boolean; - deny(options: { - insert?: (userId: string, doc: T) => boolean; - update?: (userId: string, doc: T, fieldNames: string[], modifier: any) => boolean; - remove?: (userId: string, doc: T) => boolean; - fetch?: string[]; - transform?: Function; - }): boolean; - find(selector?: Mongo.Selector | Mongo.ObjectID | string, options?: { - sort?: Mongo.SortSpecifier; - skip?: number; - limit?: number; - fields?: Mongo.FieldSpecifier; - reactive?: boolean; - transform?: Function; - disableOplog?: boolean; - pollingIntervalMs?: number; - pollingThrottleMs?: number; - }): Mongo.Cursor; - findOne(selector?: Mongo.Selector | Mongo.ObjectID | string, options?: { - sort?: Mongo.SortSpecifier; - skip?: number; - fields?: Mongo.FieldSpecifier; - reactive?: boolean; - transform?: Function; - }): T; - insert(doc: T, callback?: Function): string; - rawCollection(): any; - rawDatabase(): any; - remove(selector: Mongo.Selector | Mongo.ObjectID | string, callback?: Function): number; - update(selector: Mongo.Selector | Mongo.ObjectID | string, modifier: Mongo.Modifier, options?: { - multi?: boolean; - upsert?: boolean; - }, callback?: Function): number; - upsert(selector: Mongo.Selector | Mongo.ObjectID | string, modifier: Mongo.Modifier, options?: { - multi?: boolean; - }, callback?: Function): {numberAffected?: number; insertedId?: string;}; - _ensureIndex(indexName: string, options?: {[key: string]: any}): void; - } - - var Cursor: CursorStatic; - interface CursorStatic { - new(): Cursor; - } - interface Cursor { - count(): number; - fetch(): Array; - forEach(callback: (doc: T, index: number, cursor: Mongo.Cursor) => void, thisArg?: any): void; - map(callback: (doc: T, index: number, cursor: Mongo.Cursor) => U, thisArg?: any): Array; - observe(callbacks: Object): Meteor.LiveQueryHandle; - observeChanges(callbacks: Object): Meteor.LiveQueryHandle; - } - - var ObjectID: ObjectIDStatic; - interface ObjectIDStatic { - new(hexString?: string): ObjectID; - } - interface ObjectID { - valueOf(): string; - getTimestamp(): Date; - } - +declare module "meteor/mongo" { + module Mongo { + interface AllowDenyOptions { + insert?: (userId: string, doc: any) => boolean; + update?: (userId: string, doc: any, fieldNames: string[], modifier: any) => boolean; + remove?: (userId: string, doc: any) => boolean; + fetch?: string[]; + transform?: Function; + } + } } -declare namespace Npm { - function depends(dependencies:{[id:string]:string}): void; - function require(name: string): any; +declare module Random { + function id(numberOfChars?: number): string; + + function secret(numberOfChars?: number): string; + + function fraction(): number; + // @param numberOfDigits, @returns a random hex string of the given length + function hexString(numberOfDigits: number): string; + // @param array, @return a random element in array + function choice(array: any[]): string; + // @param str, @return a random char in str + function choice(str: string): string; } -declare namespace Package { - function describe(options: { - summary?: string; - version?: string; - name?: string; - git?: string; - documentation?: string; - debugOnly?: boolean; - prodOnly?: boolean; - testOnly?: boolean; - }): void; - function onTest(func: Function): void; - function onUse(func: Function): void; - function registerBuildPlugin(options?: { - name?: string; - use?: string | string[]; - sources?: string[]; - npmDependencies?: Object; - }): void; -} +declare module "meteor/random" { + module Random { + function id(numberOfChars?: number): string; -declare namespace Tracker { - function Computation(): void; - interface Computation { - firstRun: boolean; - invalidate(): void; - invalidated: boolean; - onInvalidate(callback: Function): void; - onStop(callback: Function): void; - stop(): void; - stopped: boolean; - } + function secret(numberOfChars?: number): string; - var Dependency: DependencyStatic; - interface DependencyStatic { - new(): Dependency; - } - interface Dependency { - changed(): void; - depend(fromComputation?: Tracker.Computation): boolean; - hasDependents(): boolean; - } - - var active: boolean; - function afterFlush(callback: Function): void; - function autorun(runFunc: (computation: Tracker.Computation) => void, options?: { - onError?: Function; - }): Tracker.Computation; - var currentComputation: Tracker.Computation; - function flush(): void; - function nonreactive(func: Function): void; - function onInvalidate(callback: Function): void; -} - -declare namespace Session { - function equals(key: string, value: string | number | boolean | any /** Null **/ | any /** Undefined **/): boolean; - function get(key: string): any; - function set(key: string, value: EJSONable | any /** Undefined **/): void; - function setDefault(key: string, value: EJSONable | any /** Undefined **/): void; -} - -declare namespace HTTP { - function call(method: string, url: string, options?: { - content?: string; - data?: Object; - query?: string; - params?: Object; - auth?: string; - headers?: Object; - timeout?: number; - followRedirects?: boolean; - npmRequestOptions?: Object; - beforeSend?: Function; - }, asyncCallback?: Function): HTTP.HTTPResponse; - function del(url: string, callOptions?: Object, asyncCallback?: Function): HTTP.HTTPResponse; - function get(url: string, callOptions?: Object, asyncCallback?: Function): HTTP.HTTPResponse; - function patch(url: string, callOptions?: Object, asyncCallback?: Function): HTTP.HTTPResponse; - function post(url: string, callOptions?: Object, asyncCallback?: Function): HTTP.HTTPResponse; - function put(url: string, callOptions?: Object, asyncCallback?: Function): HTTP.HTTPResponse; -} - -declare namespace Email { - function send(options: { - from?: string; - to?: string | string[]; - cc?: string | string[]; - bcc?: string | string[]; - replyTo?: string | string[]; - subject?: string; - text?: string; - html?: string; - headers?: Object; - attachments?: Object[]; - mailComposer?: MailComposer; - }): void; -} - -declare var CompileStep: CompileStepStatic; -interface CompileStepStatic { - new(): CompileStep; -} -interface CompileStep { - addAsset(options: { - }, path: string, data: any /** Buffer **/ | string): any; - addHtml(options: { - section?: string; - data?: string; - }): any; - addJavaScript(options: { - path?: string; - data?: string; - sourcePath?: string; - }): any; - addStylesheet(options: { - }, path: string, data: string, sourceMap: string): any; - arch: any; - declaredExports: any; - error(options: { - }, message: string, sourcePath?: string, line?: number, func?: string): any; - fileOptions: any; - fullInputPath: any; - inputPath: any; - inputSize: any; - packageName: any; - pathForSourceMap: any; - read(n?: number): any; - rootOutputPath: any; -} - -declare var PackageAPI: PackageAPIStatic; -interface PackageAPIStatic { - new(): PackageAPI; -} -interface PackageAPI { - addAssets(filenames: string | string[], architecture: string | string[]): void; - addFiles(filenames: string | string[], architecture?: string | string[], options?: { - bare?: boolean; - }): void; - export(exportedObjects: string | string[], architecture?: string | string[], exportOptions?: Object, testOnly?: boolean): void; - imply(packageNames: string | string[], architecture?: string | string[]): void; - use(packageNames: string | string[], architecture?: string | string[], options?: { - weak?: boolean; - unordered?: boolean; - }): void; - versionsFrom(meteorRelease: string | string[]): void; + function fraction(): number; + // @param numberOfDigits, @returns a random hex string of the given length + function hexString(numberOfDigits: number): string; + // @param array, @return a random element in array + function choice(array: any[]): string; + // @param str, @return a random char in str + function choice(str: string): string; + } } declare var ReactiveVar: ReactiveVarStatic; interface ReactiveVarStatic { - new(initialValue: T, equalsFunc?: Function): ReactiveVar; + new (initialValue: T, equalsFunc?: Function): ReactiveVar; } interface ReactiveVar { - get(): T; - set(newValue: T): void; + get(): T; + set(newValue: T): void; } -declare var Subscription: SubscriptionStatic; -interface SubscriptionStatic { - new(): Subscription; +declare module "meteor/reactive-var" { + var ReactiveVar: ReactiveVarStatic; + interface ReactiveVarStatic { + new (initialValue: T, equalsFunc?: Function): ReactiveVar; + } + interface ReactiveVar { + get(): T; + set(newValue: T): void; + } } -interface Subscription { - added(collection: string, id: string, fields: Object): void; - changed(collection: string, id: string, fields: Object): void; - connection: Meteor.Connection; - error(error: Error): void; - onStop(func: Function): void; - ready(): void; - removed(collection: string, id: string): void; - stop(): void; - userId: string; + +declare module Session { + function equals(key: string, value: string | number | boolean | any): boolean; + + function get(key: string): any; + + function set(key: string, value: EJSONable | any): void; + + function setDefault(key: string, value: EJSONable | any): void; +} + +declare module "meteor/session" { + module Session { + function equals(key: string, value: string | number | boolean | any): boolean; + + function get(key: string): any; + + function set(key: string, value: EJSONable | any): void; + + function setDefault(key: string, value: EJSONable | any): void; + } } declare var Template: TemplateStatic; -interface TemplateStatic { - new(): Template; - // It should be [templateName: string]: TemplateInstance but this is not possible -- user will need to cast to TemplateInstance - [templateName: string]: any | Template; // added "any" to make it work - head: Template; - find(selector:string):Blaze.Template; - findAll(selector:string):Blaze.Template[]; - $:any; - body: Template; - currentData(): {}; - deregisterHelper(name: string): void; - instance(): Blaze.TemplateInstance; - parentData(numLevels?: number): {}; - registerHelper(name: string, helperFunction: Function): void; +interface TemplateStatic extends Blaze.TemplateStatic { + new (viewName?: string, renderFunction?: Function): Blaze.Template; + body: Blaze.Template; + [index: string]: any | Blaze.Template; } -interface Template { - created: Function; - destroyed: Function; - events(eventMap: Meteor.EventMap): void; - helpers(helpers:{[id:string]: any}): void; - onCreated: Function; - onDestroyed: Function; - onRendered: Function; - rendered: Function; + +declare module "meteor/templating" { + var Template: TemplateStatic; + interface TemplateStatic extends Blaze.TemplateStatic { + new (viewName?: string, renderFunction?: Function): Blaze.Template; + body: Blaze.Template; + [index: string]: any | Blaze.Template; + } +} + +interface ILengthAble { + length: number; +} + +interface ITinytestAssertions { + ok(doc: Object): void; + expect_fail(): void; + fail(doc: Object): void; + runId(): string; + equal(actual: T, expected: T, message?: string, not?: boolean): void; + notEqual(actual: T, expected: T, message?: string): void; + instanceOf(obj: Object, klass: Function, message?: string): void; + notInstanceOf(obj: Object, klass: Function, message?: string): void; + matches(actual: any, regexp: RegExp, message?: string): void; + notMatches(actual: any, regexp: RegExp, message?: string): void; + throws(f: Function, expected?: string | RegExp): void; + isTrue(v: boolean, msg?: string): void; + isFalse(v: boolean, msg?: string): void; + isNull(v: any, msg?: string): void; + isNotNull(v: any, msg?: string): void; + isUndefined(v: any, msg?: string): void; + isNotUndefined(v: any, msg?: string): void; + isNan(v: any, msg?: string): void; + isNotNan(v: any, msg?: string): void; + include(s: Array | Object | string, value: any, msg?: string, not?: boolean): void; + + notInclude(s: Array | Object | string, value: any, msg?: string, not?: boolean): void; + length(obj: ILengthAble, expected_length: number, msg?: string): void; + _stringEqual(actual: string, expected: string, msg?: string): void; +} + +declare module Tinytest { + function add(description: string, func: (test: ITinytestAssertions) => void): void; + + function addAsync(description: string, func: (test: ITinytestAssertions) => void): void; +} + +declare module "meteor/tiny-test" { + interface ILengthAble { + length: number; + } + + interface ITinytestAssertions { + ok(doc: Object): void; + expect_fail(): void; + fail(doc: Object): void; + runId(): string; + equal(actual: T, expected: T, message?: string, not?: boolean): void; + notEqual(actual: T, expected: T, message?: string): void; + instanceOf(obj: Object, klass: Function, message?: string): void; + notInstanceOf(obj: Object, klass: Function, message?: string): void; + matches(actual: any, regexp: RegExp, message?: string): void; + notMatches(actual: any, regexp: RegExp, message?: string): void; + throws(f: Function, expected?: string | RegExp): void; + isTrue(v: boolean, msg?: string): void; + isFalse(v: boolean, msg?: string): void; + isNull(v: any, msg?: string): void; + isNotNull(v: any, msg?: string): void; + isUndefined(v: any, msg?: string): void; + isNotUndefined(v: any, msg?: string): void; + isNan(v: any, msg?: string): void; + isNotNan(v: any, msg?: string): void; + include(s: Array | Object | string, value: any, msg?: string, not?: boolean): void; + + notInclude(s: Array | Object | string, value: any, msg?: string, not?: boolean): void; + length(obj: ILengthAble, expected_length: number, msg?: string): void; + _stringEqual(actual: string, expected: string, msg?: string): void; + } + + module Tinytest { + function add(description: string, func: (test: ITinytestAssertions) => void): void; + + function addAsync(description: string, func: (test: ITinytestAssertions) => void): void; + } +} + +declare module App { + function accessRule(pattern: string, options?: { + type?: string; + launchExternal?: boolean; + }): void; + + function configurePlugin(id: string, config: Object): void; + + function icons(icons: Object): void; + + function info(options: { + id?: string; + version?: string; + name?: string; + description?: string; + author?: string; + email?: string; + website?: string; + }): void; + + function launchScreens(launchScreens: Object): void; + + function setPreference(name: string, value: string, platform?: string): void; } -declare function check(value: any, pattern: any): void; declare function execFileAsync(command: string, args?: any[], options?: { - cwd?: Object; - env?: Object; - stdio?: any[] | string; - destination?: any; - waitForClose?: string; + cwd?: Object; + env?: Object; + stdio?: any[] | string; + destination?: any; + waitForClose?: string; }): any; declare function execFileSync(command: string, args?: any[], options?: { - cwd?: Object; - env?: Object; - stdio?: any[] | string; - destination?: any; - waitForClose?: string; + cwd?: Object; + env?: Object; + stdio?: any[] | string; + destination?: any; + waitForClose?: string; }): String; -declare function getExtension(): String; + +declare module Assets { + function getBinary(assetPath: string, asyncCallback?: Function): EJSON; + + function getText(assetPath: string, asyncCallback?: Function): string; + + function absoluteFilePath(assetPath: string): string; +} + +declare module Cordova { + function depends(dependencies: { + [id: string]: string + }): void; +} + +declare module Npm { + function depends(dependencies: { + [id: string]: string + }): void; + + function require(name: string): any; +} + +declare namespace Package { + function describe(options: { + summary?: string; + version?: string; + name?: string; + git?: string; + documentation?: string; + debugOnly?: boolean; + prodOnly?: boolean; + testOnly?: boolean; + }): void; + + function onTest(func: (api: PackageAPI) => void): void; + + function onUse(func: (api: PackageAPI) => void): void; + + function registerBuildPlugin(options?: { + name?: string; + use?: string | string[]; + sources?: string[]; + npmDependencies?: Object; + }): void; +} + +interface PackageAPI { + new (): PackageAPI; + addAssets(filenames: string | string[], architecture: string | string[]): void; + addFiles(filenames: string | string[], architecture?: string | string[], options?: { + bare?: boolean; + }): void; + export(exportedObjects: string | string[], architecture?: string | string[], exportOptions?: Object, testOnly?: boolean): void; + imply(packageNames: string | string[], architecture?: string | string[]): void; + use(packageNames: string | string[], architecture?: string | string[], options?: { + weak?: boolean; + unordered?: boolean; + }): void; + versionsFrom(meteorRelease: string | string[]): void; +} + +declare var console: Console; + +declare module "meteor/tools" { + module App { + function accessRule(pattern: string, options?: { + type?: string; + launchExternal?: boolean; + }): void; + + function configurePlugin(id: string, config: Object): void; + + function icons(icons: Object): void; + + function info(options: { + id?: string; + version?: string; + name?: string; + description?: string; + author?: string; + email?: string; + website?: string; + }): void; + + function launchScreens(launchScreens: Object): void; + + function setPreference(name: string, value: string, platform?: string): void; + } + + function execFileAsync(command: string, args?: any[], options?: { + cwd?: Object; + env?: Object; + stdio?: any[] | string; + destination?: any; + waitForClose?: string; + }): any; + + function execFileSync(command: string, args?: any[], options?: { + cwd?: Object; + env?: Object; + stdio?: any[] | string; + destination?: any; + waitForClose?: string; + }): String; + + module Assets { + function getBinary(assetPath: string, asyncCallback?: Function): EJSON; + + function getText(assetPath: string, asyncCallback?: Function): string; + + function absoluteFilePath(assetPath: string): string; + } + + module Cordova { + function depends(dependencies: { + [id: string]: string + }): void; + } + + module Npm { + function depends(dependencies: { + [id: string]: string + }): void; + + function require(name: string): any; + } + + namespace Package { + function describe(options: { + summary?: string; + version?: string; + name?: string; + git?: string; + documentation?: string; + debugOnly?: boolean; + prodOnly?: boolean; + testOnly?: boolean; + }): void; + + function onTest(func: (api: PackageAPI) => void): void; + + function onUse(func: (api: PackageAPI) => void): void; + + function registerBuildPlugin(options?: { + name?: string; + use?: string | string[]; + sources?: string[]; + npmDependencies?: Object; + }): void; + } + + interface PackageAPI { + new (): PackageAPI; + addAssets(filenames: string | string[], architecture: string | string[]): void; + addFiles(filenames: string | string[], architecture?: string | string[], options?: { + bare?: boolean; + }): void; + export(exportedObjects: string | string[], architecture?: string | string[], exportOptions?: Object, testOnly?: boolean): void; + imply(packageNames: string | string[], architecture?: string | string[]): void; + use(packageNames: string | string[], architecture?: string | string[], options?: { + weak?: boolean; + unordered?: boolean; + }): void; + versionsFrom(meteorRelease: string | string[]): void; + } + + var console: Console; +} + +declare module Tracker { + function Computation(): void; + interface Computation { + firstRun: boolean; + invalidate(): void; + invalidated: boolean; + onInvalidate(callback: Function): void; + onStop(callback: Function): void; + stop(): void; + stopped: boolean; + } + var currentComputation: Computation; + + var Dependency: DependencyStatic; + interface DependencyStatic { + new (): Dependency; + } + interface Dependency { + changed(): void; + depend(fromComputation?: Computation): boolean; + hasDependents(): boolean; + } + + var active: boolean; + + function afterFlush(callback: Function): void; + + function autorun(runFunc: (computation: Computation) => void, options?: { + onError?: Function; + }): Computation; + + function flush(): void; + + function nonreactive(func: Function): void; + + function onInvalidate(callback: Function): void; +} + +declare module "meteor/tracker" { + module Tracker { + function Computation(): void; + interface Computation { + firstRun: boolean; + invalidate(): void; + invalidated: boolean; + onInvalidate(callback: Function): void; + onStop(callback: Function): void; + stop(): void; + stopped: boolean; + } + var currentComputation: Computation; + + var Dependency: DependencyStatic; + interface DependencyStatic { + new (): Dependency; + } + interface Dependency { + changed(): void; + depend(fromComputation?: Computation): boolean; + hasDependents(): boolean; + } + + var active: boolean; + + function afterFlush(callback: Function): void; + + function autorun(runFunc: (computation: Computation) => void, options?: { + onError?: Function; + }): Computation; + + function flush(): void; + + function nonreactive(func: Function): void; + + function onInvalidate(callback: Function): void; + } +} + +declare module Match { + function Maybe(pattern: any): boolean; +} + +declare module "meteor/check" { + module Match { + function Maybe(pattern: any): boolean; + } +} + +declare module Meteor { + /** Global props **/ + var isDevelopment: boolean; + var isTest: boolean; + /** Global props **/ +} + +declare module "meteor/meteor" { + module Meteor { + /** Global props **/ + var isDevelopment: boolean; + var isTest: boolean; + /** Global props **/ + } +} + +declare module Accounts { + function onLogout(func: Function): void; +} + +declare module "meteor/accounts-base" { + module Accounts { + function onLogout(func: Function): void; + } +} + +declare module Accounts { + function onLogout(func: (user: Meteor.User, connection: Meteor.Connection) => void): void; +} + +declare module "meteor/accounts-base" { + module Accounts { + function onLogout(func: (user: Meteor.User, connection: Meteor.Connection) => void): void; + } +} diff --git a/meteor/meteor-tests.ts b/meteor/meteor-tests.ts index b700e4d616..c269105eb3 100644 --- a/meteor/meteor-tests.ts +++ b/meteor/meteor-tests.ts @@ -6,11 +6,24 @@ /*********************************** Begin setup for tests ******************************/ +import { Mongo } from "meteor/mongo"; +import { Meteor } from "meteor/meteor"; +import { check, Match } from "meteor/check"; +import { Tracker } from "meteor/tracker"; +import { Template } from "meteor/templating"; +import { Blaze } from "meteor/blaze"; +import { Session } from "meteor/session"; +import { HTTP } from "meteor/http"; +import { ReactiveVar } from "meteor/reactive-var"; +import { Accounts } from "meteor/accounts-base"; +import { BrowserPolicy } from "meteor/browser-policy-common"; +import { DDPRateLimiter } from "meteor/ddp-rate-limiter"; + var Rooms = new Mongo.Collection('rooms'); var Messages = new Mongo.Collection('messages'); interface MonkeyDAO { - _id: string; - name: string; + _id: string; + name: string; } var Monkeys = new Mongo.Collection('monkeys'); //var x = new Mongo.Collection('x'); @@ -23,72 +36,73 @@ var Monkeys = new Mongo.Collection('monkeys'); * Tests Meteor.isServer, Meteor.startup, Collection.insert(), Collection.find() */ if (Meteor.isServer) { - Meteor.startup(function () { - if (Rooms.find().count() === 0) { - Rooms.insert({name: "Initial room"}); - } - }); + Meteor.startup(function () { + if (Rooms.find().count() === 0) { + Rooms.insert({ name: "Initial room" }); + } + }); } /** * From Publish and Subscribe, Meteor.publish section **/ Meteor.publish("rooms", function () { - return Rooms.find({}, {fields: {secretInfo: 0}}); + return Rooms.find({}, { fields: { secretInfo: 0 } }); }); Meteor.publish("adminSecretInfo", function () { - return Rooms.find({admin: this.userId}, {fields: {secretInfo: 1}}); + return Rooms.find({ admin: this.userId }, { fields: { secretInfo: 1 } }); }); Meteor.publish("roomAndMessages", function (roomId: string) { - check(roomId, String); - return [ - Rooms.find({_id: roomId}, {fields: {secretInfo: 0}}), - Messages.find({roomId: roomId}) - ]; + check(roomId, String); + return [ + Rooms.find({ _id: roomId }, { fields: { secretInfo: 0 } }), + Messages.find({ roomId: roomId }) + ]; }); /** * Also from Publish and Subscribe, Meteor.publish section */ Meteor.publish("counts-by-room", function (roomId: string) { - var self = this; - check(roomId, String); - var count = 0; - var initializing = true; - var handle = Messages.find({roomId: roomId}).observeChanges({ - added: function (id: any) { - count++; -// if (!initializing) + var self = this; + check(roomId, String); + var count = 0; + var initializing = true; + var handle = Messages.find({ roomId: roomId }).observeChanges({ + added: function (id: any) { + count++; + // if (!initializing) + // this.changed("counts", roomId, {count: count}); + }, + removed: function (id: any) { + count--; + // Todo: Not sure how to define in typescript + // self.changed("counts", roomId, {count: count}); + } + }); -// Todo: Not sure how to define in typescript -// self.changed("counts", roomId, {count: count}); - }, - removed: function (id: any) { - count--; -// Todo: Not sure how to define in typescript -// self.changed("counts", roomId, {count: count}); - } - }); + initializing = false; - initializing = false; + // Todo: Not sure how to define in typescript + // self.added("counts", roomId, {count: count}); + self.ready(); -// Todo: Not sure how to define in typescript -// self.added("counts", roomId, {count: count}); - self.ready(); - - self.onStop(function () { - handle.stop(); - }); + self.onStop(function () { + handle.stop(); + }); }); var Counts = new Mongo.Collection("counts"); Tracker.autorun(function () { - Meteor.subscribe("counts-by-room", Session.get("roomId")); + Meteor.subscribe("counts-by-room", Session.get("roomId")); }); +// Checking status +let status: DDP.Status = 'connected'; + console.log("Current room has " + Counts.find(Session.get("roomId")).count + " messages."); @@ -102,47 +116,47 @@ Meteor.subscribe("allplayers"); * Also from Meteor.subscribe section */ Tracker.autorun(function () { - Meteor.subscribe("chat", {room: Session.get("current-room")}); - Meteor.subscribe("privateMessages"); + Meteor.subscribe("chat", { room: Session.get("current-room") }); + Meteor.subscribe("privateMessages"); }); /** * From Methods, Meteor.methods section */ Meteor.methods({ - foo: function (arg1: string, arg2: number[]) { - check(arg1, String); - check(arg2, [Number]); + foo: function (arg1: string, arg2: number[]) { + check(arg1, String); + check(arg2, [Number]); - var you_want_to_throw_an_error = true; - if (you_want_to_throw_an_error) - throw new Meteor.Error("404", "Can't find my pants"); - return "some return value"; - }, + var you_want_to_throw_an_error = true; + if (you_want_to_throw_an_error) + throw new Meteor.Error("404", "Can't find my pants"); + return "some return value"; + }, - bar: function () { - // .. do other stuff .. - return "baz"; - } + bar: function () { + // .. do other stuff .. + return "baz"; + } }); /** * From Methods, Meteor.Error section */ function meteorErrorTestFunction1() { - throw new Meteor.Error("logged-out", - "The user must be logged in to post a comment."); + throw new Meteor.Error("logged-out", + "The user must be logged in to post a comment."); } function meteorErrorTestFunction2() { - throw new Meteor.Error(403, - "The user must be logged in to post a comment."); + throw new Meteor.Error(403, + "The user must be logged in to post a comment."); } Meteor.call("methodName", function (error: Meteor.Error) { - if (error.error === "logged-out") { - Session.set("errorMessage", "Please log in to post a comment."); - } + if (error.error === "logged-out") { + Session.set("errorMessage", "Please log in to post a comment."); + } }); var error = new Meteor.Error("logged-out", "The user must be logged in to post a comment."); console.log(error.error === "logged-out"); @@ -152,7 +166,7 @@ console.log(error.details !== ""); /** * From Methods, Meteor.call section */ -Meteor.call('foo', 1, 2, function (error:any, result:any) {} ); +Meteor.call('foo', 1, 2, function (error: any, result: any) { }); var result = Meteor.call('foo', 1, 2); /** @@ -161,22 +175,22 @@ var result = Meteor.call('foo', 1, 2); // DA: I added the "var" keyword in there interface ChatroomsDAO { - _id?: string; + _id?: string; } interface MessagesDAO { - _id?: string; + _id?: string; } var Chatrooms = new Mongo.Collection("chatrooms"); Messages = new Mongo.Collection("messages"); -var myMessages:any[] = Messages.find({userId: Session.get('myUserId')}).fetch(); +var myMessages: any[] = Messages.find({ userId: Session.get('myUserId') }).fetch(); -Messages.insert({text: "Hello, world!"}); +Messages.insert({ text: "Hello, world!" }); -Messages.update(myMessages[0]._id, {$set: {important: true}}); +Messages.update(myMessages[0]._id, { $set: { important: true } }); var Posts = new Mongo.Collection("posts"); -Posts.insert({title: "Hello world", body: "First post"}); +Posts.insert({ title: "Hello world", body: "First post" }); // Couldn't find assert() in the meteor docs //assert(Posts.find().count() === 1); @@ -192,30 +206,30 @@ Posts.insert({title: "Hello world", body: "First post"}); **/ class Animal { - private sound:string; - constructor(doc:any) { + private sound: string; + constructor(doc: any) { } makeNoise() { - console.log(this.sound) + console.log(this.sound) } } interface AnimalDAO { - _id?: string; - name: string; - sound: string; - makeNoise?: () => void; + _id?: string; + name: string; + sound: string; + makeNoise?: () => void; } // Define a Collection that uses Animal as its document var Animals = new Mongo.Collection("Animals", { - transform: function (doc:any): Animal { return new Animal(doc); } + transform: function (doc: any): Animal { return new Animal(doc); } }); // Create an Animal and call its makeNoise method -Animals.insert({name: "raptor", sound: "roar"}); -Animals.findOne({name: "raptor"}).makeNoise(); // prints "roar" +Animals.insert({ name: "raptor", sound: "roar" }); +Animals.findOne({ name: "raptor" }).makeNoise(); // prints "roar" /** * From Collections, Collection.insert section @@ -224,9 +238,9 @@ Animals.findOne({name: "raptor"}).makeNoise(); // prints "roar" var Lists = new Mongo.Collection('Lists'); var Items = new Mongo.Collection('Lists'); -var groceriesId = Lists.insert({name: "Groceries"}); -Items.insert({list: groceriesId, name: "Watercress"}); -Items.insert({list: groceriesId, name: "Persimmons"}); +var groceriesId = Lists.insert({ name: "Groceries" }); +Items.insert({ list: groceriesId, name: "Watercress" }); +Items.insert({ list: groceriesId, name: "Persimmons" }); /** * From Collections, collection.update section @@ -234,39 +248,39 @@ Items.insert({list: groceriesId, name: "Persimmons"}); var Players = new Mongo.Collection('Players'); Template['adminDashboard'].events({ - 'click .givePoints': function () { - Players.update(Session.get("currentPlayer"), {$inc: {score: 5}}); - } + 'click .givePoints': function () { + Players.update(Session.get("currentPlayer"), { $inc: { score: 5 } }); + } }); /** * Also from Collections, collection.update section */ Meteor.methods({ - declareWinners: function () { - Players.update({score: {$gt: 10}}, - {$addToSet: {badges: "Winner"}}, - {multi: true}); - } + declareWinners: function () { + Players.update({ score: { $gt: 10 } }, + { $addToSet: { badges: "Winner" } }, + { multi: true }); + } }); /** * From Collections, collection.remove section */ Template['chat'].events({ - 'click .remove': function () { - Messages.remove(this._id); - } + 'click .remove': function () { + Messages.remove(this._id); + } }); // DA: I added this next line var Logs = new Mongo.Collection('logs'); Meteor.startup(function () { - if (Meteor.isServer) { - Logs.remove({}); - Players.remove({karma: {$lt: -2}}); - } + if (Meteor.isServer) { + Logs.remove({}); + Players.remove({ karma: { $lt: -2 } }); + } }); /*** @@ -274,50 +288,50 @@ Meteor.startup(function () { */ interface iPost { - _id: string; - owner: string; - userId: string; - locked: boolean; + _id: string; + owner: string; + userId: string; + locked: boolean; } Posts = new Mongo.Collection("posts"); Posts.allow({ - insert: function (userId:string, doc: iPost) { - // the user must be logged in, and the document must be owned by the user - return (userId && doc.owner === userId); - }, - update: function (userId:string, doc: iPost, fields:string[], modifier:any) { - // can only change your own documents - return doc.owner === userId; - }, - remove: function (userId:string, doc: iPost) { - // can only remove your own documents - return doc.owner === userId; - }, - fetch: ['owner'] + insert: function (userId: string, doc: iPost) { + // the user must be logged in, and the document must be owned by the user + return (userId && doc.owner === userId); + }, + update: function (userId: string, doc: iPost, fields: string[], modifier: any) { + // can only change your own documents + return doc.owner === userId; + }, + remove: function (userId: string, doc: iPost) { + // can only remove your own documents + return doc.owner === userId; + }, + fetch: ['owner'] }); Posts.deny({ - update: function (userId:string, doc: iPost, fields:string[], modifier:any) { - // can't change owners - return doc.userId !== userId; - }, - remove: function (userId:string, doc: iPost) { - // can't remove locked documents - return doc.locked; - }, - fetch: ['locked'] // no need to fetch 'owner' + update: function (userId: string, doc: iPost, fields: string[], modifier: any) { + // can't change owners + return doc.userId !== userId; + }, + remove: function (userId: string, doc: iPost) { + // can't remove locked documents + return doc.locked; + }, + fetch: ['locked'] // no need to fetch 'owner' }); /** * From Collections, cursor.forEach section */ -var topPosts = Posts.find({}, {sort: {score: -1}, limit: 5}); +var topPosts = Posts.find({}, { sort: { score: -1 }, limit: 5 }); var count = 0; -topPosts.forEach(function (post:{title:string}) { - console.log("Title of post " + count + ": " + post.title); - count += 1; +topPosts.forEach(function (post: { title: string }) { + console.log("Title of post " + count + ": " + post.title); + count += 1; }); /** @@ -327,26 +341,28 @@ topPosts.forEach(function (post:{title:string}) { var Users = new Mongo.Collection('users'); var count1 = 0; -var query = Users.find({admin: true, onlineNow: true}); +var query = Users.find({ admin: true, onlineNow: true }); var handle = query.observeChanges({ - added: function (id:string, user:{name:string}) { - count1++; - console.log(user.name + " brings the total to " + count1 + " admins."); - }, - removed: function () { - count1--; - console.log("Lost one. We're now down to " + count1 + " admins."); - } + added: function (id: string, user: { name: string }) { + count1++; + console.log(user.name + " brings the total to " + count1 + " admins."); + }, + removed: function () { + count1--; + console.log("Lost one. We're now down to " + count1 + " admins."); + } }); +let cursor: Mongo.Cursor; + // After five seconds, stop keeping the count. -setTimeout(function () {handle.stop();}, 5000); +setTimeout(function () { handle.stop(); }, 5000); /** * From Sessions, Session.set section */ Tracker.autorun(function () { - Meteor.subscribe("chat-history", {room: Session.get("currentRoomId")}); + Meteor.subscribe("chat-history", { room: Session.get("currentRoomId") }); }); // Causes the function passed to Tracker.autorun to be re-run, so @@ -375,59 +391,59 @@ Session.equals("key", value); * From Accounts, Meteor.users section */ Meteor.publish("userData", function () { - return Meteor.users.find({_id: this.userId}, - {fields: {'other': 1, 'things': 1}}); + return Meteor.users.find({ _id: this.userId }, + { fields: { 'other': 1, 'things': 1 } }); }); -Meteor.users.deny({update: function () { return true; }}); +Meteor.users.deny({ update: function () { return true; } }); /** * From Accounts, Meteor.loginWithExternalService section */ Meteor.loginWithGithub({ - requestPermissions: ['user', 'public_repo'] + requestPermissions: ['user', 'public_repo'] }, function (err: Meteor.Error) { - if (err) - Session.set('errorMessage', err.reason || 'Unknown error'); + if (err) + Session.set('errorMessage', err.reason || 'Unknown error'); }); /** * From Accounts, Accounts.ui.config section */ Accounts.ui.config({ - requestPermissions: { - facebook: ['user_likes'], - github: ['user', 'repo'] - }, - requestOfflineToken: { - google: true - }, - passwordSignupFields: 'USERNAME_AND_OPTIONAL_EMAIL' + requestPermissions: { + facebook: ['user_likes'], + github: ['user', 'repo'] + }, + requestOfflineToken: { + google: true + }, + passwordSignupFields: 'USERNAME_AND_OPTIONAL_EMAIL' }); /** * From Accounts, Accounts.validateNewUser section */ -Accounts.validateNewUser(function (user:{username:string}) { - if (user.username && user.username.length >= 3) - return true; - throw new Meteor.Error("403", "Username must have at least 3 characters"); +Accounts.validateNewUser(function (user: { username: string }) { + if (user.username && user.username.length >= 3) + return true; + throw new Meteor.Error("403", "Username must have at least 3 characters"); }); // Validate username, without a specific error message. -Accounts.validateNewUser(function (user:{username:string}) { - return user.username !== "root"; +Accounts.validateNewUser(function (user: { username: string }) { + return user.username !== "root"; }); /** * From Accounts, Accounts.onCreateUser section */ -Accounts.onCreateUser(function(options:{profile:any}, user:{profile:any, dexterity:number}) { - var d6 = function () { return Math.floor(Math.random() * 6) + 1; }; - user.dexterity = d6() + d6() + d6(); - // We still want the default hook's 'profile' behavior. - if (options.profile) - user.profile = options.profile; - return user; +Accounts.onCreateUser(function (options: { profile: any }, user: { profile: any, dexterity: number }) { + var d6 = function () { return Math.floor(Math.random() * 6) + 1; }; + user.dexterity = d6() + d6() + d6(); + // We still want the default hook's 'profile' behavior. + if (options.profile) + user.profile = options.profile; + return user; }); /** @@ -435,26 +451,27 @@ Accounts.onCreateUser(function(options:{profile:any}, user:{profile:any, dexteri */ Accounts.emailTemplates.siteName = "AwesomeSite"; Accounts.emailTemplates.from = "AwesomeSite Admin "; -Accounts.emailTemplates.enrollAccount.subject = function (user:{ profile:{name: string} }) { - return "Welcome to Awesome Town, " + user.profile.name; +Accounts.emailTemplates.enrollAccount.subject = function (user: { profile: { name: string } }) { + return "Welcome to Awesome Town, " + user.profile.name; }; -Accounts.emailTemplates.enrollAccount.text = function (user:any, url:string) { - return "You have been selected to participate in building a better future!" - + " To activate your account, simply click the link below:\n\n" - + url; +Accounts.emailTemplates.enrollAccount.text = function (user: any, url: string) { + return "You have been selected to participate in building a better future!" + + " To activate your account, simply click the link below:\n\n" + + url; }; /** * From Templates, Template.myTemplate.helpers section */ Template['adminDashboard'].helpers({ - foo: function () { - return Session.get("foo"); - } + foo: function () { + return Session.get("foo"); + } }); + Template['newTemplate'].helpers({ - helperName: function () { - } + helperName: function () { + } }); Template['newTemplate'].created = function () { @@ -470,12 +487,12 @@ Template['newTemplate'].destroyed = function () { }; Template['newTemplate'].events({ - 'click .something': function (event: Meteor.Event, template: Blaze.TemplateInstance) { - } + 'click .something': function (event: Meteor.Event, template: Blaze.TemplateInstance) { + } }); -Template.registerHelper('testHelper', function() { - return 'tester'; +Template.registerHelper('testHelper', function () { + return 'tester'; }); var instance = Template.instance(); @@ -488,23 +505,25 @@ var body = Template.body; */ var Chats = new Mongo.Collection('chats'); -Meteor.publish("chats-in-room", function (roomId:string) { - // Make sure roomId is a string, not an arbitrary mongo selector object. - check(roomId, String); - return Chats.find({room: roomId}); +Meteor.publish("chats-in-room", function (roomId: string) { + // Make sure roomId is a string, not an arbitrary mongo selector object. + check(roomId, String); + return Chats.find({ room: roomId }); }); -Meteor.methods({addChat: function (roomId:string, message:{text:string, timestamp:Date, tags:string}) { - check(roomId, String); - check(message, { - text: String, - timestamp: Date, - // Optional, but if present must be an array of strings. - tags: Match.Optional('Test String') - }); +Meteor.methods({ + addChat: function (roomId: string, message: { text: string, timestamp: Date, tags: string }) { + check(roomId, String); + check(message, { + text: String, + timestamp: Date, + // Optional, but if present must be an array of strings. + tags: Match.Optional('Test String') + }); - // ... do something with the message ... -}}); + // ... do something with the message ... + } +}); /** * From Match patterns section @@ -521,27 +540,27 @@ check(undefined, Match.Optional('test')); // OK * From Deps, Tracker.autorun section */ Tracker.autorun(function () { - var oldest = Monkeys.findOne('age = 20'); + var oldest = Monkeys.findOne('age = 20'); - if (oldest) - Session.set("oldest", oldest.name); + if (oldest) + Session.set("oldest", oldest.name); }); Tracker.autorun(function (c) { - if (! Session.equals("shouldAlert", true)) - return; + if (!Session.equals("shouldAlert", true)) + return; - c.stop(); - alert("Oh no!"); + c.stop(); + alert("Oh no!"); }); /** * From Deps, Deps.Computation */ if (Tracker.active) { - Tracker.onInvalidate(function () { - console.log('invalidated'); - }); + Tracker.onInvalidate(function () { + console.log('invalidated'); + }); } /** @@ -551,50 +570,52 @@ var weather = "sunny"; var weatherDep = new Tracker.Dependency; var getWeather = function () { - weatherDep.depend(); - return weather; + weatherDep.depend(); + return weather; }; -var setWeather = function (w:string) { - weather = w; - // (could add logic here to only call changed() - // if the new value is different from the old) - weatherDep.changed(); +var setWeather = function (w: string) { + weather = w; + // (could add logic here to only call changed() + // if the new value is different from the old) + weatherDep.changed(); }; /** * From HTTP, HTTP.call section */ -Meteor.methods({checkTwitter: function (userId:string) { - check(userId, String); - this.unblock(); - var result = HTTP.call("GET", "http://api.twitter.com/xyz", - {params: {user: userId}}); - if (result.statusCode === 200) - return true - return false; -}}); +Meteor.methods({ + checkTwitter: function (userId: string) { + check(userId, String); + this.unblock(); + var result = HTTP.call("GET", "http://api.twitter.com/xyz", + { params: { user: userId } }); + if (result.statusCode === 200) + return true + return false; + } +}); HTTP.call("POST", "http://api.twitter.com/xyz", - {data: {some: "json", stuff: 1}}, - function (error: Meteor.Error, result:any) { - if (result.statusCode === 200) { - Session.set("twizzled", true); - } + { data: { some: "json", stuff: 1 } }, + function (error: Meteor.Error, result: any) { + if (result.statusCode === 200) { + Session.set("twizzled", true); + } }); /** * From Email, Email.send section */ Meteor.methods({ - sendEmail: function (to:string, from:string, subject:string, text:string) { - check([to, from, subject, text], [String]); + sendEmail: function (to: string, from: string, subject: string, text: string) { + check([to, from, subject, text], [String]); - // Let other method calls from the same client start running, - // without waiting for the email sending to complete. - this.unblock(); - } + // Let other method calls from the same client start running, + // without waiting for the email sending to complete. + this.unblock(); + } }); // In your client code: asynchronously send an email @@ -603,74 +624,112 @@ Meteor.call('sendEmail', 'Hello from Meteor!', 'This is a test of Email.send.'); -var testTemplate = new Blaze.Template(); -var testView = new Blaze.View(); +var testTemplate = new Blaze.Template('foo'); +var testView = new Blaze.View('foo'); +Blaze.Template.instance(); declare var el: HTMLElement; Blaze.render(testTemplate, el); -Blaze.renderWithData(testTemplate, {testData: 123}, el); +Blaze.renderWithData(testTemplate, { testData: 123 }, el); Blaze.remove(testView); Blaze.getData(el); Blaze.getData(testView); Blaze.toHTML(testTemplate); Blaze.toHTML(testView); -Blaze.toHTMLWithData(testTemplate, {test: 1}); -Blaze.toHTMLWithData(testTemplate, function() {}); -Blaze.toHTMLWithData(testView, {test: 1}); -Blaze.toHTMLWithData(testView, function() {}); +Blaze.toHTMLWithData(testTemplate, { test: 1 }); +Blaze.toHTMLWithData(testTemplate, function () { }); +Blaze.toHTMLWithData(testView, { test: 1 }); +Blaze.toHTMLWithData(testView, function () { }); var reactiveVar1 = new ReactiveVar('test value'); -var reactiveVar2 = new ReactiveVar('test value', function(oldVal:any) { return true; }); +var reactiveVar2 = new ReactiveVar('test value', function (oldVal: any) { return true; }); var varValue: string = reactiveVar1.get(); reactiveVar1.set('new value'); // Covers this PR: https://github.com/DefinitelyTyped/DefinitelyTyped/pull/8233 var isConfigured: boolean = Accounts.loginServicesConfigured(); -Accounts.onPageLoadLogin(function() { - // do something +Accounts.onPageLoadLogin(function () { + // do something }); // Covers this PR: https://github.com/DefinitelyTyped/DefinitelyTyped/pull/8065 -var loginOpts: Meteor.LoginWithExternalServiceOptions = { - requestPermissions: ["a", "b"], - requestOfflineToken: true, - loginUrlParameters: {asdf: 1, qwer: "1234"}, - loginHint: "Help me", - loginStyle: "Bold and powerful", - redirectUrl: "popup", - profile: "asdfasdf", - email: "asdf@ASDf.com" +var loginOpts = { + requestPermissions: ["a", "b"], + requestOfflineToken: true, + loginUrlParameters: { asdf: 1, qwer: "1234" }, + loginHint: "Help me", + loginStyle: "Bold and powerful", + redirectUrl: "popup", + profile: "asdfasdf" }; -Meteor.loginWithMeteorDeveloperAccount(loginOpts, function(error: Meteor.Error) {}); +Meteor.loginWithMeteorDeveloperAccount(loginOpts, function (error: Meteor.Error) { }); Accounts.emailTemplates.siteName = "AwesomeSite"; Accounts.emailTemplates.from = "AwesomeSite Admin "; Accounts.emailTemplates.headers = { asdf: 'asdf', qwer: 'qwer' }; Accounts.emailTemplates.enrollAccount.subject = function (user: Meteor.User) { - return "Welcome to Awesome Town, " + user.profile.name; + return "Welcome to Awesome Town, " + user.profile.name; }; Accounts.emailTemplates.enrollAccount.html = function (user: Meteor.User, url: string) { - return "

Some html here

"; + return "

Some html here

"; }; -Accounts.emailTemplates.enrollAccount.from = function() { - return "asdf@asdf.com"; +Accounts.emailTemplates.enrollAccount.from = function () { + return "asdf@asdf.com"; }; Accounts.emailTemplates.enrollAccount.text = function (user: Meteor.User, url: string) { - return "You have been selected to participate in building a better future!" + return "You have been selected to participate in building a better future!" + " To activate your account, simply click the link below:\n\n" + url; }; -var handle = Accounts.validateLoginAttempt(function(attemptInfoObject: Accounts.IValidateLoginAttemptCbOpts) { - var type: string = attemptInfoObject.type; - var allowed: boolean = attemptInfoObject.allowed; - var error: Meteor.Error = attemptInfoObject.error; - var user: Meteor.User = attemptInfoObject.user; - var connection: Meteor.Connection = attemptInfoObject.connection; - var methodName: string = attemptInfoObject.methodName; - var methodArguments: any[] = attemptInfoObject.methodArguments; - return true; +var handle = Accounts.validateLoginAttempt(function (attemptInfoObject: Accounts.IValidateLoginAttemptCbOpts) { + var type: string = attemptInfoObject.type; + var allowed: boolean = attemptInfoObject.allowed; + var error: Meteor.Error = attemptInfoObject.error; + var user: Meteor.User = attemptInfoObject.user; + var connection: Meteor.Connection = attemptInfoObject.connection; + var methodName: string = attemptInfoObject.methodName; + var methodArguments: any[] = attemptInfoObject.methodArguments; + return true; }); handle.stop(); + + +// Covers https://github.com/meteor-typings/meteor/issues/8 +const publicSetting = Meteor.settings.public['somePublicSetting']; +const deeperPublicSetting = Meteor.settings.public['somePublicSetting']['deeperSetting']; +const privateSetting = Meteor.settings['somePrivateSetting']; +const deeperPrivateSetting = Meteor.settings['somePrivateSettings']['deeperSetting']; + + +// Covers https://github.com/meteor-typings/meteor/issues/9 +const username = (Template.instance().find('#username')).value; + + +// Covers https://github.com/meteor-typings/meteor/issues/3 +BrowserPolicy.framing.disallow(); +BrowserPolicy.content.allowEval(); + + +// Covers https://github.com/meteor-typings/meteor/issues/18 +if (Meteor.isDevelopment) { + Rooms._dropIndex({ field: 1 }); +} + + +// Covers https://github.com/meteor-typings/meteor/issues/20 +Rooms.find().count(true); + + +// Covers https://github.com/meteor-typings/meteor/issues/21 +if (Meteor.isTest) { + // do something +} + +DDPRateLimiter.addRule({ userId: 'foo' }, 5, 1000); + +DDPRateLimiter.addRule((userId: string) => userId == 'foo', 5, 1000); + +Template.instance().autorun(() => { }).stop(); diff --git a/mongoose/index.d.ts b/mongoose/index.d.ts index 7ef5615436..25b0e177ea 100644 --- a/mongoose/index.d.ts +++ b/mongoose/index.d.ts @@ -385,6 +385,9 @@ declare module "mongoose" { * If connecting to multiple mongos servers, set the mongos option to true. */ mongos?: boolean; + + /** sets the underlying driver's promise library (see http://mongodb.github.io/node-mongodb-native/2.1/api/MongoClient.html) */ + promiseLibrary?: any; } interface ConnectionOptions extends @@ -720,6 +723,8 @@ declare module "mongoose" { validateBeforeSave?: boolean; /** defaults to "__v" */ versionKey?: string|boolean; + /** defaults to false */ + retainKeyOrder?: boolean; /** * skipVersioning allows excluding paths from * versioning (the internal revision will not be diff --git a/node-forge/index.d.ts b/node-forge/index.d.ts index 8640f699d4..900fdfc2f9 100644 --- a/node-forge/index.d.ts +++ b/node-forge/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for node-forge 0.6.42 // Project: https://github.com/digitalbazaar/forge // Definitions by: Seth Westphal +// Kay Schecker // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module "node-forge" { @@ -23,6 +24,7 @@ declare module "node-forge" { function privateKeyToPem(key: Key, maxline?: number): PEM; function publicKeyToPem(key: Key, maxline?: number): PEM; + function certificateToPem(cert: Certificate, maxline?: number): PEM; interface oids { [key: string]: string; @@ -234,4 +236,40 @@ declare module "node-forge" { } } } + + namespace pkcs12 { + + interface BagsFilter { + localKeyId?: string; + localKeyIdHex?: string; + friendlyName?: string; + bagType?: string; + } + + interface Bag { + type: string; + attributes: any; + key?: pki.Key; + cert?: pki.Certificate; + asn1: asn1.Asn1 + } + + interface Pkcs12Pfx { + version: string; + safeContents: [{ + encrypted: boolean; + safeBags: Bag[]; + }]; + getBags: (filter: BagsFilter) => { + [key: string]: Bag[]; + localKeyId?: Bag[]; + friendlyName?: Bag[]; + }; + getBagsByFriendlyName: (fiendlyName: string, bagType: string) => Bag[] + getBagsByLocalKeyId: (localKeyId: string, bagType: string) => Bag[] + } + + function pkcs12FromAsn1(obj:any, strict?: boolean, password?: string) : Pkcs12Pfx; + function pkcs12FromAsn1(obj:any, password?: string) : Pkcs12Pfx; + } } diff --git a/notNeededPackages.json b/notNeededPackages.json index 0cd56b96d1..27b2764051 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -305,6 +305,18 @@ "typingsPackageName": "gaea-model", "sourceRepoURL": "https://github.com/ascoders/gaea-model", "asOfVersion": "0.0.0" + }, + { + "libraryName": "Raven JS", + "typingsPackageName": "raven-js", + "sourceRepoURL": "https://github.com/getsentry/raven-js", + "asOfVersion": "3.10.0" + }, + { + "libraryName": "antd", + "typingsPackageName": "antd", + "sourceRepoURL": "https://github.com/ant-design/ant-design", + "asOfVersion": "1.0.0" } ] } diff --git a/office-js/index.d.ts b/office-js/index.d.ts index dd18c22914..2c78cac7f4 100644 --- a/office-js/index.d.ts +++ b/office-js/index.d.ts @@ -10328,29 +10328,7 @@ declare module Excel { //////////////////////////////////////////////////////////////// -declare module Word { - /** - * - * The Application object. - * - * [Api set: WordApi 1.3] - */ - class Application extends OfficeExtension.ClientObject { - /** - * - * Creates a new document by using a base64 encoded .docx file. - * - * @param base64File Optional. The base64 encoded .docx file. The default value is null. - * - * [Api set: WordApi 1.3] - */ - createDocument(base64File?: string): Word.Document; - /** - * Create a new instance of Word.Application object - */ - static newObject(context: OfficeExtension.ClientRequestContext): Word.Application; - toJSON(): {}; - } +declare namespace Word { /** * * Represents the body of a document or a section. @@ -10395,25 +10373,46 @@ declare module Word { paragraphs: Word.ParagraphCollection; /** * - * Gets the parent body of the body. For example, a table cell body's parent body could be a header. Read-only. + * Gets the parent body of the body. For example, a table cell body's parent body could be a header. Throws if there isn't a parent body. Read-only. * * [Api set: WordApi 1.3] */ parentBody: Word.Body; /** * - * Gets the content control that contains the body. Returns a null object if there isn't a parent content control. Read-only. + * Gets the parent body of the body. For example, a table cell body's parent body could be a header. Returns a null object if there isn't a parent body. Read-only. + * + * [Api set: WordApi 1.3] + */ + parentBodyOrNullObject: Word.Body; + /** + * + * Gets the content control that contains the body. Throws if there isn't a parent content control. Read-only. * * [Api set: WordApi 1.1] */ parentContentControl: Word.ContentControl; /** * - * Gets the parent section of the body. Read-only. + * Gets the content control that contains the body. Returns a null object if there isn't a parent content control. Read-only. + * + * [Api set: WordApi 1.3] + */ + parentContentControlOrNullObject: Word.ContentControl; + /** + * + * Gets the parent section of the body. Throws if there isn't a parent section. Read-only. * * [Api set: WordApi 1.3] */ parentSection: Word.Section; + /** + * + * Gets the parent section of the body. Returns a null object if there isn't a parent section. Read-only. + * + * [Api set: WordApi 1.3] + */ + parentSectionOrNullObject: Word.Section; /** * * Gets the collection of table objects in the body. Read-only. @@ -10449,6 +10448,15 @@ declare module Word { * [Api set: WordApi 1.3] */ type: string; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.BodyUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: Body): void; /** * * Clears the contents of the body object. The user can perform the undo operation on the cleared content. @@ -10474,19 +10482,19 @@ declare module Word { * * Gets the whole body, or the starting or ending point of the body, as a range. * - * @param rangeLocation Optional. The range location can be 'Whole', 'Start', 'End', 'After' or 'Content'. - * * [Api set: WordApi 1.3] + * + * @param rangeLocation Optional. The range location can be 'Whole', 'Start', 'End', 'After' or 'Content'. */ getRange(rangeLocation?: string): Word.Range; /** * * Inserts a break at the specified location in the main document. The insertLocation value can be 'Start' or 'End'. * + * [Api set: WordApi 1.1] + * * @param breakType Required. The break type to add to the body. * @param insertLocation Required. The value can be 'Start' or 'End'. - * - * [Api set: WordApi 1.1] */ insertBreak(breakType: string, insertLocation: string): void; /** @@ -10500,82 +10508,82 @@ declare module Word { * * Inserts a document into the body at the specified location. The insertLocation value can be 'Replace', 'Start' or 'End'. * + * [Api set: WordApi 1.1] + * * @param base64File Required. The base64 encoded content of a .docx file. * @param insertLocation Required. The value can be 'Replace', 'Start' or 'End'. - * - * [Api set: WordApi 1.1] */ insertFileFromBase64(base64File: string, insertLocation: string): Word.Range; /** * * Inserts HTML at the specified location. The insertLocation value can be 'Replace', 'Start' or 'End'. * + * [Api set: WordApi 1.1] + * * @param html Required. The HTML to be inserted in the document. * @param insertLocation Required. The value can be 'Replace', 'Start' or 'End'. - * - * [Api set: WordApi 1.1] */ insertHtml(html: string, insertLocation: string): Word.Range; /** * * Inserts a picture into the body at the specified location. The insertLocation value can be 'Start' or 'End'. * + * [Api set: WordApi 1.2] + * * @param base64EncodedImage Required. The base64 encoded image to be inserted in the body. * @param insertLocation Required. The value can be 'Start' or 'End'. - * - * [Api set: WordApi 1.2] */ insertInlinePictureFromBase64(base64EncodedImage: string, insertLocation: string): Word.InlinePicture; /** * * Inserts OOXML at the specified location. The insertLocation value can be 'Replace', 'Start' or 'End'. * + * [Api set: WordApi 1.1] + * * @param ooxml Required. The OOXML to be inserted. * @param insertLocation Required. The value can be 'Replace', 'Start' or 'End'. - * - * [Api set: WordApi 1.1] */ insertOoxml(ooxml: string, insertLocation: string): Word.Range; /** * * Inserts a paragraph at the specified location. The insertLocation value can be 'Start' or 'End'. * + * [Api set: WordApi 1.1] + * * @param paragraphText Required. The paragraph text to be inserted. * @param insertLocation Required. The value can be 'Start' or 'End'. - * - * [Api set: WordApi 1.1] */ insertParagraph(paragraphText: string, insertLocation: string): Word.Paragraph; /** * * Inserts a table with the specified number of rows and columns. The insertLocation value can be 'Start' or 'End'. * + * [Api set: WordApi 1.3] + * * @param rowCount Required. The number of rows in the table. * @param columnCount Required. The number of columns in the table. * @param insertLocation Required. The value can be 'Start' or 'End'. * @param values Optional 2D array. Cells are filled if the corresponding strings are specified in the array. - * - * [Api set: WordApi 1.3] */ insertTable(rowCount: number, columnCount: number, insertLocation: string, values?: Array>): Word.Table; /** * * Inserts text into the body at the specified location. The insertLocation value can be 'Replace', 'Start' or 'End'. * + * [Api set: WordApi 1.1] + * * @param text Required. Text to be inserted. * @param insertLocation Required. The value can be 'Replace', 'Start' or 'End'. - * - * [Api set: WordApi 1.1] */ insertText(text: string, insertLocation: string): Word.Range; /** * * Performs a search with the specified searchOptions on the scope of the body object. The search results are a collection of range objects. * + * [Api set: WordApi 1.1] + * * @param searchText Required. The search text. * @param searchOptions Optional. Options for the search. - * - * [Api set: WordApi 1.1] */ search(searchText: string, searchOptions?: Word.SearchOptions | { ignorePunct?: boolean; @@ -10590,9 +10598,9 @@ declare module Word { * * Selects the body and navigates the Word UI to it. * - * @param selectionMode Optional. The selection mode can be 'Select', 'Start' or 'End'. 'Select' is the default. - * * [Api set: WordApi 1.1] + * + * @param selectionMode Optional. The selection mode can be 'Select', 'Start' or 'End'. 'Select' is the default. */ select(selectionMode?: string): void; /** @@ -10604,7 +10612,7 @@ declare module Word { */ track(): Word.Body; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.Body; toJSON(): { @@ -10666,25 +10674,46 @@ declare module Word { parentBody: Word.Body; /** * - * Gets the content control that contains the content control. Returns a null object if there isn't a parent content control. Read-only. + * Gets the content control that contains the content control. Throws if there isn't a parent content control. Read-only. * * [Api set: WordApi 1.1] */ parentContentControl: Word.ContentControl; /** * - * Gets the table that contains the content control. Returns a null object if it is not contained in a table. Read-only. + * Gets the content control that contains the content control. Returns a null object if there isn't a parent content control. Read-only. + * + * [Api set: WordApi 1.3] + */ + parentContentControlOrNullObject: Word.ContentControl; + /** + * + * Gets the table that contains the content control. Throws if it is not contained in a table. Read-only. * * [Api set: WordApi 1.3] */ parentTable: Word.Table; /** * - * Gets the table cell that contains the content control. Returns a null object if it is not contained in a table cell. Read-only. + * Gets the table cell that contains the content control. Throws if it is not contained in a table cell. Read-only. * * [Api set: WordApi 1.3] */ parentTableCell: Word.TableCell; + /** + * + * Gets the table cell that contains the content control. Returns a null object if it is not contained in a table cell. Read-only. + * + * [Api set: WordApi 1.3] + */ + parentTableCellOrNullObject: Word.TableCell; + /** + * + * Gets the table that contains the content control. Returns a null object if it is not contained in a table. Read-only. + * + * [Api set: WordApi 1.3] + */ + parentTableOrNullObject: Word.Table; /** * * Gets the collection of table objects in the content control. Read-only. @@ -10790,6 +10819,15 @@ declare module Word { * [Api set: WordApi 1.1] */ type: string; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.ContentControlUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: ContentControl): void; /** * * Clears the contents of the content control. The user can perform the undo operation on the cleared content. @@ -10801,9 +10839,9 @@ declare module Word { * * Deletes the content control and its content. If keepContent is set to true, the content is not deleted. * - * @param keepContent Required. Indicates whether the content should be deleted with the content control. If keepContent is set to true, the content is not deleted. - * * [Api set: WordApi 1.1] + * + * @param keepContent Required. Indicates whether the content should be deleted with the content control. If keepContent is set to true, the content is not deleted. */ delete(keepContent: boolean): void; /** @@ -10824,111 +10862,111 @@ declare module Word { * * Gets the whole content control, or the starting or ending point of the content control, as a range. * - * @param rangeLocation Optional. The range location can be 'Whole', 'Before', 'Start', 'End', 'After' or 'Content'. - * * [Api set: WordApi 1.3] + * + * @param rangeLocation Optional. The range location can be 'Whole', 'Before', 'Start', 'End', 'After' or 'Content'. */ getRange(rangeLocation?: string): Word.Range; /** * * Gets the text ranges in the content control by using punctuation marks and/or other ending marks. * + * [Api set: WordApi 1.3] + * * @param endingMarks Required. The punctuation marks and/or other ending marks as an array of strings. * @param trimSpacing Optional. Indicates whether to trim spacing characters (spaces, tabs, column breaks and paragraph end marks) from the start and end of the ranges returned in the range collection. Default is false which indicates that spacing characters at the start and end of the ranges are included in the range collection. - * - * [Api set: WordApi 1.3] */ getTextRanges(endingMarks: Array, trimSpacing?: boolean): Word.RangeCollection; /** * * Inserts a break at the specified location in the main document. The insertLocation value can be 'Start', 'End', 'Before' or 'After'. This method cannot be used with 'RichTextTable', 'RichTextTableRow' and 'RichTextTableCell' content controls. * + * [Api set: WordApi 1.1] + * * @param breakType Required. Type of break. * @param insertLocation Required. The value can be 'Start', 'End', 'Before' or 'After'. - * - * [Api set: WordApi 1.1] */ insertBreak(breakType: string, insertLocation: string): void; /** * * Inserts a document into the content control at the specified location. The insertLocation value can be 'Replace', 'Start' or 'End'. * + * [Api set: WordApi 1.1] + * * @param base64File Required. The base64 encoded content of a .docx file. * @param insertLocation Required. The value can be 'Replace', 'Start' or 'End'. 'Replace' cannot be used with 'RichTextTable' and 'RichTextTableRow' content controls. - * - * [Api set: WordApi 1.1] */ insertFileFromBase64(base64File: string, insertLocation: string): Word.Range; /** * * Inserts HTML into the content control at the specified location. The insertLocation value can be 'Replace', 'Start' or 'End'. * + * [Api set: WordApi 1.1] + * * @param html Required. The HTML to be inserted in to the content control. * @param insertLocation Required. The value can be 'Replace', 'Start' or 'End'. 'Replace' cannot be used with 'RichTextTable' and 'RichTextTableRow' content controls. - * - * [Api set: WordApi 1.1] */ insertHtml(html: string, insertLocation: string): Word.Range; /** * * Inserts an inline picture into the content control at the specified location. The insertLocation value can be 'Replace', 'Start' or 'End'. * + * [Api set: WordApi 1.2] + * * @param base64EncodedImage Required. The base64 encoded image to be inserted in the content control. * @param insertLocation Required. The value can be 'Replace', 'Start' or 'End'. 'Replace' cannot be used with 'RichTextTable' and 'RichTextTableRow' content controls. - * - * [Api set: WordApi 1.2] */ insertInlinePictureFromBase64(base64EncodedImage: string, insertLocation: string): Word.InlinePicture; /** * * Inserts OOXML into the content control at the specified location. The insertLocation value can be 'Replace', 'Start' or 'End'. * + * [Api set: WordApi 1.1] + * * @param ooxml Required. The OOXML to be inserted in to the content control. * @param insertLocation Required. The value can be 'Replace', 'Start' or 'End'. 'Replace' cannot be used with 'RichTextTable' and 'RichTextTableRow' content controls. - * - * [Api set: WordApi 1.1] */ insertOoxml(ooxml: string, insertLocation: string): Word.Range; /** * * Inserts a paragraph at the specified location. The insertLocation value can be 'Start', 'End', 'Before' or 'After'. * + * [Api set: WordApi 1.1] + * * @param paragraphText Required. The paragrph text to be inserted. * @param insertLocation Required. The value can be 'Start', 'End', 'Before' or 'After'. 'Before' and 'After' cannot be used with 'RichTextTable', 'RichTextTableRow' and 'RichTextTableCell' content controls. - * - * [Api set: WordApi 1.1] */ insertParagraph(paragraphText: string, insertLocation: string): Word.Paragraph; /** * * Inserts a table with the specified number of rows and columns into, or next to, a content control. The insertLocation value can be 'Start', 'End', 'Before' or 'After'. * + * [Api set: WordApi 1.3] + * * @param rowCount Required. The number of rows in the table. * @param columnCount Required. The number of columns in the table. * @param insertLocation Required. The value can be 'Start', 'End', 'Before' or 'After'. 'Before' and 'After' cannot be used with 'RichTextTable', 'RichTextTableRow' and 'RichTextTableCell' content controls. * @param values Optional 2D array. Cells are filled if the corresponding strings are specified in the array. - * - * [Api set: WordApi 1.3] */ insertTable(rowCount: number, columnCount: number, insertLocation: string, values?: Array>): Word.Table; /** * * Inserts text into the content control at the specified location. The insertLocation value can be 'Replace', 'Start' or 'End'. * + * [Api set: WordApi 1.1] + * * @param text Required. The text to be inserted in to the content control. * @param insertLocation Required. The value can be 'Replace', 'Start' or 'End'. 'Replace' cannot be used with 'RichTextTable' and 'RichTextTableRow' content controls. - * - * [Api set: WordApi 1.1] */ insertText(text: string, insertLocation: string): Word.Range; /** * * Performs a search with the specified searchOptions on the scope of the content control object. The search results are a collection of range objects. * + * [Api set: WordApi 1.1] + * * @param searchText Required. The search text. * @param searchOptions Optional. Options for the search. - * - * [Api set: WordApi 1.1] */ search(searchText: string, searchOptions?: Word.SearchOptions | { ignorePunct?: boolean; @@ -10943,21 +10981,21 @@ declare module Word { * * Selects the content control. This causes Word to scroll to the selection. * - * @param selectionMode Optional. The selection mode can be 'Select', 'Start' or 'End'. 'Select' is the default. - * * [Api set: WordApi 1.1] + * + * @param selectionMode Optional. The selection mode can be 'Select', 'Start' or 'End'. 'Select' is the default. */ select(selectionMode?: string): void; /** * * Splits the content control into child ranges by using delimiters. * + * [Api set: WordApi 1.3] + * * @param delimiters Required. The delimiters as an array of strings. * @param multiParagraphs Optional. Indicates whether a returned child range can cover multiple paragraphs. Default is false which indicates that the paragraph boundaries are also used as delimiters. * @param trimDelimiters Optional. Indicates whether to trim delimiters from the ranges in the range collection. Default is false which indicates that the delimiters are included in the ranges returned in the range collection. * @param trimSpacing Optional. Indicates whether to trim spacing characters (spaces, tabs, column breaks and paragraph end marks) from the start and end of the ranges returned in the range collection. Default is false which indicates that spacing characters at the start and end of the ranges are included in the range collection. - * - * [Api set: WordApi 1.3] */ split(delimiters: Array, multiParagraphs?: boolean, trimDelimiters?: boolean, trimSpacing?: boolean): Word.RangeCollection; /** @@ -10969,7 +11007,7 @@ declare module Word { */ track(): Word.ContentControl; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.ContentControl; toJSON(): { @@ -11001,54 +11039,70 @@ declare module Word { items: Array; /** * - * Gets a content control by its identifier. - * - * @param id Required. A content control identifier. + * Gets a content control by its identifier. Throws if there isn't a content control with the identifier in this collection. * * [Api set: WordApi 1.1] + * + * @param id Required. A content control identifier. */ getById(id: number): Word.ContentControl; + /** + * + * Gets a content control by its identifier. Returns a null object if there isn't a content control with the identifier in this collection. + * + * [Api set: WordApi 1.3] + * + * @param id Required. A content control identifier. + */ + getByIdOrNullObject(id: number): Word.ContentControl; /** * * Gets the content controls that have the specified tag. * - * @param tag Required. A tag set on a content control. - * * [Api set: WordApi 1.1] + * + * @param tag Required. A tag set on a content control. */ getByTag(tag: string): Word.ContentControlCollection; /** * * Gets the content controls that have the specified title. * - * @param title Required. The title of a content control. - * * [Api set: WordApi 1.1] + * + * @param title Required. The title of a content control. */ getByTitle(title: string): Word.ContentControlCollection; /** * * Gets the content controls that have the specified types and/or subtypes. * - * @param types Required. An array of content control types and/or subtypes. - * * [Api set: WordApi 1.3] + * + * @param types Required. An array of content control types and/or subtypes. */ getByTypes(types: Array): Word.ContentControlCollection; /** * - * Gets the first content control in this collection. + * Gets the first content control in this collection. Throws if this collection is empty. * * [Api set: WordApi 1.3] */ getFirst(): Word.ContentControl; + /** + * + * Gets the first content control in this collection. Returns a null object if this collection is empty. + * + * [Api set: WordApi 1.3] + */ + getFirstOrNullObject(): Word.ContentControl; /** * * Gets a content control by its index in the collection. * - * @param index The index. - * * [Api set: WordApi 1.1] + * + * @param index The index. */ getItem(index: number): Word.ContentControl; /** @@ -11060,7 +11114,7 @@ declare module Word { */ track(): Word.ContentControlCollection; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.ContentControlCollection; toJSON(): {}; @@ -11093,6 +11147,15 @@ declare module Word { * [Api set: WordApi 1.3] */ value: any; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.CustomPropertyUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: CustomProperty): void; /** * * Deletes the custom property. @@ -11109,7 +11172,7 @@ declare module Word { */ track(): Word.CustomProperty; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.CustomProperty; toJSON(): { @@ -11127,6 +11190,16 @@ declare module Word { class CustomPropertyCollection extends OfficeExtension.ClientObject { /** Gets the loaded child items in this collection. */ items: Array; + /** + * + * Creates a new or sets an existing custom property. + * + * [Api set: WordApi 1.3] + * + * @param key Required. The custom property's key, which is case-insensitive. + * @param value Required. The custom property's value. + */ + add(key: string, value: any): Word.CustomProperty; /** * * Deletes all custom properties in this collection. @@ -11143,23 +11216,22 @@ declare module Word { getCount(): OfficeExtension.ClientResult; /** * - * Gets a custom property object by its key, which is case-insensitive. - * - * @param key The key that identifies the custom property object. + * Gets a custom property object by its key, which is case-insensitive. Throws if the custom property does not exist. * * [Api set: WordApi 1.3] + * + * @param key The key that identifies the custom property object. */ getItem(key: string): Word.CustomProperty; /** * - * Creates or sets a custom property. - * - * @param key Required. The custom property's key, which is case-insensitive. - * @param value Required. The custom property's value. + * Gets a custom property object by its key, which is case-insensitive. Returns a null object if the custom property does not exist. * * [Api set: WordApi 1.3] + * + * @param key Required. The key that identifies the custom property object. */ - set(key: string, value: any): Word.CustomProperty; + getItemOrNullObject(key: string): Word.CustomProperty; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -11169,7 +11241,7 @@ declare module Word { */ track(): Word.CustomPropertyCollection; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.CustomPropertyCollection; toJSON(): {}; @@ -11216,6 +11288,15 @@ declare module Word { * [Api set: WordApi 1.1] */ saved: boolean; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.DocumentUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: Document): void; /** * * Gets the current selection of the document. Multiple selections are not supported. @@ -11223,13 +11304,6 @@ declare module Word { * [Api set: WordApi 1.1] */ getSelection(): Word.Range; - /** - * - * Open the document. - * - * [Api set: WordApi 1.3] - */ - open(): void; /** * * Saves the document. This will use the Word default file naming convention if the document has not been saved before. @@ -11246,7 +11320,7 @@ declare module Word { */ track(): Word.Document; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.Document; toJSON(): { @@ -11327,7 +11401,7 @@ declare module Word { keywords: string; /** * - * Gets or sets the last author of the document. + * Gets the last author of the document. Read only. * * [Api set: WordApi 1.3] */ @@ -11388,6 +11462,15 @@ declare module Word { * [Api set: WordApi 1.3] */ title: string; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.DocumentPropertiesUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: DocumentProperties): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -11397,7 +11480,7 @@ declare module Word { */ track(): Word.DocumentProperties; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.DocumentProperties; toJSON(): { @@ -11504,6 +11587,15 @@ declare module Word { * [Api set: WordApi 1.1] */ underline: string; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.FontUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: Font): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -11513,7 +11605,7 @@ declare module Word { */ track(): Word.Font; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.Font; toJSON(): { @@ -11546,25 +11638,46 @@ declare module Word { paragraph: Word.Paragraph; /** * - * Gets the content control that contains the inline image. Returns a null object if there isn't a parent content control. Read-only. + * Gets the content control that contains the inline image. Throws if there isn't a parent content control. Read-only. * * [Api set: WordApi 1.1] */ parentContentControl: Word.ContentControl; /** * - * Gets the table that contains the inline image. Returns a null object if it is not contained in a table. Read-only. + * Gets the content control that contains the inline image. Returns a null object if there isn't a parent content control. Read-only. + * + * [Api set: WordApi 1.3] + */ + parentContentControlOrNullObject: Word.ContentControl; + /** + * + * Gets the table that contains the inline image. Throws if it is not contained in a table. Read-only. * * [Api set: WordApi 1.3] */ parentTable: Word.Table; /** * - * Gets the table cell that contains the inline image. Returns a null object if it is not contained in a table cell. Read-only. + * Gets the table cell that contains the inline image. Throws if it is not contained in a table cell. Read-only. * * [Api set: WordApi 1.3] */ parentTableCell: Word.TableCell; + /** + * + * Gets the table cell that contains the inline image. Returns a null object if it is not contained in a table cell. Read-only. + * + * [Api set: WordApi 1.3] + */ + parentTableCellOrNullObject: Word.TableCell; + /** + * + * Gets the table that contains the inline image. Returns a null object if it is not contained in a table. Read-only. + * + * [Api set: WordApi 1.3] + */ + parentTableOrNullObject: Word.Table; /** * * Gets or sets a string that represents the alternative text associated with the inline image @@ -11588,7 +11701,7 @@ declare module Word { height: number; /** * - * Gets or sets a hyperlink on the image. Use a newline character ('\n') to separate the address part from the optional location part. + * Gets or sets a hyperlink on the image. Use a '#' to separate the address part from the optional location part. * * [Api set: WordApi 1.1] */ @@ -11607,6 +11720,15 @@ declare module Word { * [Api set: WordApi 1.1] */ width: number; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.InlinePictureUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: InlinePicture): void; /** * * Deletes the inline picture from the document. @@ -11623,28 +11745,35 @@ declare module Word { getBase64ImageSrc(): OfficeExtension.ClientResult; /** * - * Gets the next inline image. + * Gets the next inline image. Throws if this inline image is the last one. * * [Api set: WordApi 1.3] */ getNext(): Word.InlinePicture; /** * - * Gets the picture, or the starting or ending point of the picture, as a range. - * - * @param rangeLocation Optional. The range location can be 'Whole', 'Start' or 'End'. + * Gets the next inline image. Returns a null object if this inline image is the last one. * * [Api set: WordApi 1.3] */ + getNextOrNullObject(): Word.InlinePicture; + /** + * + * Gets the picture, or the starting or ending point of the picture, as a range. + * + * [Api set: WordApi 1.3] + * + * @param rangeLocation Optional. The range location can be 'Whole', 'Start' or 'End'. + */ getRange(rangeLocation?: string): Word.Range; /** * * Inserts a break at the specified location in the main document. The insertLocation value can be 'Before' or 'After'. * + * [Api set: WordApi 1.2] + * * @param breakType Required. The break type to add. * @param insertLocation Required. The value can be 'Before' or 'After'. - * - * [Api set: WordApi 1.2] */ insertBreak(breakType: string, insertLocation: string): void; /** @@ -11658,69 +11787,69 @@ declare module Word { * * Inserts a document at the specified location. The insertLocation value can be 'Before' or 'After'. * + * [Api set: WordApi 1.2] + * * @param base64File Required. The base64 encoded content of a .docx file. * @param insertLocation Required. The value can be 'Before' or 'After'. - * - * [Api set: WordApi 1.2] */ insertFileFromBase64(base64File: string, insertLocation: string): Word.Range; /** * * Inserts HTML at the specified location. The insertLocation value can be 'Before' or 'After'. * + * [Api set: WordApi 1.2] + * * @param html Required. The HTML to be inserted. * @param insertLocation Required. The value can be 'Before' or 'After'. - * - * [Api set: WordApi 1.2] */ insertHtml(html: string, insertLocation: string): Word.Range; /** * * Inserts an inline picture at the specified location. The insertLocation value can be 'Replace', 'Before' or 'After'. * + * [Api set: WordApi 1.2] + * * @param base64EncodedImage Required. The base64 encoded image to be inserted. * @param insertLocation Required. The value can be 'Replace', 'Before' or 'After'. - * - * [Api set: WordApi 1.2] */ insertInlinePictureFromBase64(base64EncodedImage: string, insertLocation: string): Word.InlinePicture; /** * * Inserts OOXML at the specified location. The insertLocation value can be 'Before' or 'After'. * + * [Api set: WordApi 1.2] + * * @param ooxml Required. The OOXML to be inserted. * @param insertLocation Required. The value can be 'Before' or 'After'. - * - * [Api set: WordApi 1.2] */ insertOoxml(ooxml: string, insertLocation: string): Word.Range; /** * * Inserts a paragraph at the specified location. The insertLocation value can be 'Before' or 'After'. * + * [Api set: WordApi 1.2] + * * @param paragraphText Required. The paragraph text to be inserted. * @param insertLocation Required. The value can be 'Before' or 'After'. - * - * [Api set: WordApi 1.2] */ insertParagraph(paragraphText: string, insertLocation: string): Word.Paragraph; /** * * Inserts text at the specified location. The insertLocation value can be 'Before' or 'After'. * + * [Api set: WordApi 1.2] + * * @param text Required. Text to be inserted. * @param insertLocation Required. The value can be 'Before' or 'After'. - * - * [Api set: WordApi 1.2] */ insertText(text: string, insertLocation: string): Word.Range; /** * * Selects the inline picture. This causes Word to scroll to the selection. * - * @param selectionMode Optional. The selection mode can be 'Select', 'Start' or 'End'. 'Select' is the default. - * * [Api set: WordApi 1.2] + * + * @param selectionMode Optional. The selection mode can be 'Select', 'Start' or 'End'. 'Select' is the default. */ select(selectionMode?: string): void; /** @@ -11732,7 +11861,7 @@ declare module Word { */ track(): Word.InlinePicture; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.InlinePicture; toJSON(): { @@ -11755,11 +11884,18 @@ declare module Word { items: Array; /** * - * Gets the first inline image in this collection. + * Gets the first inline image in this collection. Throws if this collection is empty. * * [Api set: WordApi 1.3] */ getFirst(): Word.InlinePicture; + /** + * + * Gets the first inline image in this collection. Returns a null object if this collection is empty. + * + * [Api set: WordApi 1.3] + */ + getFirstOrNullObject(): Word.InlinePicture; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -11769,7 +11905,7 @@ declare module Word { */ track(): Word.InlinePictureCollection; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.InlinePictureCollection; toJSON(): {}; @@ -11813,82 +11949,82 @@ declare module Word { * * Gets the paragraphs that occur at the specified level in the list. * - * @param level Required. The level in the list. - * * [Api set: WordApi 1.3] + * + * @param level Required. The level in the list. */ getLevelParagraphs(level: number): Word.ParagraphCollection; /** * * Gets the bullet, number or picture at the specified level as a string. * - * @param level Required. The level in the list. - * * [Api set: WordApi 1.3] + * + * @param level Required. The level in the list. */ getLevelString(level: number): OfficeExtension.ClientResult; /** * * Inserts a paragraph at the specified location. The insertLocation value can be 'Start', 'End', 'Before' or 'After'. * + * [Api set: WordApi 1.3] + * * @param paragraphText Required. The paragraph text to be inserted. * @param insertLocation Required. The value can be 'Start', 'End', 'Before' or 'After'. - * - * [Api set: WordApi 1.3] */ insertParagraph(paragraphText: string, insertLocation: string): Word.Paragraph; /** * * Sets the alignment of the bullet, number or picture at the specified level in the list. * + * [Api set: WordApi 1.3] + * * @param level Required. The level in the list. * @param alignment Required. The level alignment that can be 'left', 'centered' or 'right'. - * - * [Api set: WordApi 1.3] */ setLevelAlignment(level: number, alignment: string): void; /** * * Sets the bullet format at the specified level in the list. If the bullet is 'Custom', the charCode is required. * + * [Api set: WordApi 1.3] + * * @param level Required. The level in the list. * @param listBullet Required. The bullet. * @param charCode Optional. The bullet character's code value. Used only if the bullet is 'Custom'. * @param fontName Optional. The bullet's font name. Used only if the bullet is 'Custom'. - * - * [Api set: WordApi 1.3] */ setLevelBullet(level: number, listBullet: string, charCode?: number, fontName?: string): void; /** * * Sets the two indents of the specified level in the list. * + * [Api set: WordApi 1.3] + * * @param level Required. The level in the list. * @param textIndent Required. The text indent in points. It is the same as paragraph left indent. * @param textIndent Required. The relative indent, in points, of the bullet, number or picture. It is the same as paragraph first line indent. - * - * [Api set: WordApi 1.3] */ setLevelIndents(level: number, textIndent: number, bulletNumberPictureIndent: number): void; /** * * Sets the numbering format at the specified level in the list. * + * [Api set: WordApi 1.3] + * * @param level Required. The level in the list. * @param listNumbering Required. The ordinal format. * @param formatString Optional. The numbering string format defined as an array of strings and/or integers. Each integer is a level of number type that is higher than or equal to this level. For example, an array of ["(", level - 1, ".", level, ")"] can define the format of "(2.c)", where 2 is the parent's item number and c is this level's item number. - * - * [Api set: WordApi 1.3] */ setLevelNumbering(level: number, listNumbering: string, formatString?: Array): void; /** * * Sets the starting number at the specified level in the list. Default value is 1. * + * [Api set: WordApi 1.3] + * * @param level Required. The level in the list. * @param startingNumber Required. The number to start with. - * - * [Api set: WordApi 1.3] */ setLevelStartingNumber(level: number, startingNumber: number): void; /** @@ -11900,7 +12036,7 @@ declare module Word { */ track(): Word.List; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.List; toJSON(): { @@ -11920,28 +12056,44 @@ declare module Word { items: Array; /** * - * Gets a list by its identifier. - * - * @param id Required. A list identifier. + * Gets a list by its identifier. Throws if there isn't a list with the identifier in this collection. * * [Api set: WordApi 1.3] + * + * @param id Required. A list identifier. */ getById(id: number): Word.List; /** * - * Gets the first list in this collection. + * Gets a list by its identifier. Returns a null object if there isn't a list with the identifier in this collection. + * + * [Api set: WordApi 1.3] + * + * @param id Required. A list identifier. + */ + getByIdOrNullObject(id: number): Word.List; + /** + * + * Gets the first list in this collection. Throws if this collection is empty. * * [Api set: WordApi 1.3] */ getFirst(): Word.List; /** * - * Gets a list object by its index in the collection. - * - * @param index A number that identifies the index location of a list object. + * Gets the first list in this collection. Returns a null object if this collection is empty. * * [Api set: WordApi 1.3] */ + getFirstOrNullObject(): Word.List; + /** + * + * Gets a list object by its index in the collection. + * + * [Api set: WordApi 1.3] + * + * @param index A number that identifies the index location of a list object. + */ getItem(index: number): Word.List; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. @@ -11952,7 +12104,7 @@ declare module Word { */ track(): Word.ListCollection; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.ListCollection; toJSON(): {}; @@ -11985,22 +12137,40 @@ declare module Word { * [Api set: WordApi 1.3] */ siblingIndex: number; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.ListItemUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: ListItem): void; /** * - * Gets the list item parent, or the closest ancestor if the parent does not exist. - * - * @param parentOnly Optional. Specified only the list item's parent will be returned. The default is false that specifies to get the lowest ancestor. + * Gets the list item parent, or the closest ancestor if the parent does not exist. Throws if the list item has no ancester. * * [Api set: WordApi 1.3] + * + * @param parentOnly Optional. Specified only the list item's parent will be returned. The default is false that specifies to get the lowest ancestor. */ getAncestor(parentOnly?: boolean): Word.Paragraph; /** * - * Gets all descendant list items of the list item. - * - * @param directChildrenOnly Optional. Specified only the list item's direct children will be returned. The default is false that indicates to get all descendant items. + * Gets the list item parent, or the closest ancestor if the parent does not exist. Returns a null object if the list item has no ancester. * * [Api set: WordApi 1.3] + * + * @param parentOnly Optional. Specified only the list item's parent will be returned. The default is false that specifies to get the lowest ancestor. + */ + getAncestorOrNullObject(parentOnly?: boolean): Word.Paragraph; + /** + * + * Gets all descendant list items of the list item. + * + * [Api set: WordApi 1.3] + * + * @param directChildrenOnly Optional. Specified only the list item's direct children will be returned. The default is false that indicates to get all descendant items. */ getDescendants(directChildrenOnly?: boolean): Word.ParagraphCollection; /** @@ -12012,7 +12182,7 @@ declare module Word { */ track(): Word.ListItem; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.ListItem; toJSON(): { @@ -12051,18 +12221,32 @@ declare module Word { inlinePictures: Word.InlinePictureCollection; /** * - * Gets the List to which this paragraph belongs. Returns a null object if the paragraph is not in a list. Read-only. + * Gets the List to which this paragraph belongs. Throws if the paragraph is not in a list. Read-only. * * [Api set: WordApi 1.3] */ list: Word.List; /** * - * Gets the ListItem for the paragraph. Returns a null object if the paragraph is not part of a list. Read-only. + * Gets the ListItem for the paragraph. Throws if the paragraph is not part of a list. Read-only. * * [Api set: WordApi 1.3] */ listItem: Word.ListItem; + /** + * + * Gets the ListItem for the paragraph. Returns a null object if the paragraph is not part of a list. Read-only. + * + * [Api set: WordApi 1.3] + */ + listItemOrNullObject: Word.ListItem; + /** + * + * Gets the List to which this paragraph belongs. Returns a null object if the paragraph is not in a list. Read-only. + * + * [Api set: WordApi 1.3] + */ + listOrNullObject: Word.List; /** * * Gets the parent body of the paragraph. Read-only. @@ -12072,25 +12256,46 @@ declare module Word { parentBody: Word.Body; /** * - * Gets the content control that contains the paragraph. Returns a null object if there isn't a parent content control. Read-only. + * Gets the content control that contains the paragraph. Throws if there isn't a parent content control. Read-only. * * [Api set: WordApi 1.1] */ parentContentControl: Word.ContentControl; /** * - * Gets the table that contains the paragraph. Returns a null object if it is not contained in a table. Read-only. + * Gets the content control that contains the paragraph. Returns a null object if there isn't a parent content control. Read-only. + * + * [Api set: WordApi 1.3] + */ + parentContentControlOrNullObject: Word.ContentControl; + /** + * + * Gets the table that contains the paragraph. Throws if it is not contained in a table. Read-only. * * [Api set: WordApi 1.3] */ parentTable: Word.Table; /** * - * Gets the table cell that contains the paragraph. Returns a null object if it is not contained in a table cell. Read-only. + * Gets the table cell that contains the paragraph. Throws if it is not contained in a table cell. Read-only. * * [Api set: WordApi 1.3] */ parentTableCell: Word.TableCell; + /** + * + * Gets the table cell that contains the paragraph. Returns a null object if it is not contained in a table cell. Read-only. + * + * [Api set: WordApi 1.3] + */ + parentTableCellOrNullObject: Word.TableCell; + /** + * + * Gets the table that contains the paragraph. Returns a null object if it is not contained in a table. Read-only. + * + * [Api set: WordApi 1.3] + */ + parentTableOrNullObject: Word.Table; /** * * Gets or sets the alignment for a paragraph. The value can be 'left', 'centered', 'right', or 'justified'. @@ -12203,14 +12408,23 @@ declare module Word { * [Api set: WordApi 1.1] */ text: string; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.ParagraphUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: Paragraph): void; /** * * Lets the paragraph join an existing list at the specified level. Fails if the paragraph cannot join the list or if the paragraph is already a list item. * + * [Api set: WordApi 1.3] + * * @param listId Required. The ID of an existing list. * @param level Required. The level in the list. - * - * [Api set: WordApi 1.3] */ attachToList(listId: number, level: number): Word.List; /** @@ -12243,11 +12457,18 @@ declare module Word { getHtml(): OfficeExtension.ClientResult; /** * - * Gets the next paragraph. + * Gets the next paragraph. Throws if the paragraph is the last one. * * [Api set: WordApi 1.3] */ getNext(): Word.Paragraph; + /** + * + * Gets the next paragraph. Returns a null object if the paragraph is the last one. + * + * [Api set: WordApi 1.3] + */ + getNextOrNullObject(): Word.Paragraph; /** * * Gets the Office Open XML (OOXML) representation of the paragraph object. @@ -12257,38 +12478,45 @@ declare module Word { getOoxml(): OfficeExtension.ClientResult; /** * - * Gets the previous paragraph. + * Gets the previous paragraph. Throws if the paragraph is the first one. * * [Api set: WordApi 1.3] */ getPrevious(): Word.Paragraph; /** * - * Gets the whole paragraph, or the starting or ending point of the paragraph, as a range. - * - * @param rangeLocation Optional. The range location can be 'Whole', 'Start', 'End', 'After' or 'Content'. + * Gets the previous paragraph. Returns a null object if the paragraph is the first one. * * [Api set: WordApi 1.3] */ + getPreviousOrNullObject(): Word.Paragraph; + /** + * + * Gets the whole paragraph, or the starting or ending point of the paragraph, as a range. + * + * [Api set: WordApi 1.3] + * + * @param rangeLocation Optional. The range location can be 'Whole', 'Start', 'End', 'After' or 'Content'. + */ getRange(rangeLocation?: string): Word.Range; /** * * Gets the text ranges in the paragraph by using punctuation marks and/or other ending marks. * + * [Api set: WordApi 1.3] + * * @param endingMarks Required. The punctuation marks and/or other ending marks as an array of strings. * @param trimSpacing Optional. Indicates whether to trim spacing characters (spaces, tabs, column breaks and paragraph end marks) from the start and end of the ranges returned in the range collection. Default is false which indicates that spacing characters at the start and end of the ranges are included in the range collection. - * - * [Api set: WordApi 1.3] */ getTextRanges(endingMarks: Array, trimSpacing?: boolean): Word.RangeCollection; /** * * Inserts a break at the specified location in the main document. The insertLocation value can be 'Before' or 'After'. * + * [Api set: WordApi 1.1] + * * @param breakType Required. The break type to add to the document. * @param insertLocation Required. The value can be 'Before' or 'After'. - * - * [Api set: WordApi 1.1] */ insertBreak(breakType: string, insertLocation: string): void; /** @@ -12302,82 +12530,82 @@ declare module Word { * * Inserts a document into the paragraph at the specified location. The insertLocation value can be 'Replace', 'Start' or 'End'. * + * [Api set: WordApi 1.1] + * * @param base64File Required. The base64 encoded content of a .docx file. * @param insertLocation Required. The value can be 'Replace', 'Start' or 'End'. - * - * [Api set: WordApi 1.1] */ insertFileFromBase64(base64File: string, insertLocation: string): Word.Range; /** * * Inserts HTML into the paragraph at the specified location. The insertLocation value can be 'Replace', 'Start' or 'End'. * + * [Api set: WordApi 1.1] + * * @param html Required. The HTML to be inserted in the paragraph. * @param insertLocation Required. The value can be 'Replace', 'Start' or 'End'. - * - * [Api set: WordApi 1.1] */ insertHtml(html: string, insertLocation: string): Word.Range; /** * * Inserts a picture into the paragraph at the specified location. The insertLocation value can be 'Replace', 'Start' or 'End'. * + * [Api set: WordApi 1.1] + * * @param base64EncodedImage Required. The base64 encoded image to be inserted. * @param insertLocation Required. The value can be 'Replace', 'Start' or 'End'. - * - * [Api set: WordApi 1.1] */ insertInlinePictureFromBase64(base64EncodedImage: string, insertLocation: string): Word.InlinePicture; /** * * Inserts OOXML into the paragraph at the specified location. The insertLocation value can be 'Replace', 'Start' or 'End'. * + * [Api set: WordApi 1.1] + * * @param ooxml Required. The OOXML to be inserted in the paragraph. * @param insertLocation Required. The value can be 'Replace', 'Start' or 'End'. - * - * [Api set: WordApi 1.1] */ insertOoxml(ooxml: string, insertLocation: string): Word.Range; /** * * Inserts a paragraph at the specified location. The insertLocation value can be 'Before' or 'After'. * + * [Api set: WordApi 1.1] + * * @param paragraphText Required. The paragraph text to be inserted. * @param insertLocation Required. The value can be 'Before' or 'After'. - * - * [Api set: WordApi 1.1] */ insertParagraph(paragraphText: string, insertLocation: string): Word.Paragraph; /** * * Inserts a table with the specified number of rows and columns. The insertLocation value can be 'Before' or 'After'. * + * [Api set: WordApi 1.3] + * * @param rowCount Required. The number of rows in the table. * @param columnCount Required. The number of columns in the table. * @param insertLocation Required. The value can be 'Before' or 'After'. * @param values Optional 2D array. Cells are filled if the corresponding strings are specified in the array. - * - * [Api set: WordApi 1.3] */ insertTable(rowCount: number, columnCount: number, insertLocation: string, values?: Array>): Word.Table; /** * * Inserts text into the paragraph at the specified location. The insertLocation value can be 'Replace', 'Start' or 'End'. * + * [Api set: WordApi 1.1] + * * @param text Required. Text to be inserted. * @param insertLocation Required. The value can be 'Replace', 'Start' or 'End'. - * - * [Api set: WordApi 1.1] */ insertText(text: string, insertLocation: string): Word.Range; /** * * Performs a search with the specified searchOptions on the scope of the paragraph object. The search results are a collection of range objects. * + * [Api set: WordApi 1.1] + * * @param searchText Required. The search text. * @param searchOptions Optional. Options for the search. - * - * [Api set: WordApi 1.1] */ search(searchText: string, searchOptions?: Word.SearchOptions | { ignorePunct?: boolean; @@ -12392,20 +12620,20 @@ declare module Word { * * Selects and navigates the Word UI to the paragraph. * - * @param selectionMode Optional. The selection mode can be 'Select', 'Start' or 'End'. 'Select' is the default. - * * [Api set: WordApi 1.1] + * + * @param selectionMode Optional. The selection mode can be 'Select', 'Start' or 'End'. 'Select' is the default. */ select(selectionMode?: string): void; /** * * Splits the paragraph into child ranges by using delimiters. * + * [Api set: WordApi 1.3] + * * @param delimiters Required. The delimiters as an array of strings. * @param trimDelimiters Optional. Indicates whether to trim delimiters from the ranges in the range collection. Default is false which indicates that the delimiters are included in the ranges returned in the range collection. * @param trimSpacing Optional. Indicates whether to trim spacing characters (spaces, tabs, column breaks and paragraph end marks) from the start and end of the ranges returned in the range collection. Default is false which indicates that spacing characters at the start and end of the ranges are included in the range collection. - * - * [Api set: WordApi 1.3] */ split(delimiters: Array, trimDelimiters?: boolean, trimSpacing?: boolean): Word.RangeCollection; /** @@ -12424,7 +12652,7 @@ declare module Word { */ track(): Word.Paragraph; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.Paragraph; toJSON(): { @@ -12438,6 +12666,7 @@ declare module Word { "lineUnitAfter": number; "lineUnitBefore": number; "listItem": ListItem; + "listItemOrNullObject": ListItem; "outlineLevel": number; "rightIndent": number; "spaceAfter": number; @@ -12459,18 +12688,32 @@ declare module Word { items: Array; /** * - * Gets the first paragraph in this collection. + * Gets the first paragraph in this collection. Throws if the collection is empty. * * [Api set: WordApi 1.3] */ getFirst(): Word.Paragraph; /** * - * Gets the last paragraph in this collection. + * Gets the first paragraph in this collection. Returns a null object if the collection is empty. + * + * [Api set: WordApi 1.3] + */ + getFirstOrNullObject(): Word.Paragraph; + /** + * + * Gets the last paragraph in this collection. Throws if the collection is empty. * * [Api set: WordApi 1.3] */ getLast(): Word.Paragraph; + /** + * + * Gets the last paragraph in this collection. Returns a null object if the collection is empty. + * + * [Api set: WordApi 1.3] + */ + getLastOrNullObject(): Word.Paragraph; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -12480,7 +12723,7 @@ declare module Word { */ track(): Word.ParagraphCollection; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.ParagraphCollection; toJSON(): {}; @@ -12536,25 +12779,46 @@ declare module Word { parentBody: Word.Body; /** * - * Gets the content control that contains the range. Returns a null object if there isn't a parent content control. Read-only. + * Gets the content control that contains the range. Throws if there isn't a parent content control. Read-only. * * [Api set: WordApi 1.1] */ parentContentControl: Word.ContentControl; /** * - * Gets the table that contains the range. Returns null if it is not contained in a table. Read-only. + * Gets the content control that contains the range. Returns a null object if there isn't a parent content control. Read-only. + * + * [Api set: WordApi 1.3] + */ + parentContentControlOrNullObject: Word.ContentControl; + /** + * + * Gets the table that contains the range. Throws if it is not contained in a table. Read-only. * * [Api set: WordApi 1.3] */ parentTable: Word.Table; /** * - * Gets the table cell that contains the range. Returns a null object if it is not contained in a table cell. Read-only. + * Gets the table cell that contains the range. Throws if it is not contained in a table cell. Read-only. * * [Api set: WordApi 1.3] */ parentTableCell: Word.TableCell; + /** + * + * Gets the table cell that contains the range. Returns a null object if it is not contained in a table cell. Read-only. + * + * [Api set: WordApi 1.3] + */ + parentTableCellOrNullObject: Word.TableCell; + /** + * + * Gets the table that contains the range. Returns a null object if it is not contained in a table. Read-only. + * + * [Api set: WordApi 1.3] + */ + parentTableOrNullObject: Word.Table; /** * * Gets the collection of table objects in the range. Read-only. @@ -12564,7 +12828,7 @@ declare module Word { tables: Word.TableCollection; /** * - * Gets the first hyperlink in the range, or sets a hyperlink on the range. All hyperlinks in the range are deleted when you set a new hyperlink on the range. Use a newline character ('\n') to separate the address part from the optional location part. + * Gets the first hyperlink in the range, or sets a hyperlink on the range. All hyperlinks in the range are deleted when you set a new hyperlink on the range. Use a '#' to separate the address part from the optional location part. * * [Api set: WordApi 1.3] */ @@ -12597,6 +12861,15 @@ declare module Word { * [Api set: WordApi 1.1] */ text: string; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.RangeUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: Range): void; /** * * Clears the contents of the range object. The user can perform the undo operation on the cleared content. @@ -12608,9 +12881,9 @@ declare module Word { * * Compares this range's location with another range's location. * - * @param range Required. The range to compare with this range. - * * [Api set: WordApi 1.3] + * + * @param range Required. The range to compare with this range. */ compareLocationWith(range: Word.Range): OfficeExtension.ClientResult; /** @@ -12622,13 +12895,22 @@ declare module Word { delete(): void; /** * - * Returns a new range that extends from this range in either direction to cover another range. This range is not changed. - * - * @param range Required. Another range. + * Returns a new range that extends from this range in either direction to cover another range. This range is not changed. Throws if the two ranges do not have a union. * * [Api set: WordApi 1.3] + * + * @param range Required. Another range. */ expandTo(range: Word.Range): Word.Range; + /** + * + * Returns a new range that extends from this range in either direction to cover another range. This range is not changed. Returns a null object if the two ranges do not have a union. + * + * [Api set: WordApi 1.3] + * + * @param range Required. Another range. + */ + expandToOrNullObject(range: Word.Range): Word.Range; /** * * Gets the HTML representation of the range object. @@ -12645,14 +12927,24 @@ declare module Word { getHyperlinkRanges(): Word.RangeCollection; /** * - * Gets the next text range by using punctuation marks and/or other ending marks. + * Gets the next text range by using punctuation marks and/or other ending marks. Throws if this text range is the last one. + * + * [Api set: WordApi 1.3] * * @param endingMarks Required. The punctuation marks and/or other ending marks as an array of strings. * @param trimSpacing Optional. Indicates whether to trim spacing characters (spaces, tabs, column breaks and paragraph end marks) from the start and end of the returned range. Default is false which indicates that spacing characters at the start and end of the range are included. - * - * [Api set: WordApi 1.3] */ getNextTextRange(endingMarks: Array, trimSpacing?: boolean): Word.Range; + /** + * + * Gets the next text range by using punctuation marks and/or other ending marks. Returns a null object if this text range is the last one. + * + * [Api set: WordApi 1.3] + * + * @param endingMarks Required. The punctuation marks and/or other ending marks as an array of strings. + * @param trimSpacing Optional. Indicates whether to trim spacing characters (spaces, tabs, column breaks and paragraph end marks) from the start and end of the returned range. Default is false which indicates that spacing characters at the start and end of the range are included. + */ + getNextTextRangeOrNullObject(endingMarks: Array, trimSpacing?: boolean): Word.Range; /** * * Gets the OOXML representation of the range object. @@ -12664,29 +12956,29 @@ declare module Word { * * Clones the range, or gets the starting or ending point of the range as a new range. * - * @param rangeLocation Optional. The range location can be 'Whole', 'Start', 'End', 'After' or 'Content'. - * * [Api set: WordApi 1.3] + * + * @param rangeLocation Optional. The range location can be 'Whole', 'Start', 'End', 'After' or 'Content'. */ getRange(rangeLocation?: string): Word.Range; /** * * Gets the text child ranges in the range by using punctuation marks and/or other ending marks. * + * [Api set: WordApi 1.3] + * * @param endingMarks Required. The punctuation marks and/or other ending marks as an array of strings. * @param trimSpacing Optional. Indicates whether to trim spacing characters (spaces, tabs, column breaks and paragraph end marks) from the start and end of the ranges returned in the range collection. Default is false which indicates that spacing characters at the start and end of the ranges are included in the range collection. - * - * [Api set: WordApi 1.3] */ getTextRanges(endingMarks: Array, trimSpacing?: boolean): Word.RangeCollection; /** * * Inserts a break at the specified location in the main document. The insertLocation value can be 'Before' or 'After'. * + * [Api set: WordApi 1.1] + * * @param breakType Required. The break type to add. * @param insertLocation Required. The value can be 'Before' or 'After'. - * - * [Api set: WordApi 1.1] */ insertBreak(breakType: string, insertLocation: string): void; /** @@ -12700,91 +12992,100 @@ declare module Word { * * Inserts a document at the specified location. The insertLocation value can be 'Replace', 'Start', 'End', 'Before' or 'After'. * + * [Api set: WordApi 1.1] + * * @param base64File Required. The base64 encoded content of a .docx file. * @param insertLocation Required. The value can be 'Replace', 'Start', 'End', 'Before' or 'After'. - * - * [Api set: WordApi 1.1] */ insertFileFromBase64(base64File: string, insertLocation: string): Word.Range; /** * * Inserts HTML at the specified location. The insertLocation value can be 'Replace', 'Start', 'End', 'Before' or 'After'. * + * [Api set: WordApi 1.1] + * * @param html Required. The HTML to be inserted. * @param insertLocation Required. The value can be 'Replace', 'Start', 'End', 'Before' or 'After'. - * - * [Api set: WordApi 1.1] */ insertHtml(html: string, insertLocation: string): Word.Range; /** * * Inserts a picture at the specified location. The insertLocation value can be 'Replace', 'Start', 'End', 'Before' or 'After'. * + * [Api set: WordApi 1.2] + * * @param base64EncodedImage Required. The base64 encoded image to be inserted. * @param insertLocation Required. The value can be 'Replace', 'Start', 'End', 'Before' or 'After'. - * - * [Api set: WordApi 1.2] */ insertInlinePictureFromBase64(base64EncodedImage: string, insertLocation: string): Word.InlinePicture; /** * * Inserts OOXML at the specified location. The insertLocation value can be 'Replace', 'Start', 'End', 'Before' or 'After'. * + * [Api set: WordApi 1.1] + * * @param ooxml Required. The OOXML to be inserted. * @param insertLocation Required. The value can be 'Replace', 'Start', 'End', 'Before' or 'After'. - * - * [Api set: WordApi 1.1] */ insertOoxml(ooxml: string, insertLocation: string): Word.Range; /** * * Inserts a paragraph at the specified location. The insertLocation value can be 'Before' or 'After'. * + * [Api set: WordApi 1.1] + * * @param paragraphText Required. The paragraph text to be inserted. * @param insertLocation Required. The value can be 'Before' or 'After'. - * - * [Api set: WordApi 1.1] */ insertParagraph(paragraphText: string, insertLocation: string): Word.Paragraph; /** * * Inserts a table with the specified number of rows and columns. The insertLocation value can be 'Before' or 'After'. * + * [Api set: WordApi 1.3] + * * @param rowCount Required. The number of rows in the table. * @param columnCount Required. The number of columns in the table. * @param insertLocation Required. The value can be 'Before' or 'After'. * @param values Optional 2D array. Cells are filled if the corresponding strings are specified in the array. - * - * [Api set: WordApi 1.3] */ insertTable(rowCount: number, columnCount: number, insertLocation: string, values?: Array>): Word.Table; /** * * Inserts text at the specified location. The insertLocation value can be 'Replace', 'Start', 'End', 'Before' or 'After'. * + * [Api set: WordApi 1.1] + * * @param text Required. Text to be inserted. * @param insertLocation Required. The value can be 'Replace', 'Start', 'End', 'Before' or 'After'. - * - * [Api set: WordApi 1.1] */ insertText(text: string, insertLocation: string): Word.Range; /** * - * Returns a new range as the intersection of this range with another range. This range is not changed. - * - * @param range Required. Another range. + * Returns a new range as the intersection of this range with another range. This range is not changed. Throws if the two ranges are not overlapped or adjacent. * * [Api set: WordApi 1.3] + * + * @param range Required. Another range. */ intersectWith(range: Word.Range): Word.Range; + /** + * + * Returns a new range as the intersection of this range with another range. This range is not changed. Returns a null object if the two ranges are not overlapped or adjacent. + * + * [Api set: WordApi 1.3] + * + * @param range Required. Another range. + */ + intersectWithOrNullObject(range: Word.Range): Word.Range; /** * * Performs a search with the specified searchOptions on the scope of the range object. The search results are a collection of range objects. * + * [Api set: WordApi 1.1] + * * @param searchText Required. The search text. * @param searchOptions Optional. Options for the search. - * - * [Api set: WordApi 1.1] */ search(searchText: string, searchOptions?: Word.SearchOptions | { ignorePunct?: boolean; @@ -12799,21 +13100,21 @@ declare module Word { * * Selects and navigates the Word UI to the range. * - * @param selectionMode Optional. The selection mode can be 'Select', 'Start' or 'End'. 'Select' is the default. - * * [Api set: WordApi 1.1] + * + * @param selectionMode Optional. The selection mode can be 'Select', 'Start' or 'End'. 'Select' is the default. */ select(selectionMode?: string): void; /** * * Splits the range into child ranges by using delimiters. * + * [Api set: WordApi 1.3] + * * @param delimiters Required. The delimiters as an array of strings. * @param multiParagraphs Optional. Indicates whether a returned child range can cover multiple paragraphs. Default is false which indicates that the paragraph boundaries are also used as delimiters. * @param trimDelimiters Optional. Indicates whether to trim delimiters from the ranges in the range collection. Default is false which indicates that the delimiters are included in the ranges returned in the range collection. * @param trimSpacing Optional. Indicates whether to trim spacing characters (spaces, tabs, column breaks and paragraph end marks) from the start and end of the ranges returned in the range collection. Default is false which indicates that spacing characters at the start and end of the ranges are included in the range collection. - * - * [Api set: WordApi 1.3] */ split(delimiters: Array, multiParagraphs?: boolean, trimDelimiters?: boolean, trimSpacing?: boolean): Word.RangeCollection; /** @@ -12825,7 +13126,7 @@ declare module Word { */ track(): Word.Range; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.Range; toJSON(): { @@ -12841,18 +13142,25 @@ declare module Word { * * Contains a collection of [range](range.md) objects. * - * [Api set: WordApi 1.3] + * [Api set: WordApi 1.1] */ class RangeCollection extends OfficeExtension.ClientObject { /** Gets the loaded child items in this collection. */ items: Array; /** * - * Gets the first range in this collection. + * Gets the first range in this collection. Throws if this collection is empty. * * [Api set: WordApi 1.3] */ getFirst(): Word.Range; + /** + * + * Gets the first range in this collection. Returns a null object if this collection is empty. + * + * [Api set: WordApi 1.3] + */ + getFirstOrNullObject(): Word.Range; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -12862,7 +13170,7 @@ declare module Word { */ track(): Word.RangeCollection; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.RangeCollection; toJSON(): {}; @@ -12924,6 +13232,15 @@ declare module Word { * [Api set: WordApi 1.1] */ matchWildcards: boolean; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.SearchOptionsUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: SearchOptions): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -12956,45 +13273,47 @@ declare module Word { * [Api set: WordApi 1.1] */ body: Word.Body; - /** - * - * Gets or sets a value that indicates whether even-numbered pages have a different header and footer from odd-numbered pages in the section. - * - * [Api set: WordApi 1.3] - */ - headerFooterEvenPageDifferent: boolean; - /** - * - * Gets or sets a value that indicates whether the first page has a different header and footer from the other pages in the section. - * - * [Api set: WordApi 1.3] - */ - headerFooterFirstPageDifferent: boolean; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.SectionUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: Section): void; /** * * Gets one of the section's footers. * - * @param type Required. The type of footer to return. This value can be: 'primary', 'firstPage' or 'evenPages'. - * * [Api set: WordApi 1.1] + * + * @param type Required. The type of footer to return. This value can be: 'primary', 'firstPage' or 'evenPages'. */ getFooter(type: string): Word.Body; /** * * Gets one of the section's headers. * - * @param type Required. The type of header to return. This value can be: 'primary', 'firstPage' or 'evenPages'. - * * [Api set: WordApi 1.1] + * + * @param type Required. The type of header to return. This value can be: 'primary', 'firstPage' or 'evenPages'. */ getHeader(type: string): Word.Body; /** * - * Gets the next section. + * Gets the next section. Throws if this section is the last one. * * [Api set: WordApi 1.3] */ getNext(): Word.Section; + /** + * + * Gets the next section. Returns a null object if this section is the last one. + * + * [Api set: WordApi 1.3] + */ + getNextOrNullObject(): Word.Section; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -13004,13 +13323,11 @@ declare module Word { */ track(): Word.Section; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.Section; toJSON(): { "body": Body; - "headerFooterEvenPageDifferent": boolean; - "headerFooterFirstPageDifferent": boolean; }; } /** @@ -13024,11 +13341,18 @@ declare module Word { items: Array; /** * - * Gets the first section in this collection. + * Gets the first section in this collection. Throws if this collection is empty. * * [Api set: WordApi 1.3] */ getFirst(): Word.Section; + /** + * + * Gets the first section in this collection. Returns a null object if this collection is empty. + * + * [Api set: WordApi 1.3] + */ + getFirstOrNullObject(): Word.Section; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -13038,7 +13362,7 @@ declare module Word { */ track(): Word.SectionCollection; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.SectionCollection; toJSON(): {}; @@ -13057,20 +13381,6 @@ declare module Word { * [Api set: WordApi 1.3] */ font: Word.Font; - /** - * - * Gets the paragraph after the table. Read-only. - * - * [Api set: WordApi 1.3] - */ - paragraphAfter: Word.Paragraph; - /** - * - * Gets the paragraph before the table. Read-only. - * - * [Api set: WordApi 1.3] - */ - paragraphBefore: Word.Paragraph; /** * * Gets the parent body of the table. Read-only. @@ -13080,25 +13390,46 @@ declare module Word { parentBody: Word.Body; /** * - * Gets the content control that contains the table. Read-only. + * Gets the content control that contains the table. Throws if there isn't a parent content control. Read-only. * * [Api set: WordApi 1.3] */ parentContentControl: Word.ContentControl; /** * - * Gets the table that contains this table. Returns a null object if it is not contained in a table. Read-only. + * Gets the content control that contains the table. Returns a null object if there isn't a parent content control. Read-only. + * + * [Api set: WordApi 1.3] + */ + parentContentControlOrNullObject: Word.ContentControl; + /** + * + * Gets the table that contains this table. Throws if it is not contained in a table. Read-only. * * [Api set: WordApi 1.3] */ parentTable: Word.Table; /** * - * Gets the table cell that contains this table. Returns a null object if it is not contained in a table cell. Read-only. + * Gets the table cell that contains this table. Throws if it is not contained in a table cell. Read-only. * * [Api set: WordApi 1.3] */ parentTableCell: Word.TableCell; + /** + * + * Gets the table cell that contains this table. Returns a null object if it is not contained in a table cell. Read-only. + * + * [Api set: WordApi 1.3] + */ + parentTableCellOrNullObject: Word.TableCell; + /** + * + * Gets the table that contains this table. Returns a null object if it is not contained in a table. Read-only. + * + * [Api set: WordApi 1.3] + */ + parentTableOrNullObject: Word.Table; /** * * Gets all of the table rows. Read-only. @@ -13127,13 +13458,6 @@ declare module Word { * [Api set: WordApi 1.3] */ headerRowCount: number; - /** - * - * Gets the height of the table in points. Read-only. - * - * [Api set: WordApi 1.3] - */ - height: number; /** * * Gets and sets the horizontal alignment of every cell in the table. The value can be 'left', 'centered', 'right', or 'justified'. @@ -13239,35 +13563,37 @@ declare module Word { * [Api set: WordApi 1.3] */ width: number; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.TableUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: Table): void; /** * * Adds columns to the start or end of the table, using the first or last existing column as a template. This is applicable to uniform tables. The string values, if specified, are set in the newly inserted rows. * + * [Api set: WordApi 1.3] + * * @param insertLocation Required. It can be 'Start' or 'End', corresponding to the appropriate side of the table. * @param columnCount Required. Number of columns to add. * @param values Optional 2D array. Cells are filled if the corresponding strings are specified in the array. - * - * [Api set: WordApi 1.3] */ addColumns(insertLocation: string, columnCount: number, values?: Array>): void; /** * * Adds rows to the start or end of the table, using the first or last existing row as a template. The string values, if specified, are set in the newly inserted rows. * + * [Api set: WordApi 1.3] + * * @param insertLocation Required. It can be 'Start' or 'End'. * @param rowCount Required. Number of rows to add. * @param values Optional 2D array. Cells are filled if the corresponding strings are specified in the array. - * - * [Api set: WordApi 1.3] */ addRows(insertLocation: string, rowCount: number, values?: Array>): Word.TableRowCollection; - /** - * - * Autofits the table columns to the width of their contents. - * - * [Api set: WordApi 1.3] - */ - autoFitContents(): void; /** * * Autofits the table columns to the width of the window. @@ -13293,79 +13619,117 @@ declare module Word { * * Deletes specific columns. This is applicable to uniform tables. * + * [Api set: WordApi 1.3] + * * @param columnIndex Required. The first column to delete. * @param columnCount Optional. The number of columns to delete. Default 1. - * - * [Api set: WordApi 1.3] */ deleteColumns(columnIndex: number, columnCount?: number): void; /** * * Deletes specific rows. * + * [Api set: WordApi 1.3] + * * @param rowIndex Required. The first row to delete. * @param rowCount Optional. The number of rows to delete. Default 1. - * - * [Api set: WordApi 1.3] */ deleteRows(rowIndex: number, rowCount?: number): void; /** * - * Distributes the column widths evenly. + * Distributes the column widths evenly. This is applicable to uniform tables. * * [Api set: WordApi 1.3] */ distributeColumns(): void; - /** - * - * Distributes the row heights evenly. - * - * [Api set: WordApi 1.3] - */ - distributeRows(): void; /** * * Gets the border style for the specified border. * - * @param borderLocation Required. The border location. - * * [Api set: WordApi 1.3] + * + * @param borderLocation Required. The border location. */ getBorder(borderLocation: string): Word.TableBorder; /** * - * Gets the table cell at a specified row and column. + * Gets the table cell at a specified row and column. Throws if the specified table cell does not exist. + * + * [Api set: WordApi 1.3] * * @param rowIndex Required. The index of the row. * @param cellIndex Required. The index of the cell in the row. - * - * [Api set: WordApi 1.3] */ getCell(rowIndex: number, cellIndex: number): Word.TableCell; /** * - * Gets cell padding in points. - * - * @param cellPaddingLocation Required. The cell padding location can be 'Top', 'Left', 'Bottom' or 'Right'. + * Gets the table cell at a specified row and column. Returns a null object if the specified table cell does not exist. * * [Api set: WordApi 1.3] + * + * @param rowIndex Required. The index of the row. + * @param cellIndex Required. The index of the cell in the row. + */ + getCellOrNullObject(rowIndex: number, cellIndex: number): Word.TableCell; + /** + * + * Gets cell padding in points. + * + * [Api set: WordApi 1.3] + * + * @param cellPaddingLocation Required. The cell padding location can be 'Top', 'Left', 'Bottom' or 'Right'. */ getCellPadding(cellPaddingLocation: string): OfficeExtension.ClientResult; /** * - * Gets the next table. + * Gets the next table. Throws if this table is the last one. * * [Api set: WordApi 1.3] */ getNext(): Word.Table; /** * - * Gets the range that contains this table, or the range at the start or end of the table. - * - * @param rangeLocation Optional. The range location can be 'Whole', 'Start', 'End' or 'After'. + * Gets the next table. Returns a null object if this table is the last one. * * [Api set: WordApi 1.3] */ + getNextOrNullObject(): Word.Table; + /** + * + * Gets the paragraph after the table. Throws if there isn't a paragraph after the table. + * + * [Api set: WordApi 1.3] + */ + getParagraphAfter(): Word.Paragraph; + /** + * + * Gets the paragraph after the table. Returns a null object if there isn't a paragraph after the table. + * + * [Api set: WordApi 1.3] + */ + getParagraphAfterOrNullObject(): Word.Paragraph; + /** + * + * Gets the paragraph before the table. Throws if there isn't a paragraph before the table. + * + * [Api set: WordApi 1.3] + */ + getParagraphBefore(): Word.Paragraph; + /** + * + * Gets the paragraph before the table. Returns a null object if there isn't a paragraph before the table. + * + * [Api set: WordApi 1.3] + */ + getParagraphBeforeOrNullObject(): Word.Paragraph; + /** + * + * Gets the range that contains this table, or the range at the start or end of the table. + * + * [Api set: WordApi 1.3] + * + * @param rangeLocation Optional. The range location can be 'Whole', 'Start', 'End' or 'After'. + */ getRange(rangeLocation?: string): Word.Range; /** * @@ -13378,32 +13742,32 @@ declare module Word { * * Inserts a paragraph at the specified location. The insertLocation value can be 'Before' or 'After'. * + * [Api set: WordApi 1.3] + * * @param paragraphText Required. The paragraph text to be inserted. * @param insertLocation Required. The value can be 'Before' or 'After'. - * - * [Api set: WordApi 1.3] */ insertParagraph(paragraphText: string, insertLocation: string): Word.Paragraph; /** * * Inserts a table with the specified number of rows and columns. The insertLocation value can be 'Before' or 'After'. * + * [Api set: WordApi 1.3] + * * @param rowCount Required. The number of rows in the table. * @param columnCount Required. The number of columns in the table. * @param insertLocation Required. The value can be 'Before' or 'After'. * @param values Optional 2D array. Cells are filled if the corresponding strings are specified in the array. - * - * [Api set: WordApi 1.3] */ insertTable(rowCount: number, columnCount: number, insertLocation: string, values?: Array>): Word.Table; /** * * Performs a search with the specified searchOptions on the scope of the table object. The search results are a collection of range objects. * + * [Api set: WordApi 1.3] + * * @param searchText Required. The search text. * @param searchOptions Optional. Options for the search. - * - * [Api set: WordApi 1.3] */ search(searchText: string, searchOptions?: Word.SearchOptions | { ignorePunct?: boolean; @@ -13418,18 +13782,19 @@ declare module Word { * * Selects the table, or the position at the start or end of the table, and navigates the Word UI to it. * - * @param selectionMode Optional. The selection mode can be 'Select', 'Start' or 'End'. 'Select' is the default. - * * [Api set: WordApi 1.3] + * + * @param selectionMode Optional. The selection mode can be 'Select', 'Start' or 'End'. 'Select' is the default. */ select(selectionMode?: string): void; /** * * Sets cell padding in points. * - * @param cellPaddingLocation Required. The cell padding location can be 'Top', 'Left', 'Bottom' or 'Right'. - * * [Api set: WordApi 1.3] + * + * @param cellPaddingLocation Required. The cell padding location can be 'Top', 'Left', 'Bottom' or 'Right'. + * @param cellPadding Required. The cell padding. */ setCellPadding(cellPaddingLocation: string, cellPadding: number): void; /** @@ -13441,14 +13806,13 @@ declare module Word { */ track(): Word.Table; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.Table; toJSON(): { "alignment": string; "font": Font; "headerRowCount": number; - "height": number; "horizontalAlignment": string; "isUniform": boolean; "nestingLevel": number; @@ -13477,11 +13841,18 @@ declare module Word { items: Array; /** * - * Gets the first table in this collection. + * Gets the first table in this collection. Throws if this collection is empty. * * [Api set: WordApi 1.3] */ getFirst(): Word.Table; + /** + * + * Gets the first table in this collection. Returns a null object if this collection is empty. + * + * [Api set: WordApi 1.3] + */ + getFirstOrNullObject(): Word.Table; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -13491,7 +13862,7 @@ declare module Word { */ track(): Word.TableCollection; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.TableCollection; toJSON(): {}; @@ -13568,11 +13939,11 @@ declare module Word { shadingColor: string; /** * - * Gets and sets the text values in the row, as a 1D Javascript array. + * Gets and sets the text values in the row, as a 2D Javascript array. * * [Api set: WordApi 1.3] */ - values: Array; + values: Array>; /** * * Gets and sets the vertical alignment of the cells in the row. The value can be 'top', 'center' or 'bottom'. @@ -13580,6 +13951,15 @@ declare module Word { * [Api set: WordApi 1.3] */ verticalAlignment: string; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.TableRowUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: TableRow): void; /** * * Clears the contents of the row. @@ -13598,46 +13978,53 @@ declare module Word { * * Gets the border style of the cells in the row. * - * @param borderLocation Required. The border location. - * * [Api set: WordApi 1.3] + * + * @param borderLocation Required. The border location. */ getBorder(borderLocation: string): Word.TableBorder; /** * * Gets cell padding in points. * - * @param cellPaddingLocation Required. The cell padding location can be 'Top', 'Left', 'Bottom' or 'Right'. - * * [Api set: WordApi 1.3] + * + * @param cellPaddingLocation Required. The cell padding location can be 'Top', 'Left', 'Bottom' or 'Right'. */ getCellPadding(cellPaddingLocation: string): OfficeExtension.ClientResult; /** * - * Gets the next row. + * Gets the next row. Throws if this row is the last one. * * [Api set: WordApi 1.3] */ getNext(): Word.TableRow; + /** + * + * Gets the next row. Returns a null object if this row is the last one. + * + * [Api set: WordApi 1.3] + */ + getNextOrNullObject(): Word.TableRow; /** * * Inserts rows using this row as a template. If values are specified, inserts the values into the new rows. * + * [Api set: WordApi 1.3] + * * @param insertLocation Required. Where the new rows should be inserted, relative to the current row. It can be 'Before' or 'After'. * @param rowCount Required. Number of rows to add * @param values Optional. Strings to insert in the new rows, specified as a 2D array. The number of cells in each row must not exceed the number of cells in the existing row. - * - * [Api set: WordApi 1.3] */ insertRows(insertLocation: string, rowCount: number, values?: Array>): Word.TableRowCollection; /** * * Performs a search with the specified searchOptions on the scope of the row. The search results are a collection of range objects. * + * [Api set: WordApi 1.3] + * * @param searchText Required. The search text. * @param searchOptions Optional. Options for the search. - * - * [Api set: WordApi 1.3] */ search(searchText: string, searchOptions?: Word.SearchOptions | { ignorePunct?: boolean; @@ -13652,18 +14039,19 @@ declare module Word { * * Selects the row and navigates the Word UI to it. * - * @param selectionMode Optional. The selection mode can be 'Select', 'Start' or 'End'. 'Select' is the default. - * * [Api set: WordApi 1.3] + * + * @param selectionMode Optional. The selection mode can be 'Select', 'Start' or 'End'. 'Select' is the default. */ select(selectionMode?: string): void; /** * * Sets cell padding in points. * - * @param cellPaddingLocation Required. The cell padding location can be 'Top', 'Left', 'Bottom' or 'Right'. - * * [Api set: WordApi 1.3] + * + * @param cellPaddingLocation Required. The cell padding location can be 'Top', 'Left', 'Bottom' or 'Right'. + * @param cellPadding Required. The cell padding. */ setCellPadding(cellPaddingLocation: string, cellPadding: number): void; /** @@ -13675,7 +14063,7 @@ declare module Word { */ track(): Word.TableRow; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.TableRow; toJSON(): { @@ -13686,7 +14074,7 @@ declare module Word { "preferredHeight": number; "rowIndex": number; "shadingColor": string; - "values": string[]; + "values": string[][]; "verticalAlignment": string; }; } @@ -13701,11 +14089,18 @@ declare module Word { items: Array; /** * - * Gets the first row in this collection. + * Gets the first row in this collection. Throws if this collection is empty. * * [Api set: WordApi 1.3] */ getFirst(): Word.TableRow; + /** + * + * Gets the first row in this collection. Returns a null object if this collection is empty. + * + * [Api set: WordApi 1.3] + */ + getFirstOrNullObject(): Word.TableRow; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -13715,7 +14110,7 @@ declare module Word { */ track(): Word.TableRowCollection; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.TableRowCollection; toJSON(): {}; @@ -13804,6 +14199,15 @@ declare module Word { * [Api set: WordApi 1.3] */ width: number; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.TableCellUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: TableCell): void; /** * * Deletes the column containing this cell. This is applicable to uniform tables. @@ -13822,56 +14226,64 @@ declare module Word { * * Gets the border style for the specified border. * - * @param borderLocation Required. The border location. - * * [Api set: WordApi 1.3] + * + * @param borderLocation Required. The border location. */ getBorder(borderLocation: string): Word.TableBorder; /** * * Gets cell padding in points. * - * @param cellPaddingLocation Required. The cell padding location can be 'Top', 'Left', 'Bottom' or 'Right'. - * * [Api set: WordApi 1.3] + * + * @param cellPaddingLocation Required. The cell padding location can be 'Top', 'Left', 'Bottom' or 'Right'. */ getCellPadding(cellPaddingLocation: string): OfficeExtension.ClientResult; /** * - * Gets the next cell. + * Gets the next cell. Throws if this cell is the last one. * * [Api set: WordApi 1.3] */ getNext(): Word.TableCell; + /** + * + * Gets the next cell. Returns a null object if this cell is the last one. + * + * [Api set: WordApi 1.3] + */ + getNextOrNullObject(): Word.TableCell; /** * * Adds columns to the left or right of the cell, using the cell's column as a template. This is applicable to uniform tables. The string values, if specified, are set in the newly inserted rows. * + * [Api set: WordApi 1.3] + * * @param insertLocation Required. It can be 'Before' or 'After'. * @param columnCount Required. Number of columns to add * @param values Optional 2D array. Cells are filled if the corresponding strings are specified in the array. - * - * [Api set: WordApi 1.3] */ insertColumns(insertLocation: string, columnCount: number, values?: Array>): void; /** * * Inserts rows above or below the cell, using the cell's row as a template. The string values, if specified, are set in the newly inserted rows. * + * [Api set: WordApi 1.3] + * * @param insertLocation Required. It can be 'Before' or 'After'. * @param rowCount Required. Number of rows to add. * @param values Optional 2D array. Cells are filled if the corresponding strings are specified in the array. - * - * [Api set: WordApi 1.3] */ insertRows(insertLocation: string, rowCount: number, values?: Array>): Word.TableRowCollection; /** * * Sets cell padding in points. * - * @param cellPaddingLocation Required. The cell padding location can be 'Top', 'Left', 'Bottom' or 'Right'. - * * [Api set: WordApi 1.3] + * + * @param cellPaddingLocation Required. The cell padding location can be 'Top', 'Left', 'Bottom' or 'Right'. + * @param cellPadding Required. The cell padding. */ setCellPadding(cellPaddingLocation: string, cellPadding: number): void; /** @@ -13883,7 +14295,7 @@ declare module Word { */ track(): Word.TableCell; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.TableCell; toJSON(): { @@ -13909,11 +14321,18 @@ declare module Word { items: Array; /** * - * Gets the first table cell in this collection. + * Gets the first table cell in this collection. Throws if this collection is empty. * * [Api set: WordApi 1.3] */ getFirst(): Word.TableCell; + /** + * + * Gets the first table cell in this collection. Returns a null object if this collection is empty. + * + * [Api set: WordApi 1.3] + */ + getFirstOrNullObject(): Word.TableCell; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -13923,7 +14342,7 @@ declare module Word { */ track(): Word.TableCellCollection; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.TableCellCollection; toJSON(): {}; @@ -13956,6 +14375,15 @@ declare module Word { * [Api set: WordApi 1.3] */ width: number; + /** Sets multiple properties on the object at the same time, based on JSON input. */ + set(properties: Interfaces.TableBorderUpdateData, options?: { + /** + * Throw an error if the passed-in property list includes read-only properties (default = true). + */ + throwOnReadOnly?: boolean; + }): void; + /** Sets multiple properties on the object at the same time, based on an existing loaded object. */ + set(properties: TableBorder): void; /** * Queues up a command to load the specified properties of the object. You must call "context.sync()" before reading the properties. */ @@ -13965,7 +14393,7 @@ declare module Word { */ track(): Word.TableBorder; /** - * Release the memory associated with this object, if has previous been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. + * Release the memory associated with this object, if it has previously been tracked. This call is shorthand for context.trackedObjects.remove(thisObject). Having many tracked objects slows down the host application, so please remember to free any objects you add, once you're done using them. You will need to call "context.sync()" before the memory release takes effect. */ untrack(): Word.TableBorder; toJSON(): { @@ -13980,7 +14408,7 @@ declare module Word { * * [Api set: WordApi] */ - module ContentControlType { + namespace ContentControlType { var unknown: string; var richTextInline: string; var richTextParagraphs: string; @@ -14005,7 +14433,7 @@ declare module Word { * * [Api set: WordApi] */ - module ContentControlAppearance { + namespace ContentControlAppearance { var boundingBox: string; var tags: string; var hidden: string; @@ -14016,7 +14444,7 @@ declare module Word { * * [Api set: WordApi] */ - module UnderlineType { + namespace UnderlineType { var mixed: string; var none: string; /** @@ -14053,7 +14481,7 @@ declare module Word { * * [Api set: WordApi] */ - module BreakType { + namespace BreakType { /** * * Page break. @@ -14102,7 +14530,7 @@ declare module Word { * * [Api set: WordApi] */ - module InsertLocation { + namespace InsertLocation { var before: string; var after: string; var start: string; @@ -14112,7 +14540,7 @@ declare module Word { /** * [Api set: WordApi] */ - module Alignment { + namespace Alignment { var mixed: string; var unknown: string; var left: string; @@ -14123,7 +14551,7 @@ declare module Word { /** * [Api set: WordApi] */ - module HeaderFooterType { + namespace HeaderFooterType { var primary: string; var firstPage: string; var evenPages: string; @@ -14131,7 +14559,7 @@ declare module Word { /** * [Api set: WordApi] */ - module BodyType { + namespace BodyType { var unknown: string; var mainDoc: string; var section: string; @@ -14142,7 +14570,7 @@ declare module Word { /** * [Api set: WordApi] */ - module SelectionMode { + namespace SelectionMode { var select: string; var start: string; var end: string; @@ -14150,7 +14578,7 @@ declare module Word { /** * [Api set: WordApi] */ - module ImageFormat { + namespace ImageFormat { var unsupported: string; var undefined: string; var bmp: string; @@ -14169,7 +14597,7 @@ declare module Word { /** * [Api set: WordApi] */ - module RangeLocation { + namespace RangeLocation { var whole: string; var start: string; var end: string; @@ -14180,7 +14608,7 @@ declare module Word { /** * [Api set: WordApi] */ - module LocationRelation { + namespace LocationRelation { var unrelated: string; var equal: string; var containsStart: string; @@ -14199,7 +14627,7 @@ declare module Word { /** * [Api set: WordApi] */ - module BorderLocation { + namespace BorderLocation { var top: string; var left: string; var bottom: string; @@ -14213,7 +14641,7 @@ declare module Word { /** * [Api set: WordApi] */ - module CellPaddingLocation { + namespace CellPaddingLocation { var top: string; var left: string; var bottom: string; @@ -14222,7 +14650,7 @@ declare module Word { /** * [Api set: WordApi] */ - module BorderType { + namespace BorderType { var mixed: string; var none: string; var single: string; @@ -14251,7 +14679,7 @@ declare module Word { /** * [Api set: WordApi] */ - module VerticalAlignment { + namespace VerticalAlignment { var mixed: string; var top: string; var center: string; @@ -14260,7 +14688,7 @@ declare module Word { /** * [Api set: WordApi] */ - module ListLevelType { + namespace ListLevelType { var bullet: string; var number: string; var picture: string; @@ -14268,7 +14696,7 @@ declare module Word { /** * [Api set: WordApi] */ - module ListBullet { + namespace ListBullet { var custom: string; var solid: string; var hollow: string; @@ -14280,7 +14708,7 @@ declare module Word { /** * [Api set: WordApi] */ - module ListNumbering { + namespace ListNumbering { var none: string; var arabic: string; var upperRoman: string; @@ -14291,7 +14719,7 @@ declare module Word { /** * [Api set: WordApi] */ - module Style { + namespace Style { /** * * Mixed styles or other style not in this list. @@ -14504,19 +14932,776 @@ declare module Word { /** * [Api set: WordApi] */ - module DocumentPropertyType { + namespace DocumentPropertyType { var string: string; var number: string; var date: string; var boolean: string; } - module ErrorCodes { + namespace ErrorCodes { var accessDenied: string; var generalException: string; var invalidArgument: string; var itemNotFound: string; var notImplemented: string; } + module Interfaces { + /** An interface for updating data on the Body object, for use in "body.set({ ... })". */ + interface BodyUpdateData { + /** + * + * Gets the text format of the body. Use this to get and set font name, size, color and other properties. + * + * [Api set: WordApi 1.1] + */ + font?: Word.Interfaces.FontUpdateData; + /** + * + * Gets or sets the style name for the body. Use this property for custom styles and localized style names. To use the built-in styles that are portable between locales, see the "styleBuiltIn" property. + * + * [Api set: WordApi 1.1] + */ + style?: string; + /** + * + * Gets or sets the built-in style name for the body. Use this property for built-in styles that are portable between locales. To use custom styles or localized style names, see the "style" property. + * + * [Api set: WordApi 1.3] + */ + styleBuiltIn?: string; + } + /** An interface for updating data on the ContentControl object, for use in "contentControl.set({ ... })". */ + interface ContentControlUpdateData { + /** + * + * Gets the text format of the content control. Use this to get and set font name, size, color, and other properties. + * + * [Api set: WordApi 1.1] + */ + font?: Word.Interfaces.FontUpdateData; + /** + * + * Gets or sets the appearance of the content control. The value can be 'boundingBox', 'tags' or 'hidden'. + * + * [Api set: WordApi 1.1] + */ + appearance?: string; + /** + * + * Gets or sets a value that indicates whether the user can delete the content control. Mutually exclusive with removeWhenEdited. + * + * [Api set: WordApi 1.1] + */ + cannotDelete?: boolean; + /** + * + * Gets or sets a value that indicates whether the user can edit the contents of the content control. + * + * [Api set: WordApi 1.1] + */ + cannotEdit?: boolean; + /** + * + * Gets or sets the color of the content control. Color is specified in '#RRGGBB' format or by using the color name. + * + * [Api set: WordApi 1.1] + */ + color?: string; + /** + * + * Gets or sets the placeholder text of the content control. Dimmed text will be displayed when the content control is empty. + * + * [Api set: WordApi 1.1] + */ + placeholderText?: string; + /** + * + * Gets or sets a value that indicates whether the content control is removed after it is edited. Mutually exclusive with cannotDelete. + * + * [Api set: WordApi 1.1] + */ + removeWhenEdited?: boolean; + /** + * + * Gets or sets the style name for the content control. Use this property for custom styles and localized style names. To use the built-in styles that are portable between locales, see the "styleBuiltIn" property. + * + * [Api set: WordApi 1.1] + */ + style?: string; + /** + * + * Gets or sets the built-in style name for the content control. Use this property for built-in styles that are portable between locales. To use custom styles or localized style names, see the "style" property. + * + * [Api set: WordApi 1.3] + */ + styleBuiltIn?: string; + /** + * + * Gets or sets a tag to identify a content control. + * + * [Api set: WordApi 1.1] + */ + tag?: string; + /** + * + * Gets or sets the title for a content control. + * + * [Api set: WordApi 1.1] + */ + title?: string; + } + /** An interface for updating data on the CustomProperty object, for use in "customProperty.set({ ... })". */ + interface CustomPropertyUpdateData { + /** + * + * Gets or sets the value of the custom property. + * + * [Api set: WordApi 1.3] + */ + value?: any; + } + /** An interface for updating data on the Document object, for use in "document.set({ ... })". */ + interface DocumentUpdateData { + /** + * + * Gets the body object of the document. The body is the text that excludes headers, footers, footnotes, textboxes, etc.. + * + * [Api set: WordApi 1.1] + */ + body?: Word.Interfaces.BodyUpdateData; + /** + * + * Gets the properties of the current document. + * + * [Api set: WordApi 1.3] + */ + properties?: Word.Interfaces.DocumentPropertiesUpdateData; + } + /** An interface for updating data on the DocumentProperties object, for use in "documentProperties.set({ ... })". */ + interface DocumentPropertiesUpdateData { + /** + * + * Gets or sets the author of the document. + * + * [Api set: WordApi 1.3] + */ + author?: string; + /** + * + * Gets or sets the category of the document. + * + * [Api set: WordApi 1.3] + */ + category?: string; + /** + * + * Gets or sets the comments of the document. + * + * [Api set: WordApi 1.3] + */ + comments?: string; + /** + * + * Gets or sets the company of the document. + * + * [Api set: WordApi 1.3] + */ + company?: string; + /** + * + * Gets or sets the format of the document. + * + * [Api set: WordApi 1.3] + */ + format?: string; + /** + * + * Gets or sets the keywords of the document. + * + * [Api set: WordApi 1.3] + */ + keywords?: string; + /** + * + * Gets or sets the manager of the document. + * + * [Api set: WordApi 1.3] + */ + manager?: string; + /** + * + * Gets or sets the subject of the document. + * + * [Api set: WordApi 1.3] + */ + subject?: string; + /** + * + * Gets or sets the title of the document. + * + * [Api set: WordApi 1.3] + */ + title?: string; + } + /** An interface for updating data on the Font object, for use in "font.set({ ... })". */ + interface FontUpdateData { + /** + * + * Gets or sets a value that indicates whether the font is bold. True if the font is formatted as bold, otherwise, false. + * + * [Api set: WordApi 1.1] + */ + bold?: boolean; + /** + * + * Gets or sets the color for the specified font. You can provide the value in the '#RRGGBB' format or the color name. + * + * [Api set: WordApi 1.1] + */ + color?: string; + /** + * + * Gets or sets a value that indicates whether the font has a double strike through. True if the font is formatted as double strikethrough text, otherwise, false. + * + * [Api set: WordApi 1.1] + */ + doubleStrikeThrough?: boolean; + /** + * + * Gets or sets the highlight color. To set it, use a value either in the '#RRGGBB' format or the color name. To remove highlight color, set it to null. The returned highlight color can be in the '#RRGGBB' format, or an empty string for mixed highlight colors, or null for no highlight color. + * + * [Api set: WordApi 1.1] + */ + highlightColor?: string; + /** + * + * Gets or sets a value that indicates whether the font is italicized. True if the font is italicized, otherwise, false. + * + * [Api set: WordApi 1.1] + */ + italic?: boolean; + /** + * + * Gets or sets a value that represents the name of the font. + * + * [Api set: WordApi 1.1] + */ + name?: string; + /** + * + * Gets or sets a value that represents the font size in points. + * + * [Api set: WordApi 1.1] + */ + size?: number; + /** + * + * Gets or sets a value that indicates whether the font has a strike through. True if the font is formatted as strikethrough text, otherwise, false. + * + * [Api set: WordApi 1.1] + */ + strikeThrough?: boolean; + /** + * + * Gets or sets a value that indicates whether the font is a subscript. True if the font is formatted as subscript, otherwise, false. + * + * [Api set: WordApi 1.1] + */ + subscript?: boolean; + /** + * + * Gets or sets a value that indicates whether the font is a superscript. True if the font is formatted as superscript, otherwise, false. + * + * [Api set: WordApi 1.1] + */ + superscript?: boolean; + /** + * + * Gets or sets a value that indicates the font's underline type. 'None' if the font is not underlined. + * + * [Api set: WordApi 1.1] + */ + underline?: string; + } + /** An interface for updating data on the InlinePicture object, for use in "inlinePicture.set({ ... })". */ + interface InlinePictureUpdateData { + /** + * + * Gets or sets a string that represents the alternative text associated with the inline image + * + * [Api set: WordApi 1.1] + */ + altTextDescription?: string; + /** + * + * Gets or sets a string that contains the title for the inline image. + * + * [Api set: WordApi 1.1] + */ + altTextTitle?: string; + /** + * + * Gets or sets a number that describes the height of the inline image. + * + * [Api set: WordApi 1.1] + */ + height?: number; + /** + * + * Gets or sets a hyperlink on the image. Use a '#' to separate the address part from the optional location part. + * + * [Api set: WordApi 1.1] + */ + hyperlink?: string; + /** + * + * Gets or sets a value that indicates whether the inline image retains its original proportions when you resize it. + * + * [Api set: WordApi 1.1] + */ + lockAspectRatio?: boolean; + /** + * + * Gets or sets a number that describes the width of the inline image. + * + * [Api set: WordApi 1.1] + */ + width?: number; + } + /** An interface for updating data on the ListItem object, for use in "listItem.set({ ... })". */ + interface ListItemUpdateData { + /** + * + * Gets or sets the level of the item in the list. + * + * [Api set: WordApi 1.3] + */ + level?: number; + } + /** An interface for updating data on the Paragraph object, for use in "paragraph.set({ ... })". */ + interface ParagraphUpdateData { + /** + * + * Gets the text format of the paragraph. Use this to get and set font name, size, color, and other properties. + * + * [Api set: WordApi 1.1] + */ + font?: Word.Interfaces.FontUpdateData; + /** + * + * Gets the ListItem for the paragraph. Throws if the paragraph is not part of a list. + * + * [Api set: WordApi 1.3] + */ + listItem?: Word.Interfaces.ListItemUpdateData; + /** + * + * Gets the ListItem for the paragraph. Returns a null object if the paragraph is not part of a list. + * + * [Api set: WordApi 1.3] + */ + listItemOrNullObject?: Word.Interfaces.ListItemUpdateData; + /** + * + * Gets or sets the alignment for a paragraph. The value can be 'left', 'centered', 'right', or 'justified'. + * + * [Api set: WordApi 1.1] + */ + alignment?: string; + /** + * + * Gets or sets the value, in points, for a first line or hanging indent. Use a positive value to set a first-line indent, and use a negative value to set a hanging indent. + * + * [Api set: WordApi 1.1] + */ + firstLineIndent?: number; + /** + * + * Gets or sets the left indent value, in points, for the paragraph. + * + * [Api set: WordApi 1.1] + */ + leftIndent?: number; + /** + * + * Gets or sets the line spacing, in points, for the specified paragraph. In the Word UI, this value is divided by 12. + * + * [Api set: WordApi 1.1] + */ + lineSpacing?: number; + /** + * + * Gets or sets the amount of spacing, in grid lines. after the paragraph. + * + * [Api set: WordApi 1.1] + */ + lineUnitAfter?: number; + /** + * + * Gets or sets the amount of spacing, in grid lines, before the paragraph. + * + * [Api set: WordApi 1.1] + */ + lineUnitBefore?: number; + /** + * + * Gets or sets the outline level for the paragraph. + * + * [Api set: WordApi 1.1] + */ + outlineLevel?: number; + /** + * + * Gets or sets the right indent value, in points, for the paragraph. + * + * [Api set: WordApi 1.1] + */ + rightIndent?: number; + /** + * + * Gets or sets the spacing, in points, after the paragraph. + * + * [Api set: WordApi 1.1] + */ + spaceAfter?: number; + /** + * + * Gets or sets the spacing, in points, before the paragraph. + * + * [Api set: WordApi 1.1] + */ + spaceBefore?: number; + /** + * + * Gets or sets the style name for the paragraph. Use this property for custom styles and localized style names. To use the built-in styles that are portable between locales, see the "styleBuiltIn" property. + * + * [Api set: WordApi 1.1] + */ + style?: string; + /** + * + * Gets or sets the built-in style name for the paragraph. Use this property for built-in styles that are portable between locales. To use custom styles or localized style names, see the "style" property. + * + * [Api set: WordApi 1.3] + */ + styleBuiltIn?: string; + } + /** An interface for updating data on the Range object, for use in "range.set({ ... })". */ + interface RangeUpdateData { + /** + * + * Gets the text format of the range. Use this to get and set font name, size, color, and other properties. + * + * [Api set: WordApi 1.1] + */ + font?: Word.Interfaces.FontUpdateData; + /** + * + * Gets the first hyperlink in the range, or sets a hyperlink on the range. All hyperlinks in the range are deleted when you set a new hyperlink on the range. Use a '#' to separate the address part from the optional location part. + * + * [Api set: WordApi 1.3] + */ + hyperlink?: string; + /** + * + * Gets or sets the style name for the range. Use this property for custom styles and localized style names. To use the built-in styles that are portable between locales, see the "styleBuiltIn" property. + * + * [Api set: WordApi 1.1] + */ + style?: string; + /** + * + * Gets or sets the built-in style name for the range. Use this property for built-in styles that are portable between locales. To use custom styles or localized style names, see the "style" property. + * + * [Api set: WordApi 1.3] + */ + styleBuiltIn?: string; + } + /** An interface for updating data on the SearchOptions object, for use in "searchOptions.set({ ... })". */ + interface SearchOptionsUpdateData { + /** + * + * Gets or sets a value that indicates whether to ignore all punctuation characters between words. Corresponds to the Ignore punctuation check box in the Find and Replace dialog box. + * + * [Api set: WordApi 1.1] + */ + ignorePunct?: boolean; + /** + * + * Gets or sets a value that indicates whether to ignore all whitespace between words. Corresponds to the Ignore whitespace characters check box in the Find and Replace dialog box. + * + * [Api set: WordApi 1.1] + */ + ignoreSpace?: boolean; + /** + * + * Gets or sets a value that indicates whether to perform a case sensitive search. Corresponds to the Match case check box in the Find and Replace dialog box (Edit menu). + * + * [Api set: WordApi 1.1] + */ + matchCase?: boolean; + /** + * + * Gets or sets a value that indicates whether to match words that begin with the search string. Corresponds to the Match prefix check box in the Find and Replace dialog box. + * + * [Api set: WordApi 1.1] + */ + matchPrefix?: boolean; + /** + * + * Gets or sets a value that indicates whether to match words that end with the search string. Corresponds to the Match suffix check box in the Find and Replace dialog box. + * + * [Api set: WordApi 1.1] + */ + matchSuffix?: boolean; + /** + * + * Gets or sets a value that indicates whether to find operation only entire words, not text that is part of a larger word. Corresponds to the Find whole words only check box in the Find and Replace dialog box. + * + * [Api set: WordApi 1.1] + */ + matchWholeWord?: boolean; + /** + * + * Gets or sets a value that indicates whether the search will be performed using special search operators. Corresponds to the Use wildcards check box in the Find and Replace dialog box. + * + * [Api set: WordApi 1.1] + */ + matchWildcards?: boolean; + } + /** An interface for updating data on the Section object, for use in "section.set({ ... })". */ + interface SectionUpdateData { + /** + * + * Gets the body object of the section. This does not include the header/footer and other section metadata. + * + * [Api set: WordApi 1.1] + */ + body?: Word.Interfaces.BodyUpdateData; + } + /** An interface for updating data on the Table object, for use in "table.set({ ... })". */ + interface TableUpdateData { + /** + * + * Gets the font. Use this to get and set font name, size, color, and other properties. + * + * [Api set: WordApi 1.3] + */ + font?: Word.Interfaces.FontUpdateData; + /** + * + * Gets or sets the alignment of the table against the page column. The value can be 'left', 'centered' or 'right'. + * + * [Api set: WordApi 1.3] + */ + alignment?: string; + /** + * + * Gets and sets the number of header rows. + * + * [Api set: WordApi 1.3] + */ + headerRowCount?: number; + /** + * + * Gets and sets the horizontal alignment of every cell in the table. The value can be 'left', 'centered', 'right', or 'justified'. + * + * [Api set: WordApi 1.3] + */ + horizontalAlignment?: string; + /** + * + * Gets and sets the shading color. + * + * [Api set: WordApi 1.3] + */ + shadingColor?: string; + /** + * + * Gets or sets the style name for the table. Use this property for custom styles and localized style names. To use the built-in styles that are portable between locales, see the "styleBuiltIn" property. + * + * [Api set: WordApi 1.3] + */ + style?: string; + /** + * + * Gets and sets whether the table has banded columns. + * + * [Api set: WordApi 1.3] + */ + styleBandedColumns?: boolean; + /** + * + * Gets and sets whether the table has banded rows. + * + * [Api set: WordApi 1.3] + */ + styleBandedRows?: boolean; + /** + * + * Gets or sets the built-in style name for the table. Use this property for built-in styles that are portable between locales. To use custom styles or localized style names, see the "style" property. + * + * [Api set: WordApi 1.3] + */ + styleBuiltIn?: string; + /** + * + * Gets and sets whether the table has a first column with a special style. + * + * [Api set: WordApi 1.3] + */ + styleFirstColumn?: boolean; + /** + * + * Gets and sets whether the table has a last column with a special style. + * + * [Api set: WordApi 1.3] + */ + styleLastColumn?: boolean; + /** + * + * Gets and sets whether the table has a total (last) row with a special style. + * + * [Api set: WordApi 1.3] + */ + styleTotalRow?: boolean; + /** + * + * Gets and sets the text values in the table, as a 2D Javascript array. + * + * [Api set: WordApi 1.3] + */ + values?: Array>; + /** + * + * Gets and sets the vertical alignment of every cell in the table. The value can be 'top', 'center' or 'bottom'. + * + * [Api set: WordApi 1.3] + */ + verticalAlignment?: string; + /** + * + * Gets and sets the width of the table in points. + * + * [Api set: WordApi 1.3] + */ + width?: number; + } + /** An interface for updating data on the TableRow object, for use in "tableRow.set({ ... })". */ + interface TableRowUpdateData { + /** + * + * Gets the font. Use this to get and set font name, size, color, and other properties. + * + * [Api set: WordApi 1.3] + */ + font?: Word.Interfaces.FontUpdateData; + /** + * + * Gets and sets the horizontal alignment of every cell in the row. The value can be 'left', 'centered', 'right', or 'justified'. + * + * [Api set: WordApi 1.3] + */ + horizontalAlignment?: string; + /** + * + * Gets and sets the preferred height of the row in points. + * + * [Api set: WordApi 1.3] + */ + preferredHeight?: number; + /** + * + * Gets and sets the shading color. + * + * [Api set: WordApi 1.3] + */ + shadingColor?: string; + /** + * + * Gets and sets the text values in the row, as a 2D Javascript array. + * + * [Api set: WordApi 1.3] + */ + values?: Array>; + /** + * + * Gets and sets the vertical alignment of the cells in the row. The value can be 'top', 'center' or 'bottom'. + * + * [Api set: WordApi 1.3] + */ + verticalAlignment?: string; + } + /** An interface for updating data on the TableCell object, for use in "tableCell.set({ ... })". */ + interface TableCellUpdateData { + /** + * + * Gets the body object of the cell. + * + * [Api set: WordApi 1.3] + */ + body?: Word.Interfaces.BodyUpdateData; + /** + * + * Gets and sets the width of the cell's column in points. This is applicable to uniform tables. + * + * [Api set: WordApi 1.3] + */ + columnWidth?: number; + /** + * + * Gets and sets the horizontal alignment of the cell. The value can be 'left', 'centered', 'right', or 'justified'. + * + * [Api set: WordApi 1.3] + */ + horizontalAlignment?: string; + /** + * + * Gets or sets the shading color of the cell. Color is specified in "#RRGGBB" format or by using the color name. + * + * [Api set: WordApi 1.3] + */ + shadingColor?: string; + /** + * + * Gets and sets the text of the cell. + * + * [Api set: WordApi 1.3] + */ + value?: string; + /** + * + * Gets and sets the vertical alignment of the cell. The value can be 'top', 'center' or 'bottom'. + * + * [Api set: WordApi 1.3] + */ + verticalAlignment?: string; + } + /** An interface for updating data on the TableBorder object, for use in "tableBorder.set({ ... })". */ + interface TableBorderUpdateData { + /** + * + * Gets or sets the table border color, as a hex value or name. + * + * [Api set: WordApi 1.3] + */ + color?: string; + /** + * + * Gets or sets the type of the table border. + * + * [Api set: WordApi 1.3] + */ + type?: string; + /** + * + * Gets or sets the width, in points, of the table border. Not applicable to table border types that have fixed widths. + * + * [Api set: WordApi 1.3] + */ + width?: number; + } + } } declare module Word { /** @@ -14525,7 +15710,6 @@ declare module Word { class RequestContext extends OfficeExtension.ClientRequestContext { constructor(url?: string); document: Document; - application: Application; } /** * Executes a batch script that performs actions on the Word object model, using a new RequestContext. When the promise is resolved, any tracked objects that were automatically allocated during execution will be released. diff --git a/parse-unit/index.d.ts b/parse-unit/index.d.ts new file mode 100644 index 0000000000..238f3cfc06 --- /dev/null +++ b/parse-unit/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for parse-unit 1.0 +// Project: https://github.com/mattdesl/parse-unit +// Definitions by: Jack Works +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function parse(value: string): [number, string]; +export = parse; diff --git a/parse-unit/parse-unit-tests.ts b/parse-unit/parse-unit-tests.ts new file mode 100644 index 0000000000..772641c302 --- /dev/null +++ b/parse-unit/parse-unit-tests.ts @@ -0,0 +1,4 @@ +import parse = require('parse-unit') +let [number, length] = parse('10px') +number === 50 +length === 'px' diff --git a/parse-unit/tsconfig.json b/parse-unit/tsconfig.json new file mode 100644 index 0000000000..4f0a626508 --- /dev/null +++ b/parse-unit/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "parse-unit-tests.ts" + ] +} diff --git a/parse-unit/tslint.json b/parse-unit/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/parse-unit/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/passport-facebook/index.d.ts b/passport-facebook/index.d.ts index 4e84b4996b..320a2169ba 100644 --- a/passport-facebook/index.d.ts +++ b/passport-facebook/index.d.ts @@ -31,12 +31,31 @@ interface IStrategyOption { scopeSeparator?: string; enableProof?: boolean; profileFields?: string[]; - passReqToCallback?: boolean; +} + +interface IStrategyOptionWithRequest { + clientID: string; + clientSecret: string; + callbackURL: string; + + scopeSeparator?: string; + enableProof?: boolean; + profileFields?: string[]; + passReqToCallback: boolean; +} + +interface VerifyFunction { + (accessToken: string, refreshToken: string, profile: Profile, done: (error: any, user?: any, info?: any) => void): void; +} + +interface VerifyFunctionWithRequest { + (req: express.Request, accessToken: string, refreshToken: string, profile: Profile, done: (error: any, user?: any, info?: any) => void): void; } declare class Strategy implements passport.Strategy { - constructor(options: IStrategyOption, - verify: (accessToken: string, refreshToken: string, profile: Profile, done: (error: any, user?: any, info?: any) => void) => void); + constructor(options: IStrategyOptionWithRequest, verify: VerifyFunctionWithRequest); + constructor(options: IStrategyOption, verify: VerifyFunction); + name: string; authenticate: (req: express.Request, options?: Object) => void; } diff --git a/proj4/index.d.ts b/proj4/index.d.ts index d59063f51b..ff2b8334de 100644 --- a/proj4/index.d.ts +++ b/proj4/index.d.ts @@ -1,102 +1,67 @@ -// Type definitions for proj4 2.3.15 +// Type definitions for proj4 2.3 // Project: https://github.com/proj4js/proj4js // Definitions by: Denis Carriere // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "proj4" { - const TemplateCoordinates: Array | InterfaceCoordinates; +declare namespace proj4 { + type TemplateCoordinates = number[] | InterfaceCoordinates; interface InterfaceCoordinates { - x: number, - y: number, - z?: number, - m?: number + x: number; + y: number; + z?: number; + m?: number; } interface InterfaceDatum { - datum_type: number - a: number - b: number - es: number - ep2: number + datum_type: number; + a: number; + b: number; + es: number; + ep2: number; } - interface Proj4Static { - forward(coordinates: typeof TemplateCoordinates): Array - inverse(coordinates: typeof TemplateCoordinates): Array + interface Static { + forward(coordinates: TemplateCoordinates): number[]; + inverse(coordinates: TemplateCoordinates): number[]; } interface InterfaceProjection { - datum: string - b: number - rf: number - sphere: number - es: number - e: number - ep2: number - forward(coordinates: typeof TemplateCoordinates): Array - inverse(coordinates: typeof TemplateCoordinates): Array + datum: string; + b: number; + rf: number; + sphere: number; + es: number; + e: number; + ep2: number; + forward(coordinates: TemplateCoordinates): number[]; + inverse(coordinates: TemplateCoordinates): number[]; } - namespace proj4 { - /** - * @name defaultDatum - */ - export const defaultDatum: string; + export const defaultDatum: string; - /** - * @name Proj - */ - export function Proj(srsCode:any, callback?: any): InterfaceProjection; - - /** - * @name WGS84 - */ - export const WGS84: any; + export function Proj(srsCode: any, callback?: any): InterfaceProjection; - /** - * Depecrated v3 - * @name Point - */ - export function Point(x: number, y: number, z?: number): InterfaceCoordinates; - export function Point(coordinates: Array): InterfaceCoordinates; - export function Point(coordinates: InterfaceCoordinates): InterfaceCoordinates; - export function Point(coordinates: string): InterfaceCoordinates; - - /** - * @name toPoint - */ - export function toPoint(array: Array): InterfaceCoordinates; - - /** - * @name defs - */ - export function defs(name: string): any; - export function defs(name: string, projection: string): any; - export function defs(name: Array>): any; - - /** - * @name transform - */ - export function transform(source: InterfaceProjection, dest: InterfaceProjection, point: typeof TemplateCoordinates): any; - - /** - * @name mgrs - */ - export function mgrs(coordinates: Array, accuracy: number): string; - - /** - * @name version - */ - export const version: string; - } + export const WGS84: any; /** - * @name proj4 + * Depecrated v3 */ - function proj4(fromProjection: string): Proj4Static; - function proj4(fromProjection: string, toProjection: string): Proj4Static; - function proj4(fromProjection: string, coordinates: typeof TemplateCoordinates): Array; - function proj4(fromProjection: string, toProjection: string, coordinates: typeof TemplateCoordinates): Array; - export = proj4 + export function Point(x: number, y: number, z?: number): InterfaceCoordinates; + export function Point(coordinates: TemplateCoordinates | string): InterfaceCoordinates; + + export function toPoint(array: number[]): InterfaceCoordinates; + + export function defs(name: string, projection?: string): any; + export function defs(name: string[][]): any; + + export function transform(source: InterfaceProjection, dest: InterfaceProjection, point: TemplateCoordinates): any; + + export function mgrs(coordinates: number[], accuracy: number): string; + + export const version: string; } + +declare function proj4(fromProjection: string, toProjection?: string, coordinates?: proj4.TemplateCoordinates): proj4.Static; +declare function proj4(fromProjection: string, coordinates: proj4.TemplateCoordinates): number[]; +export = proj4; diff --git a/proj4/proj4-tests.ts b/proj4/proj4-tests.ts index 72fa804c6e..2c658b8f24 100644 --- a/proj4/proj4-tests.ts +++ b/proj4/proj4-tests.ts @@ -1,49 +1,49 @@ -import * as proj4 from 'proj4' +import * as proj4 from 'proj4'; /////////////////////////////////////////// // Tests data initialisation /////////////////////////////////////////// -const name = 'WGS84' +const name = 'WGS84'; const epsg = { 4269: '+title=NAD83 (long/lat) +proj=longlat +a=6378137.0 +b=6356752.31414036 +ellps=GRS80 +datum=NAD83 +units=degrees', 4326: '+title=WGS 84 (long/lat) +proj=longlat +ellps=WGS84 +datum=WGS84 +units=degrees', -} -const point1 = [-71, 41] -const point2 = {x: 2, y: 5} -const mgrs = "24XWT783908" +}; +const point1 = [-71, 41]; +const point2 = {x: 2, y: 5}; +const mgrs = "24XWT783908"; /////////////////////////////////////////// // Tests Measurement /////////////////////////////////////////// -proj4(epsg['4269'], epsg['4326'], point1) -proj4(epsg['4269'], point1) -proj4(epsg['4269'], epsg['4326']).forward(point2) -proj4(epsg['4269'], epsg['4326']).inverse(point2) +proj4(epsg['4269'], epsg['4326'], point1); +proj4(epsg['4269'], point1); +proj4(epsg['4269'], epsg['4326']).forward(point2); +proj4(epsg['4269'], epsg['4326']).inverse(point2); /////////////////////////////////// // Named Projections /////////////////////////////////// -proj4.defs('WGS84', epsg['4326']) +proj4.defs('WGS84', epsg['4326']); proj4.defs([ ['EPSG:4326', epsg['4326']], ['EPSG:4269', epsg['4269']] -]) -proj4.defs('urn:x-ogc:def:crs:EPSG:4326', proj4.defs('EPSG:4326')) +]); +proj4.defs('urn:x-ogc:def:crs:EPSG:4326', proj4.defs('EPSG:4326')); /////////////////////////////////// // Utils /////////////////////////////////// // WGS84 -proj4.WGS84 +proj4.WGS84; // Proj -proj4.Proj('WGS84') +proj4.Proj('WGS84'); // toPoint -proj4.toPoint([1, 2]) -proj4.toPoint([1, 2, 3]) -proj4.toPoint([1, 2, 3, 4]) +proj4.toPoint([1, 2]); +proj4.toPoint([1, 2, 3]); +proj4.toPoint([1, 2, 3, 4]); // Point // WARNING: Deprecated in v3 -proj4.Point([1, 2, 3, 4]) \ No newline at end of file +proj4.Point([1, 2, 3, 4]); \ No newline at end of file diff --git a/proj4/tslint.json b/proj4/tslint.json new file mode 100644 index 0000000000..2221e40e4a --- /dev/null +++ b/proj4/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } \ No newline at end of file diff --git a/protractor-helpers/index.d.ts b/protractor-helpers/index.d.ts index 3ab4691778..9821f5ba0c 100644 --- a/protractor-helpers/index.d.ts +++ b/protractor-helpers/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/wix/protractor-helpers // Definitions by: John Cant // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// diff --git a/protractor-http-mock/index.d.ts b/protractor-http-mock/index.d.ts index 5f9dbcd79a..110883a8d3 100644 --- a/protractor-http-mock/index.d.ts +++ b/protractor-http-mock/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Crevil // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +import * as webdriver from 'selenium-webdriver'; declare namespace mock { interface ProtractorHttpMock { diff --git a/protractor-http-mock/tsconfig.json b/protractor-http-mock/tsconfig.json index 1280c748d3..486d3cff30 100644 --- a/protractor-http-mock/tsconfig.json +++ b/protractor-http-mock/tsconfig.json @@ -9,6 +9,9 @@ "strictNullChecks": false, "baseUrl": "../", "types": [], + "paths": { + "selenium-webdriver": ["selenium-webdriver/v2"] + }, "noEmit": true, "forceConsistentCasingInFileNames": true }, diff --git a/ramda/index.d.ts b/ramda/index.d.ts index 114ba38d6d..3e79c3cd4c 100644 --- a/ramda/index.d.ts +++ b/ramda/index.d.ts @@ -185,8 +185,8 @@ declare namespace R { * Returns a new list, composed of n-tuples of consecutive elements If n is greater than the length of the list, * an empty list is returned. */ - aperture(n: number, list: T): T[][]; - aperture(n: number): (list: T) => T[][]; + aperture(n: number, list: T[]): T[][]; + aperture(n: number): (list: T[]) => T[][]; /** * Returns a new list containing the contents of the given list, followed by the given element. diff --git a/raven-js/index.d.ts b/raven-js/index.d.ts deleted file mode 100644 index 7b54ec7372..0000000000 --- a/raven-js/index.d.ts +++ /dev/null @@ -1,338 +0,0 @@ -// Type definitions for Raven.js -// Project: https://github.com/getsentry/raven-js -// Definitions by: Santi Albo , Benjamin Pannell , Gary Blackwood , Rich Rout , Ben Vinegar , Ilya Pirogov , Eli White , David Cramer , Connor Peet , comaz , Luca Vazzano -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - - -declare let Raven: RavenStatic; -export default Raven; - -interface RavenStatic { - /** Raven.js version. */ - VERSION: string; - - /** A list of currently active plugins. */ - Plugins: { [id: string]: RavenPlugin }; - - /** - * Allow Raven to be configured as soon as it is loaded. - * It uses a global RavenConfig = {dsn: '...', config: {}} - */ - afterLoad(): void; - - /** - * Allow multiple versions of Raven to be installed. - * Strip Raven from the global context and returns the instance. - */ - noConflict(): RavenStatic; - - /** - * Configure Raven with a DSN and extra options - * - * @param dsn The public Sentry DSN - * @param options Optional set of of global options - */ - config(dsn: string, options?: RavenGlobalOptions): RavenStatic; - - /** - * Set the DSN (can be called multiple times, unlike config) - * - * @param dsn The public Sentry DSN - */ - setDSN(dsn: string): RavenStatic; - - /** - * Installs a global window.onerror error handler to capture and report uncaught exceptions. - * At this point, install() is required to be called due to the way TraceKit is set up. - */ - install(): RavenStatic; - - /** - * Adds a plugin to Raven - */ - addPlugin(plugin: RavenPlugin, ...pluginArgs: any[]): RavenStatic; - - /** - * Wrap code within a context so Raven can capture errors reliably across domains that is - * executed immediately. - * - * @param options A specific set of options for this context - * @param func The callback to be immediately executed within the context - * @param args An array of arguments to be called with the callback - */ - context(func: Function, ...args: any[]): void; - context(options: RavenWrapOptions, func: Function, ...args: any[]): void; - - /** - * Wrap code within a context and returns back a new function to be executed - * - * @param options A specific set of options for this context - * @param func The function to be wrapped in a new context - * @return The newly wrapped functions with a context - */ - wrap(func: Function): Function; - wrap(options: RavenWrapOptions, func: Function): Function; - wrap(func: T): T; - wrap(options: RavenWrapOptions, func: T): T; - - /** - * Uninstalls the global error handler. - */ - uninstall(): RavenStatic; - - /** - * Manually capture an exception and send it over to Sentry - * - * @param ex An exception to be logged - * @param options A specific set of options for this error - */ - captureException(ex: Error, options?: RavenOptions): RavenStatic; - - /* - * Manually send a message to Sentry - * - * @param msg A plain message to be captured in Sentry - * @param options A specific set of options for this message - */ - captureMessage(msg: string, options?: RavenOptions): RavenStatic; - - /** - * Add a breadcrumb - * @param crumb The trail which should be added to the trail - */ - captureBreadcrumb(crumb: RavenBreadcrumb): RavenStatic; - - /** - * Set a user to be sent along with payloads. - * - * @param user The definition of the currently active user's unique identity - */ - setUserContext(user: RavenUserContext): RavenStatic; - - /** - * Clear the user context, removing the user data that would be sent to Sentry. - */ - setUserContext(): RavenStatic; - - /** - * Add arbitrary data to be sent along with the payload. - * @param extra data of an arbitrary, nested type which will be added - */ - setExtraContext(extra: { [prop: string]: any }): RavenStatic; - - /** - * Add additional tags to be sent along with payloads. - * @param tags A key/value-pair which will be added - */ - setTagsContext(tags: { [id: string]: string }): RavenStatic; - - /** - * Clear the whole currently set context. - */ - clearContext(): RavenStatic; - - /** - * Get a copy of the current context. - */ - getContext(): Object; - - /** - * Set environment of application - * @param environment Typically something like 'production' - */ - setEnvironment(environment: string): RavenStatic; - - /** - * Set release version of application - * @param release Typically something like a git SHA to identify the current version - */ - setRelease(release: string): RavenStatic; - - /** - * Specify a function that can mutate the payload right before it is being sent to Sentry. - * @param callback The function which can mutate the data - */ - setDataCallback(callback: (data: any, orig?: string) => any): RavenStatic; - - /** - * Specify a callback function that can mutate or filter breadcrumbs when they are captured. - * @param callback The function which applies the filter - */ - setBreadcrumbCallback(callback :(data: any, orig?: string) => any): RavenStatic; - - /** - * Specify a callback function that determines if the given message should be sent to Sentry. - * @param callback The function which determines if the given blob should be sent - */ - setShouldSendCallback(callback: (data: any, orig?: string) => boolean): RavenStatic; - - /** - * Override the default HTTP data transport handler. - * @param transport The function which will be invoked to handle the data transmission - */ - setTransport(transport: (options: RavenTransportOptions) => void): RavenStatic; - - /** - * Get the latest raw exception that was captured by Raven. - */ - lastException(): Error; - - /** - * Get the ID of the last Event captured by Raven. - */ - lastEventId(): string; - - /** - * Determine if Raven is setup and ready to go. - */ - isSetup(): boolean; - - /** - * Show the User Feedback Dialog of Sentry - * @param RavenReportDialogOptions Optional Options to set for the User Feedback - */ - showReportDialog(options?: RavenReportDialogOptions): void; -} - - -// --- Helper Interfaces for Options -------------- -export interface RavenBreadcrumOptions { - /** Whether to collect XHR calls, defaults to true */ - xhr?: boolean; - - /** Whether to collect console logs, defaults to true */ - console?: boolean; - - /** Whether to collect dom events, defaults to true */ - dom?: boolean; - - /** Whether to record window location and navigation, defaults to true */ - location?: boolean; -} - -export interface CommonRavenOptions { - /** The environment of the application you are monitoring with Sentry */ - environment?: string; - - /** The release version of the application you are monitoring with Sentry */ - release?: string; - - /** Additional key/value-data to be tagged onto the error. */ - tags?: { [id: string]: string }; - - /** Additional, arbitrary metadata to collect */ - extra?: { [prop: string]: any }; - - /** The name of the logger used by Sentry. Default: javascript */ - logger?: string; - - /** set to true to get the strack trace of your message */ - stacktrace?: boolean; -} - -export interface RavenOptions extends CommonRavenOptions { - /** The name of the server or device that the client is running on */ - server_name?: string; - - /** The log level associated with this event. Default: error */ - level?: string; - - /** In some cases you may see issues where Sentry groups multiple events together when they - * should be separate entities. In other cases, Sentry simply doesn’t group events together - * because they’re so sporadic that they never look the same. */ - fingerprint?: string[]; - - /** Number of frames to trim off the stacktrace. Default: 1 */ - trimHeadFrames?: number; - - /** The name of the device platform. Default: "javascript" */ - platform?: string; -} - -export interface RavenGlobalOptions extends CommonRavenOptions { - /** The name of the server or device that the client is running on */ - serverName?: string; - - /** Configures which breadcrumbs are collected automatically */ - autoBreadcrumbs?: boolean | RavenBreadcrumOptions; - - /** Whether to collect errors on the window via TraceKit.collectWindowErrors. Default: true. */ - collectWindowErrors?: boolean; - - /** Max number of breadcrumbs to collect. Default: 100 */ - maxBreadcrumbs?: number; - - /** Exclude messages which match one of the given RegEx-Patterns from being sent to Sentry. */ - ignoreErrors?: (RegExp | string)[]; - - /** Exclude messages which come from whole urls matching one of the given RegEx patterns. */ - ignoreUrls?: (RegExp | string)[]; - - /** Only report messages which come from whole urls matching one of the given RegEx patterns. */ - whitelistUrls?: (RegExp | string)[]; - - /** An array of RegEx patterns to indicate which urls are a part of your app. */ - includePaths?: (RegExp | string)[]; - - /** Maximum amount of stack frames to collect. Default: Infinity */ - stackTraceLimit?: number; - - /** Override the default HTTP data transport handler. */ - transport?: (options: RavenTransportOptions) => void; - - /** Limit the maxium length of a message to this number of characters. Default: Infinity */ - maxMessageLength?: number; - - /** Allows you to apply your own filters to determine if the message should be sent to Sentry. */ - shouldSendCallback?: (data: any) => boolean; - - /** A function which allows mutation of the data payload right before being sent to Sentry */ - dataCallback?: (data: any) => any; -} - -export interface RavenWrapOptions extends RavenOptions { - /** Whether to run the wrap recursively. Default: false. */ - deep?: boolean; -} - -export interface RavenTransportOptions { - url: string; - data: any; - auth: { - sentry_version: string; - sentry_client: string; - sentry_key: string; - }; - onSuccess: () => void; - onFailure: () => void; -} - -export interface RavenReportDialogOptions { - eventId?: number, - dsn?: string, - user?: { - name?: string, - email?: string - } -} - - -// --- Helper Interfaces for complex Data Structures -------------- -export interface RavenPlugin { - (raven: RavenStatic, ...args: any[]): RavenStatic; -} - -export interface RavenUserContext { - id?: string; - username?: string; - email?: string; - ip_address?: string; - extra?: { [prop: string]: any }; -} - -export interface RavenBreadcrumb { - message: string; - data: { [id: string]: string }; - category: string; - level: string; -} diff --git a/raven-js/raven-js-tests.ts b/raven-js/raven-js-tests.ts deleted file mode 100644 index bbd3285e1e..0000000000 --- a/raven-js/raven-js-tests.ts +++ /dev/null @@ -1,61 +0,0 @@ -import RavenJS from 'raven-js'; - -RavenJS.config('https://public@getsentry.com/1').install(); - - -RavenJS.config( - 'https://public@getsentry.com/1', - { - logger: 'my-logger', - ignoreUrls: [ - /graph\.facebook\.com/i - ], - ignoreErrors: [ - 'fb_xd_fragment' - ], - includePaths: [ - /https?:\/\/(www\.)?getsentry\.com/, - /https?:\/\/d3nslu0hdya83q\.cloudfront\.net/ - ] - } -).install(); - -var throwsError = () => { - throw new Error('broken'); -}; - -try { - throwsError(); -} catch(e) { - RavenJS.captureException(e); - RavenJS.captureException(e, {tags: { key: "value" }}); -} - -RavenJS.context(throwsError); -RavenJS.context({tags: { key: "value" }}, throwsError); -RavenJS.context({extra: {planet: {name: 'Earth'}}}, throwsError); - -setTimeout(RavenJS.wrap(throwsError), 1000); -RavenJS.wrap({logger: "my.module"}, throwsError)(); -RavenJS.wrap({tags: {git_commit: 'c0deb10c4'}}, throwsError)(); - -RavenJS.setUserContext({ - email: 'matt@example.com', - id: '123' -}); - -RavenJS.captureMessage('Broken!'); -RavenJS.captureMessage('Broken!', {tags: { key: "value" }}); - -RavenJS.showReportDialog({ - eventId: 0815, - dsn:'1337asdf', - user: { - name: 'DefenitelyTyped', - email: 'df@ts.ms' - } -}); - -RavenJS.setTagsContext({ key: "value" }); - -RavenJS.setExtraContext({ foo: "bar" }); diff --git a/react-autosuggest/index.d.ts b/react-autosuggest/index.d.ts index d0d6bec839..7199fefcdb 100644 --- a/react-autosuggest/index.d.ts +++ b/react-autosuggest/index.d.ts @@ -1,11 +1,16 @@ -// Type definitions for react-autosuggest 7.0 +// Type definitions for react-autosuggest 8.0 // Project: http://react-autosuggest.js.org/ -// Definitions by: Nicolas Schmitt , Philip Ottesen , Robert Essig +// Definitions by: Nicolas Schmitt , Philip Ottesen , Robert Essig , Terry Bayne // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 -import * as React from 'react'; +import * as React from 'react'; +declare class Autosuggest extends React.Component {} + +export = Autosuggest; + +declare namespace Autosuggest { interface SuggestionsFetchRequest { value: string; reason: string; @@ -31,7 +36,7 @@ import * as React from 'react'; onBlur?: (event: React.FormEvent, params?: BlurEvent) => void; } - export interface SuggestionSelectedEventData { + export interface SuggestionSelectedEventData { method: 'click' | 'enter'; sectionIndex: number | null; suggestion: TSuggestion; @@ -71,4 +76,4 @@ import * as React from 'react'; id?: string; } - export class Autosuggest extends React.Component {} +} diff --git a/react-autosuggest/react-autosuggest-tests.tsx b/react-autosuggest/react-autosuggest-tests.tsx index 3eaee3e4e7..f5ecaedc63 100644 --- a/react-autosuggest/react-autosuggest-tests.tsx +++ b/react-autosuggest/react-autosuggest-tests.tsx @@ -1,42 +1,69 @@ // region Imports import React = require('react'); import ReactDOM = require('react-dom'); -import { Autosuggest, SuggestionSelectedEventData } from 'react-autosuggest'; +import Autosuggest = require('react-autosuggest'); // endregion interface Language { - name: string; - year: number; + name : string; + year : number; } -// https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions#Using_Special_Characters -function escapeRegexCharacters(str: string): string { +// https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expression +// s#Using_Special_Characters +function escapeRegexCharacters(str : string) : string { return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); } export class ReactAutosuggestBasicTest extends React.Component { // region Fields - static languages: Language[] = [ - {name: 'C', year: 1972}, - {name: 'C#', year: 2000}, - {name: 'C++', year: 1983}, - {name: 'Clojure', year: 2007}, - {name: 'Elm', year: 2012}, - {name: 'Go', year: 2009}, - {name: 'Haskell', year: 1990}, - {name: 'Java', year: 1995}, - {name: 'Javascript', year: 1995}, - {name: 'Perl', year: 1987}, - {name: 'PHP', year: 1995}, - {name: 'Python', year: 1991}, - {name: 'Ruby', year: 1995}, - {name: 'Scala', year: 2003} + static languages : Language[] = [ + { + name: 'C', + year: 1972 + }, { + name: 'C#', + year: 2000 + }, { + name: 'C++', + year: 1983 + }, { + name: 'Clojure', + year: 2007 + }, { + name: 'Elm', + year: 2012 + }, { + name: 'Go', + year: 2009 + }, { + name: 'Haskell', + year: 1990 + }, { + name: 'Java', + year: 1995 + }, { + name: 'Javascript', + year: 1995 + }, { + name: 'Perl', + year: 1987 + }, { + name: 'PHP', + year: 1995 + }, { + name: 'Python', + year: 1991 + }, { + name: 'Ruby', + year: 1995 + }, { + name: 'Scala', + year: 2003 + } ]; - // endregion - - - // region Constructor - constructor(props: any) { + // endregion region Constructor + constructor(props : any) { super(props); this.state = { @@ -44,15 +71,15 @@ export class ReactAutosuggestBasicTest extends React.Component { suggestions: this.getSuggestions('') }; } - // endregion - - // region Rendering methods - render(): JSX.Element { + // endregion region Rendering methods + render() : JSX.Element { const {value, suggestions} = this.state; const inputProps = { placeholder: `Type 'c'`, value, - onChange: this.onChange.bind(this) + onChange: this + .onChange + .bind(this) }; const theme = { @@ -61,42 +88,38 @@ export class ReactAutosuggestBasicTest extends React.Component { suggestionFocused: 'active' }; - return ; + return ; } - protected onSuggestionsSelected(event: React.FormEvent, data: SuggestionSelectedEventData): void { + protected onSuggestionsSelected(event : React.FormEvent, data : Autosuggest.SuggestionSelectedEventData) : void { alert(`Selected language is ${data.suggestion.name} (${data.suggestion.year}).`); } - protected renderSuggestion(suggestion: Language): JSX.Element { + protected renderSuggestion(suggestion : Language) : JSX.Element { return {suggestion.name}; } - // endregion - - // region Event handlers - protected onChange(event: React.FormEvent, {newValue, method}: any): void { - this.setState({ - value: newValue - }); + // endregion region Event handlers + protected onChange(event : React.FormEvent, {newValue, method} : any) : void { + this.setState({value: newValue}); } - protected onSuggestionsFetchRequested({ value }: any): void { + protected onSuggestionsFetchRequested({value}: any) : void { this.setState({ suggestions: this.getSuggestions(value) }); } - // endregion - - // region Helper methods - protected getSuggestions(value: string): Language[] { + // endregion region Helper methods + protected getSuggestions(value: string) : Language[] { const escapedValue = escapeRegexCharacters(value.trim()); if (escapedValue === '') { @@ -105,69 +128,97 @@ export class ReactAutosuggestBasicTest extends React.Component { const regex = new RegExp('^' + escapedValue, 'i'); - return ReactAutosuggestBasicTest.languages.filter(language => regex.test(language.name)); + return ReactAutosuggestBasicTest + .languages + .filter(language => regex.test(language.name)); } - protected getSuggestionValue(suggestion: Language): string { - return suggestion.name; - } + protected getSuggestionValue(suggestion: Language) : string {return suggestion.name;} // endregion } -ReactDOM.render(, document.getElementById('app')); +ReactDOM.render( + , document.getElementById('app')); interface LanguageGroup { - title: string; - languages: Language[]; + title : string; + languages : Language[]; } -export class ReactAutosuggestMultipleTest extends React.Component { +export class ReactAutosuggestMultipleTest extends React.Component { // region Fields - static languages: LanguageGroup[] = [ + static languages : LanguageGroup[] = [ { title: '1970s', languages: [ - {name: 'C', year: 1972} + { + name: 'C', + year: 1972 + } ] - }, - { + }, { title: '1980s', languages: [ - {name: 'C++', year: 1983}, - {name: 'Perl', year: 1987} + { + name: 'C++', + year: 1983 + }, { + name: 'Perl', + year: 1987 + } ] - }, - { + }, { title: '1990s', languages: [ - {name: 'Haskell', year: 1990}, - {name: 'Python', year: 1991}, - {name: 'Java', year: 1995}, - {name: 'Javascript', year: 1995}, - {name: 'PHP', year: 1995}, - {name: 'Ruby', year: 1995} + { + name: 'Haskell', + year: 1990 + }, { + name: 'Python', + year: 1991 + }, { + name: 'Java', + year: 1995 + }, { + name: 'Javascript', + year: 1995 + }, { + name: 'PHP', + year: 1995 + }, { + name: 'Ruby', + year: 1995 + } ] - }, - { + }, { title: '2000s', languages: [ - {name: 'C#', year: 2000}, - {name: 'Scala', year: 2003}, - {name: 'Clojure', year: 2007}, - {name: 'Go', year: 2009} + { + name: 'C#', + year: 2000 + }, { + name: 'Scala', + year: 2003 + }, { + name: 'Clojure', + year: 2007 + }, { + name: 'Go', + year: 2009 + } ] - }, - { + }, { title: '2010s', languages: [ - {name: 'Elm', year: 2012} + { + name: 'Elm', + year: 2012 + } ] } ]; - // endregion - - // region Constructor - constructor(props: any) { + // endregion region Constructor + constructor(props : any) { super(props); this.state = { @@ -175,59 +226,56 @@ export class ReactAutosuggestMultipleTest extends React.Component { suggestions: this.getSuggestions('') }; } - // endregion - - // region Rendering methods - render(): JSX.Element { - const { value, suggestions } = this.state; + // endregion region Rendering methods + render() : JSX.Element { + const {value, suggestions} = this.state; const inputProps = { placeholder: `Type 'c'`, value, - onChange: this.onChange.bind(this) + onChange: this + .onChange + .bind(this) }; - return ; + return ; } - protected onSuggestionSelected(event: React.FormEvent, data: SuggestionSelectedEventData): void { + protected onSuggestionSelected(event : React.FormEvent, data : Autosuggest.SuggestionSelectedEventData) : void { const language = data.suggestion as Language; alert(`Selected language is ${language.name} (${language.year}).`); } - protected renderSuggestion(suggestion: Language): JSX.Element { + protected renderSuggestion(suggestion : Language) : JSX.Element { return {suggestion.name}; } - protected renderSectionTitle(section: LanguageGroup): JSX.Element { + protected renderSectionTitle(section : LanguageGroup) : JSX.Element { return {section.title}; } - // endregion - - // region Event handlers - protected onChange(event: React.FormEvent, { newValue, method }: any): void { - this.setState({ - value: newValue - }); + // endregion region Event handlers + protected onChange(event : React.FormEvent, {newValue, method} : any) : void { + this.setState({value: newValue}); } - protected onSuggestionsFetchRequested({ value }: any): void { + protected onSuggestionsFetchRequested({value} : any) : void { this.setState({ suggestions: this.getSuggestions(value) }); } - // endregion - - // region Helper methods - protected getSuggestions(value: string): LanguageGroup[] { + // endregion region Helper methods + protected getSuggestions(value : string) : LanguageGroup[] { const escapedValue = escapeRegexCharacters(value.trim()); if (escapedValue === '') { @@ -236,46 +284,61 @@ export class ReactAutosuggestMultipleTest extends React.Component { const regex = new RegExp('^' + escapedValue, 'i'); - return ReactAutosuggestMultipleTest.languages + return ReactAutosuggestMultipleTest + .languages .map(section => { return { title: section.title, - languages: section.languages.filter(language => regex.test(language.name)) + languages: section + .languages + .filter(language => regex.test(language.name)) }; }) .filter(section => section.languages.length > 0); } - protected getSuggestionValue(suggestion: Language) { + protected getSuggestionValue(suggestion : Language) { return suggestion.name; } - protected getSectionSuggestions(section: LanguageGroup) { + protected getSectionSuggestions(section : LanguageGroup) { return section.languages; } // endregion } -ReactDOM.render(, document.getElementById('app')); +ReactDOM.render( + , document.getElementById('app')); interface Person { - first: string; - last: string; - twitter: string; + first : string; + last : string; + twitter : string; } -export class ReactAutosuggestCustomTest extends React.Component { +export class ReactAutosuggestCustomTest extends React.Component { // region Fields - static people: Person[] = [ - {first: 'Charlie', last: 'Brown', twitter: 'dancounsell'}, - {first: 'Charlotte', last: 'White', twitter: 'mtnmissy'}, - {first: 'Chloe', last: 'Jones', twitter: 'ladylexy'}, - {first: 'Cooper', last: 'King', twitter: 'steveodom'} + static people : Person[] = [ + { + first: 'Charlie', + last: 'Brown', + twitter: 'dancounsell' + }, { + first: 'Charlotte', + last: 'White', + twitter: 'mtnmissy' + }, { + first: 'Chloe', + last: 'Jones', + twitter: 'ladylexy' + }, { + first: 'Cooper', + last: 'King', + twitter: 'steveodom' + } ]; - // endregion - - // region Constructor - constructor(props: any) { + // endregion region Constructor + constructor(props : any) { super(props); this.state = { @@ -283,64 +346,62 @@ export class ReactAutosuggestCustomTest extends React.Component { suggestions: this.getSuggestions('') }; } - // endregion - - // region Rendering methods - render(): JSX.Element { - const { value, suggestions } = this.state; + // endregion region Rendering methods + render() : JSX.Element { + const {value, suggestions} = this.state; const inputProps = { placeholder: "Type 'c'", value, - onChange: this.onChange.bind(this) + onChange: this + .onChange + .bind(this) }; - return ; + return; } - protected renderSuggestion(suggestion: Person, { value, valueBeforeUpDown }: any): JSX.Element { + protected renderSuggestion(suggestion : Person, {value, valueBeforeUpDown} : any) : JSX.Element { const suggestionText = `${suggestion.first} ${suggestion.last}`; const query = (valueBeforeUpDown || value).trim(); - const parts = suggestionText.split(' ').map((part: string) => { - return { - highlight: (Math.ceil(Math.random() * 10)) % 2, - text: part - }; - }); + const parts = suggestionText + .split(' ') + .map((part : string) => { + return { + highlight: (Math.ceil(Math.random() * 10)) % 2, + text: part + }; + }); - return - - { - parts.map((part, index) => { - const className = part.highlight ? 'highlight' : undefined; + return + + {parts.map((part, index) => { + const className = part.highlight + ? 'highlight' + : undefined; - return {part.text}; - }) - } - - ; + return{part.text}; + }) +} + + ; } - // endregion - - // region Event handlers - protected onChange(event: React.FormEvent, {newValue, method}: any): void { - this.setState({ - value: newValue - }); + // endregion region Event handlers + protected onChange(event : React.FormEvent, {newValue, method} : any) : void { + this.setState({value: newValue}); } - protected onSuggestionsFetchRequested({ value }: any): void { + protected onSuggestionsFetchRequested({value} : any) : void { this.setState({ suggestions: this.getSuggestions(value) }); } - // endregion - - // region Helper methods - protected getSuggestions(value: string): Person[] { + // endregion region Helper methods + protected getSuggestions(value : string) : Person[] { const escapedValue = escapeRegexCharacters(value.trim()); if (escapedValue === '') { @@ -349,13 +410,14 @@ export class ReactAutosuggestCustomTest extends React.Component { const regex = new RegExp('\\b' + escapedValue, 'i'); - return ReactAutosuggestCustomTest.people.filter(person => regex.test(this.getSuggestionValue(person))); + return ReactAutosuggestCustomTest + .people + .filter(person => regex.test(this.getSuggestionValue(person))); } - protected getSuggestionValue(suggestion: Person): string { - return `${suggestion.first} ${suggestion.last}`; - } + protected getSuggestionValue(suggestion : Person) : string {return `${suggestion.first} ${suggestion.last}`;} // endregion } -ReactDOM.render(, document.getElementById('app')); +ReactDOM.render( + , document.getElementById('app')); diff --git a/react-bootstrap/index.d.ts b/react-bootstrap/index.d.ts index 6c17fb4cee..500babd6cf 100644 --- a/react-bootstrap/index.d.ts +++ b/react-bootstrap/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for react-bootstrap // Project: https://github.com/react-bootstrap/react-bootstrap -// Definitions by: Walker Burgin , Vincent Siao , Danilo Barros , Batbold Gansukh , Raymond May Jr. +// Definitions by: Walker Burgin , Vincent Siao , Danilo Barros , Batbold Gansukh , Raymond May Jr. , Cheng Sieu Ly // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 @@ -867,6 +867,15 @@ declare namespace ReactBootstrap { type Image = React.ClassicComponent; var Image: React.ClassicComponentClass; + // + interface ResponsiveEmbedProps extends React.HTMLProps { + a16by9?: boolean; + a4by3?: boolean; + bsClass?: string; + } + class ResponsiveEmbed extends React.Component { + } + // interface PageHeaderProps extends React.HTMLProps { } diff --git a/react-bootstrap/react-bootstrap-tests.tsx b/react-bootstrap/react-bootstrap-tests.tsx index f3772d0fef..987203fbf8 100644 --- a/react-bootstrap/react-bootstrap-tests.tsx +++ b/react-bootstrap/react-bootstrap-tests.tsx @@ -14,7 +14,7 @@ import { Nav, NavItem, Navbar, NavDropdown, Tabs, Tab, Pager, PageItem, Pagination, Alert, Carousel, SafeAnchor, - Grid, Row, Col, Thumbnail, Image, + Grid, Row, Col, Thumbnail, Image, ResponsiveEmbed, Label, Badge, Jumbotron, PageHeader, Glyphicon, Table, Form, FormGroup, ControlLabel, FormControl, HelpBlock, @@ -845,6 +845,20 @@ export class ReactBootstrapTest extends Component { +
+
+ + Embedded Content + + + Embedded Content + + + Embedded Content + +
+
+
Example page header Subtext for header
diff --git a/react-color/index.d.ts b/react-color/index.d.ts index bed3ae46ff..798f44d6eb 100644 --- a/react-color/index.d.ts +++ b/react-color/index.d.ts @@ -1,249 +1,58 @@ -// Type definitions for react-color v2.3.4 -// Project: https://casesandberg.github.io/react-color/ +// Type definitions for react-color 2.11 +// Project: https://github.com/casesandberg/react-color/ // Definitions by: Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 -/// +import { ComponentClass, ClassAttributes, StatelessComponent, ReactNode } from "react"; -declare namespace ReactColor { - interface HSLColor { - a?: number - h: number - l: number - s: number - } - - interface RGBColor { - a?: number - b: number - g: number - r: number - } - - type Color = string | HSLColor | RGBColor - - interface ColorResult { - hex: string - hsl: HSLColor - rgb: RGBColor - } - - type ColorChangeHandler = (color: ColorResult) => void - - interface ColorPickerProps extends React.ClassAttributes { - color?: Color - onChange?: ColorChangeHandler - onChangeComplete?: ColorChangeHandler - } - - /* Predefined pickers */ - interface AlphaPickerProps extends ColorPickerProps { - height?: string - width?: string - } - interface AlphaPicker extends React.ComponentClass {} - const AlphaPicker: AlphaPicker - - interface BlockPickerProps extends ColorPickerProps { - colors?: Array - width?: string - } - interface BlockPicker extends React.ComponentClass {} - const BlockPicker: BlockPicker - - interface ChromePickerProps extends ColorPickerProps { - disableAlpha?: boolean - } - interface ChromePicker extends React.ComponentClass {} - const ChromePicker: ChromePicker - - interface CirclePickerProps extends ColorPickerProps { - colors?: Array - width?: string - } - interface CirclePicker extends React.ComponentClass {} - const CirclePicker: CirclePicker - - interface CompactPickerProps extends ColorPickerProps { - colors?: Array - } - interface CompactPicker extends React.ComponentClass {} - const CompactPicker: CompactPicker - - interface GithubPickerProps extends ColorPickerProps { - colors?: Array - width?: string - } - interface GithubPicker extends React.ComponentClass {} - const GithubPicker: GithubPicker - - interface HuePickerProps extends ColorPickerProps { - height?: string - width?: string - } - interface HuePicker extends React.ComponentClass {} - const HuePicker: HuePicker - - interface MaterialPickerProps extends ColorPickerProps {} - interface MaterialPicker extends React.ComponentClass {} - const MaterialPicker: MaterialPicker - - interface PhotoshopPickerProps extends ColorPickerProps { - header?: string - onAccept?: ColorChangeHandler - onCancel?: ColorChangeHandler - } - interface PhotoshopPicker extends React.ComponentClass {} - const PhotoshopPicker: PhotoshopPicker - - interface SketchPickerProps extends ColorPickerProps { - disableAlpha?: boolean - presetColors?: Array - width?: string - } - interface SketchPicker extends React.ComponentClass {} - const SketchPicker: SketchPicker - - interface SliderPickerProps extends ColorPickerProps {} - interface SliderPicker extends React.ComponentClass {} - const SliderPicker: SliderPicker - - interface SwatchesPickerProps extends ColorPickerProps { - colors?: Array> - height?: number - width?: number - } - interface SwatchesPicker extends React.ComponentClass {} - const SwatchesPicker: SwatchesPicker - - interface TwitterPickerProps extends ColorPickerProps {} - interface TwitterPicker extends React.ComponentClass {} - const TwitterPicker: TwitterPicker - - /* For custom picker */ - interface InjectedColorProps { - hex?: string - hsl?: HSLColor - rgb?: RGBColor - onChange?: ColorChangeHandler - } - - function CustomPicker(component: React.ComponentClass | React.StatelessComponent): React.ComponentClass - - interface CustomPickerProps extends React.ClassAttributes { - color?: Color - pointer?: React.ReactNode - onChange?: ColorChangeHandler - } - - interface AlphaProps extends CustomPickerProps {} - interface Alpha extends React.ComponentClass {} - const Alpha: Alpha - - interface EditableInputStyles { - input?: React.CSSProperties - label?: React.CSSProperties - wrap?: React.CSSProperties - } - interface EditableInputProps extends React.ClassAttributes { - color?: Color - label?: string - onChange?: ColorChangeHandler - styles?: EditableInputStyles - value?: any - } - interface EditableInput extends React.ComponentClass {} - const EditableInput: EditableInput - - interface HueProps extends CustomPickerProps { - direction?: "horizontal" | "vertical" - } - interface Hue extends React.ComponentClass {} - const Hue: Hue - - interface SaturationProps extends CustomPickerProps {} - interface Saturation extends React.ComponentClass {} - const Saturation: Saturation - - interface CheckboardProps extends React.ClassAttributes { - grey?: string - size?: number - white?: string - } - interface Checkboard extends React.ComponentClass {} - const Checkboard: Checkboard +export interface HSLColor { + a?: number; + h: number; + l: number; + s: number; } -declare module "react-color/lib/components/common/Alpha" { export default ReactColor.Alpha } -declare module "react-color/lib/components/common/Checkboard" { export default ReactColor.Checkboard } -declare module "react-color/lib/components/common/EditableInput" { export default ReactColor.EditableInput } -declare module "react-color/lib/components/common/Hue" { export default ReactColor.Hue } -declare module "react-color/lib/components/common/Saturation" { export default ReactColor.Saturation } -declare module "react-color/lib/components/common/ColorWrap" { export default ReactColor.CustomPicker } - -declare module "react-color/lib/components/common" { - import Alpha from "react-color/lib/components/common/Alpha" - import Checkboard from "react-color/lib/components/common/Checkboard" - import EditableInput from "react-color/lib/components/common/EditableInput" - import Hue from "react-color/lib/components/common/Hue" - import Saturation from "react-color/lib/components/common/Saturation" - - export { - Alpha, - Checkboard, - EditableInput, - Hue, - Saturation - } +export interface RGBColor { + a?: number; + b: number; + g: number; + r: number; } -declare module "react-color/lib/components/alpha/Alpha" { export default ReactColor.AlphaPicker } -declare module "react-color/lib/components/block/Block" { export default ReactColor.BlockPicker } -declare module "react-color/lib/components/chrome/Chrome" { export default ReactColor.ChromePicker } -declare module "react-color/lib/components/circle/Circle" { export default ReactColor.CirclePicker } -declare module "react-color/lib/components/compact/Compact" { export default ReactColor.CompactPicker } -declare module "react-color/lib/components/github/Github" { export default ReactColor.GithubPicker } -declare module "react-color/lib/components/hue/Hue" { export default ReactColor.HuePicker } -declare module "react-color/lib/components/meterial/Material" { export default ReactColor.MaterialPicker } -declare module "react-color/lib/components/photoshop/Photoshop" { export default ReactColor.PhotoshopPicker } -declare module "react-color/lib/components/sketch/Sketch" { export default ReactColor.SketchPicker } -declare module "react-color/lib/components/slider/Slider" { export default ReactColor.SliderPicker } -declare module "react-color/lib/components/swatches/Swatches" { export default ReactColor.SwatchesPicker } -declare module "react-color/lib/components/twitter/Twitter" { export default ReactColor.TwitterPicker } +export type Color = string | HSLColor | RGBColor; -declare module "react-color" { - import AlphaPicker from "react-color/lib/components/alpha/Alpha" - import BlockPicker from "react-color/lib/components/block/Block" - import ChromePicker from "react-color/lib/components/chrome/Chrome" - import CirclePicker from "react-color/lib/components/circle/Circle" - import CompactPicker from "react-color/lib/components/compact/Compact" - import GithubPicker from "react-color/lib/components/github/Github" - import HuePicker from "react-color/lib/components/hue/Hue" - import MaterialPicker from "react-color/lib/components/meterial/Material" - import PhotoshopPicker from "react-color/lib/components/photoshop/Photoshop" - import SketchPicker from "react-color/lib/components/sketch/Sketch" - import SliderPicker from "react-color/lib/components/slider/Slider" - import SwatchesPicker from "react-color/lib/components/swatches/Swatches" - import TwitterPicker from "react-color/lib/components/twitter/Twitter" - import CustomPicker from "react-color/lib/components/common/ColorWrap" - - export type CustomPickerProps = ReactColor.CustomPickerProps - - export { - AlphaPicker, - BlockPicker, - ChromePicker, - CirclePicker, - CompactPicker, - GithubPicker, - HuePicker, - MaterialPicker, - PhotoshopPicker, - SketchPicker, - SliderPicker, - SwatchesPicker, - TwitterPicker, - CustomPicker - } +export interface ColorResult { + hex: string; + hsl: HSLColor; + rgb: RGBColor; } + +export type ColorChangeHandler = (color: ColorResult) => void; + +export interface ColorPickerProps extends ClassAttributes { + color?: Color; + onChange?: ColorChangeHandler; + onChangeComplete?: ColorChangeHandler; +} + +export interface CustomPickerProps extends ClassAttributes { + color?: Color; + pointer?: ReactNode; + onChange: ColorChangeHandler; +} + +export { default as AlphaPicker, AlphaPickerProps } from "react-color/lib/components/alpha/Alpha"; +export { default as BlockPicker, BlockPickerProps } from "react-color/lib/components/block/Block"; +export { default as ChromePicker, ChromePickerProps } from "react-color/lib/components/chrome/Chrome"; +export { default as CirclePicker, CirclePickerProps } from "react-color/lib/components/circle/Circle"; +export { default as CompactPicker, CompactPickerProps } from "react-color/lib/components/compact/Compact"; +export { default as GithubPicker, GithubPickerProps } from "react-color/lib/components/github/Github"; +export { default as HuePicker, HuePickerProps } from "react-color/lib/components/hue/Hue"; +export { default as MaterialPicker, MaterialPickerProps } from "react-color/lib/components/material/Material"; +export { default as PhotoshopPicker, PhotoshopPickerProps } from "react-color/lib/components/photoshop/Photoshop"; +export { default as SketchPicker, SketchPickerProps } from "react-color/lib/components/sketch/Sketch"; +export { default as SliderPicker, SliderPickerProps } from "react-color/lib/components/slider/Slider"; +export { default as SwatchesPicker, SwatchesPickerProps } from "react-color/lib/components/swatches/Swatches"; +export { default as TwitterPicker, TwitterPickerProps } from "react-color/lib/components/twitter/Twitter"; +export { default as CustomPicker, InjectedColorProps } from "react-color/lib/components/common/ColorWrap"; diff --git a/react-color/lib/components/alpha/Alpha.d.ts b/react-color/lib/components/alpha/Alpha.d.ts new file mode 100644 index 0000000000..2856f077b9 --- /dev/null +++ b/react-color/lib/components/alpha/Alpha.d.ts @@ -0,0 +1,9 @@ +import { Component } from "react"; +import { ColorPickerProps } from "react-color"; + +export interface AlphaPickerProps extends ColorPickerProps { + height?: string; + width?: string; +} + +export default class AlphaPicker extends Component {} diff --git a/react-color/lib/components/block/Block.d.ts b/react-color/lib/components/block/Block.d.ts new file mode 100644 index 0000000000..edb3c72347 --- /dev/null +++ b/react-color/lib/components/block/Block.d.ts @@ -0,0 +1,9 @@ +import { Component } from "react"; +import { ColorPickerProps } from "react-color"; + +export interface BlockPickerProps extends ColorPickerProps { + colors?: string[]; + width?: string; +} + +export default class BlockPicker extends Component {} diff --git a/react-color/lib/components/chrome/Chrome.d.ts b/react-color/lib/components/chrome/Chrome.d.ts new file mode 100644 index 0000000000..fa214d1b14 --- /dev/null +++ b/react-color/lib/components/chrome/Chrome.d.ts @@ -0,0 +1,8 @@ +import { Component } from "react"; +import { ColorPickerProps } from "react-color"; + +export interface ChromePickerProps extends ColorPickerProps { + disableAlpha?: boolean; +} + +export default class ChromePicker extends Component {} diff --git a/react-color/lib/components/circle/Circle.d.ts b/react-color/lib/components/circle/Circle.d.ts new file mode 100644 index 0000000000..204842d72a --- /dev/null +++ b/react-color/lib/components/circle/Circle.d.ts @@ -0,0 +1,9 @@ +import { Component } from "react"; +import { ColorPickerProps } from "react-color"; + +export interface CirclePickerProps extends ColorPickerProps { + colors?: string[]; + width?: string; +} + +export default class CirclePicker extends Component {} diff --git a/react-color/lib/components/common/Alpha.d.ts b/react-color/lib/components/common/Alpha.d.ts new file mode 100644 index 0000000000..da20010497 --- /dev/null +++ b/react-color/lib/components/common/Alpha.d.ts @@ -0,0 +1,6 @@ +import { Component } from "react"; +import { CustomPickerProps } from "react-color"; + +export type AlphaProps = CustomPickerProps; + +export default class Alpha extends Component {} diff --git a/react-color/lib/components/common/Checkboard.d.ts b/react-color/lib/components/common/Checkboard.d.ts new file mode 100644 index 0000000000..40d8f26913 --- /dev/null +++ b/react-color/lib/components/common/Checkboard.d.ts @@ -0,0 +1,9 @@ +import { Component, ClassAttributes } from "react"; + +export interface CheckboardProps extends ClassAttributes { + grey?: string; + size?: number; + white?: string; +} + +export default class Checkboard extends Component {} diff --git a/react-color/lib/components/common/ColorWrap.d.ts b/react-color/lib/components/common/ColorWrap.d.ts new file mode 100644 index 0000000000..94a8f5b789 --- /dev/null +++ b/react-color/lib/components/common/ColorWrap.d.ts @@ -0,0 +1,11 @@ +import { ComponentClass, StatelessComponent } from "react"; +import { HSLColor, RGBColor, ColorChangeHandler } from "react-color"; + +export interface InjectedColorProps { + hex?: string; + hsl?: HSLColor; + rgb?: RGBColor; + onChange?: ColorChangeHandler; +} + +export default function CustomPicker(component: ComponentClass | StatelessComponent): ComponentClass; diff --git a/react-color/lib/components/common/EditableInput.d.ts b/react-color/lib/components/common/EditableInput.d.ts new file mode 100644 index 0000000000..78df9473f2 --- /dev/null +++ b/react-color/lib/components/common/EditableInput.d.ts @@ -0,0 +1,19 @@ +import { Component, ClassAttributes, CSSProperties } from "react"; +import { Color, ColorChangeHandler } from "react-color"; + +export interface EditableInputStyles { + input?: CSSProperties; + label?: CSSProperties; + wrap?: CSSProperties; +} + +export interface EditableInputProps extends ClassAttributes { + color?: Color; + label?: string; + onChange?: ColorChangeHandler; + styles?: EditableInputStyles; + value?: any; +} + +export default class EditableInput extends Component {} + diff --git a/react-color/lib/components/common/Hue.d.ts b/react-color/lib/components/common/Hue.d.ts new file mode 100644 index 0000000000..1f61841107 --- /dev/null +++ b/react-color/lib/components/common/Hue.d.ts @@ -0,0 +1,8 @@ +import { Component } from "react"; +import { CustomPickerProps } from "react-color"; + +export interface HueProps extends CustomPickerProps { + direction?: "horizontal" | "vertical"; +} + +export default class Hue extends Component {} diff --git a/react-color/lib/components/common/Saturation.d.ts b/react-color/lib/components/common/Saturation.d.ts new file mode 100644 index 0000000000..c90a7d9685 --- /dev/null +++ b/react-color/lib/components/common/Saturation.d.ts @@ -0,0 +1,6 @@ +import { Component } from "react"; +import { CustomPickerProps } from "react-color"; + +export type SaturationProps = CustomPickerProps; + +export default class Saturation extends Component {} diff --git a/react-color/lib/components/common/index.d.ts b/react-color/lib/components/common/index.d.ts new file mode 100644 index 0000000000..ed5af44bdf --- /dev/null +++ b/react-color/lib/components/common/index.d.ts @@ -0,0 +1,5 @@ +export { default as Alpha } from "react-color/lib/components/common/Alpha"; +export { default as Checkboard } from "react-color/lib/components/common/Checkboard"; +export { default as EditableInput } from "react-color/lib/components/common/EditableInput"; +export { default as Hue } from "react-color/lib/components/common/Hue"; +export { default as Saturation } from "react-color/lib/components/common/Saturation"; diff --git a/react-color/lib/components/compact/Compact.d.ts b/react-color/lib/components/compact/Compact.d.ts new file mode 100644 index 0000000000..3f9ff74f60 --- /dev/null +++ b/react-color/lib/components/compact/Compact.d.ts @@ -0,0 +1,8 @@ +import { Component } from "react"; +import { ColorPickerProps } from "react-color"; + +export interface CompactPickerProps extends ColorPickerProps { + colors?: string[]; +} + +export default class CompactPicker extends Component {} diff --git a/react-color/lib/components/github/Github.d.ts b/react-color/lib/components/github/Github.d.ts new file mode 100644 index 0000000000..fd1479abad --- /dev/null +++ b/react-color/lib/components/github/Github.d.ts @@ -0,0 +1,9 @@ +import { Component } from "react"; +import { ColorPickerProps } from "react-color"; + +export interface GithubPickerProps extends ColorPickerProps { + colors?: string[]; + width?: string; +} + +export default class GithubPicker extends Component {} diff --git a/react-color/lib/components/hue/Hue.d.ts b/react-color/lib/components/hue/Hue.d.ts new file mode 100644 index 0000000000..6aab83baea --- /dev/null +++ b/react-color/lib/components/hue/Hue.d.ts @@ -0,0 +1,9 @@ +import { Component } from "react"; +import { ColorPickerProps } from "react-color"; + +export interface HuePickerProps extends ColorPickerProps { + height?: string; + width?: string; +} + +export default class HuePicker extends Component {} diff --git a/react-color/lib/components/material/Material.d.ts b/react-color/lib/components/material/Material.d.ts new file mode 100644 index 0000000000..4ae849b910 --- /dev/null +++ b/react-color/lib/components/material/Material.d.ts @@ -0,0 +1,6 @@ +import { Component } from "react"; +import { ColorPickerProps } from "react-color"; + +export type MaterialPickerProps = ColorPickerProps; + +export default class MaterialPicker extends Component {} diff --git a/react-color/lib/components/photoshop/Photoshop.d.ts b/react-color/lib/components/photoshop/Photoshop.d.ts new file mode 100644 index 0000000000..c3abaf0ccd --- /dev/null +++ b/react-color/lib/components/photoshop/Photoshop.d.ts @@ -0,0 +1,10 @@ +import { Component } from "react"; +import { ColorChangeHandler, ColorPickerProps } from "react-color"; + +export interface PhotoshopPickerProps extends ColorPickerProps { + header?: string; + onAccept?: ColorChangeHandler; + onCancel?: ColorChangeHandler; +} + +export default class PhotoshopPicker extends Component {} diff --git a/react-color/lib/components/sketch/Sketch.d.ts b/react-color/lib/components/sketch/Sketch.d.ts new file mode 100644 index 0000000000..229b2b2b51 --- /dev/null +++ b/react-color/lib/components/sketch/Sketch.d.ts @@ -0,0 +1,10 @@ +import { Component } from "react"; +import { ColorPickerProps } from "react-color"; + +export interface SketchPickerProps extends ColorPickerProps { + disableAlpha?: boolean; + presetColors?: string[]; + width?: string; +} + +export default class SketchPicker extends Component {} diff --git a/react-color/lib/components/slider/Slider.d.ts b/react-color/lib/components/slider/Slider.d.ts new file mode 100644 index 0000000000..913f30692a --- /dev/null +++ b/react-color/lib/components/slider/Slider.d.ts @@ -0,0 +1,6 @@ +import { Component } from "react"; +import { ColorPickerProps } from "react-color"; + +export type SliderPickerProps = ColorPickerProps; + +export default class SliderPicker extends Component {} diff --git a/react-color/lib/components/swatches/Swatches.d.ts b/react-color/lib/components/swatches/Swatches.d.ts new file mode 100644 index 0000000000..22e9d1704c --- /dev/null +++ b/react-color/lib/components/swatches/Swatches.d.ts @@ -0,0 +1,10 @@ +import { Component } from "react"; +import { ColorPickerProps } from "react-color"; + +export interface SwatchesPickerProps extends ColorPickerProps { + colors?: string[][]; + height?: number; + width?: number; +} + +export default class SwatchesPicker extends Component {} diff --git a/react-color/lib/components/twitter/Twitter.d.ts b/react-color/lib/components/twitter/Twitter.d.ts new file mode 100644 index 0000000000..b4e6bb2308 --- /dev/null +++ b/react-color/lib/components/twitter/Twitter.d.ts @@ -0,0 +1,6 @@ +import { Component } from "react"; +import { ColorPickerProps } from "react-color"; + +export type TwitterPickerProps = ColorPickerProps; + +export default class TwitterPicker extends Component {} diff --git a/react-color/react-color-tests.tsx b/react-color/react-color-tests.tsx index 7969047569..e4e6f2348b 100644 --- a/react-color/react-color-tests.tsx +++ b/react-color/react-color-tests.tsx @@ -5,16 +5,19 @@ import { AlphaPicker, BlockPicker, ChromePicker, CirclePicker, CompactPicker, GithubPicker, HuePicker, MaterialPicker, PhotoshopPicker, SketchPicker, SliderPicker, SwatchesPicker, - TwitterPicker, CustomPicker + TwitterPicker, CustomPicker, InjectedColorProps, ColorResult, + Color } from "react-color" import { Alpha, Checkboard, EditableInput, Hue, Saturation } from "react-color/lib/components/common" -interface CustomProps extends ReactColor.InjectedColorProps { - color?: ReactColor.Color +interface CustomProps extends InjectedColorProps { + color?: Color } var CustomComponent: StatelessComponent = (props: CustomProps) => { - function onChange (color: ReactColor.ColorResult) {} + function onChange (color: ColorResult) { + console.log(color) + } return (
diff --git a/react-color/tsconfig.json b/react-color/tsconfig.json index a88182ffbc..26e01d85c6 100644 --- a/react-color/tsconfig.json +++ b/react-color/tsconfig.json @@ -15,10 +15,32 @@ "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true, - "jsx": "react" + "jsx": "react", + "noUnusedParameters": true, + "noUnusedLocals": true }, "files": [ "index.d.ts", + "lib/components/alpha/Alpha.d.ts", + "lib/components/block/Block.d.ts", + "lib/components/chrome/Chrome.d.ts", + "lib/components/circle/Circle.d.ts", + "lib/components/common/Alpha.d.ts", + "lib/components/common/Checkboard.d.ts", + "lib/components/common/ColorWrap.d.ts", + "lib/components/common/EditableInput.d.ts", + "lib/components/common/Hue.d.ts", + "lib/components/common/index.d.ts", + "lib/components/common/Saturation.d.ts", + "lib/components/compact/Compact.d.ts", + "lib/components/github/Github.d.ts", + "lib/components/hue/Hue.d.ts", + "lib/components/material/Material.d.ts", + "lib/components/photoshop/Photoshop.d.ts", + "lib/components/sketch/Sketch.d.ts", + "lib/components/slider/Slider.d.ts", + "lib/components/swatches/Swatches.d.ts", + "lib/components/twitter/Twitter.d.ts", "react-color-tests.tsx" ] -} \ No newline at end of file +} diff --git a/react-color/tslint.json b/react-color/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/react-color/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/react-dates/index.d.ts b/react-dates/index.d.ts new file mode 100644 index 0000000000..e3ca801887 --- /dev/null +++ b/react-dates/index.d.ts @@ -0,0 +1,364 @@ +// Type definitions for react-dates v7.0.1 +// Project: https://github.com/airbnb/react-dates +// Definitions by: Artur Ampilogov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +import * as React from "react"; +import * as moment from "moment"; + +export = ReactDates; + +declare namespace momentPropTypes{ + type momentObj = any; + type momentString = any; + type momentDurationObj = any; +} + + +declare namespace ReactDates{ + type AnchorDirectionShape = 'left' | 'right'; + type FocusedInputShape = 'startDate' | 'endDate'; + type OrientationShape = 'horizontal' | 'vertical'; + type ScrollableOrientationShape = 'horizontal' | 'vertical' | 'verticalScrollable'; + + + interface DateRangePickerShape{ + startDate?: momentPropTypes.momentObj, + endDate?: momentPropTypes.momentObj, + focusedInput?: FocusedInputShape, + screenReaderInputMessage?: string, + minimumNights?: number, + isDayBlocked?: (day: any) => boolean, + isOutsideRange?: (day: any) => boolean, + enableOutsideDays?: boolean, + reopenPickerOnClearDates?: boolean, + keepOpenOnDateSelect?: boolean, + numberOfMonths?: number, + showClearDates?: boolean, + disabled?: boolean, + required?: boolean, + showDefaultInputIcon?: boolean, + + orientation?: OrientationShape, + anchorDirection?: AnchorDirectionShape, + horizontalMargin?: number, + // portal options + withPortal?: boolean, + withFullScreenPortal?: boolean, + + startDateId?: string, + startDatePlaceholderText?: string, + endDateId?: string, + endDatePlaceholderText?: string, + + initialVisibleMonth?: () => moment.Moment, + onDatesChange?: (arg: { startDate: any, endDate: any }) => void, + onFocusChange?: (arg: FocusedInputShape) => void, + onPrevMonthClick?: (e: React.EventHandler>) => void, + onNextMonthClick?: (e: React.EventHandler>) => void, + + renderDay?: (day: any) => (string | JSX.Element), + + // i18n + displayFormat?: (string | (()=> string)), + monthFormat?: string, + phrases?: { + closeDatePicker: string | JSX.Element, + clearDates: string | JSX.Element, + } + } + + type DateRangePicker = React.ClassicComponentClass; + var DateRangePicker: React.ClassicComponentClass; + + interface SingleDatePickerShape{ + id: string, + placeholder?: string, + date?: momentPropTypes.momentObj, + focused?: boolean, + showClearDate?: boolean, + reopenPickerOnClearDates?: boolean, + keepOpenOnDateSelect?: boolean, + disabled?: boolean, + required?: boolean, + screenReaderInputMessage?: string, + + onDateChange?: (date: any) => void, + onFocusChange?: (arg: { focused: boolean | null }) => void, + + isDayBlocked?: (day: any) => boolean, + isOutsideRange?: (day: any) => boolean, + enableOutsideDays?: boolean, + numberOfMonths?: number, + orientation?: OrientationShape, + initialVisibleMonth?: () => moment.Moment, + anchorDirection?: AnchorDirectionShape, + horizontalMargin?: number, + + navPrev?: string | JSX.Element, + navNext?: string | JSX.Element, + + // portal options + withPortal?: boolean, + withFullScreenPortal?: boolean, + + onPrevMonthClick?: (e: React.EventHandler>) => void, + onNextMonthClick?: (e: React.EventHandler>) => void, + + renderDay?: (day: any) => (string | JSX.Element), + + // i18n + displayFormat?: (string | (()=> string)), + monthFormat?: string, + phrases?: { + closeDatePicker: string | JSX.Element, + }, + } + type SingleDatePicker = React.ClassicComponentClass; + var SingleDatePicker: React.ClassicComponentClass; + + + + interface DateRangePickerInputControllerShape { + startDate?: momentPropTypes.momentObj, + startDateId?: string, + startDatePlaceholderText?: string, + isStartDateFocused?: boolean, + + endDate?: momentPropTypes.momentObj, + endDateId?: string, + endDatePlaceholderText?: string, + isEndDateFocused?: boolean, + + screenReaderMessage?: string, + showClearDates?: boolean, + showCaret?: boolean, + showDefaultInputIcon?: boolean, + disabled?: boolean, + required?: boolean, + + keepOpenOnDateSelect?: boolean, + reopenPickerOnClearDates?: boolean, + withFullScreenPortal?: boolean, + isOutsideRange?: (day: any) => boolean, + displayFormat?: (string | (()=> string)), + + onFocusChange?: (arg: FocusedInputShape) => void, + onDatesChange?: (arg: { startDate: any, endDate: any }) => void, + + customInputIcon?: string | JSX.Element, + customArrowIcon?: string | JSX.Element, + + // i18n + phrases?: { + clearDates: string | JSX.Element, + } + } + type DateRangePickerInputController = React.ClassicComponentClass; + var DateRangePickerInputController: React.ClassicComponentClass; + + + + interface DateRangePickerInputShape{ + startDateId?: string, + startDatePlaceholderText?: string, + screenReaderMessage?: string, + + endDateId?: string, + endDatePlaceholderText?: string, + + onStartDateFocus?: (e: React.EventHandler>) => void, + onEndDateFocus?: (e: React.EventHandler>) => void, + onStartDateChange?: (e: React.EventHandler>) => void, + onEndDateChange?: (e: React.EventHandler>) => void, + onStartDateShiftTab?: (e: React.EventHandler>) => void, + onEndDateTab?: (e: React.EventHandler>) => void, + onClearDates?: (e: React.EventHandler>) => void, + + startDate?: string, + startDateValue?: string, + endDate?: string, + endDateValue?: string, + + isStartDateFocused?: boolean, + isEndDateFocused?: boolean, + showClearDates?: boolean, + disabled?: boolean, + required?: boolean, + showCaret?: boolean, + showDefaultInputIcon?: boolean, + customInputIcon?: string | JSX.Element, + customArrowIcon?: string | JSX.Element, + + // i18n + phrases?:{ + clearDates: string | JSX.Element, + }, + } + type DateRangePickerInput = React.ClassicComponentClass; + var DateRangePickerInput: React.ClassicComponentClass; + + + + interface SingleDatePickerInputShape{ + id: string, + placeholder?: string, // also used as label + displayValue?: string, + inputValue?: string, + screenReaderMessage?: string, + focused?: boolean, + disabled?: boolean, + required?: boolean, + showCaret?: boolean, + showClearDate?: boolean, + + onChange?: (e: React.EventHandler>) => void, + onClearDate?: (e: React.EventHandler>) => void, + onFocus?: (e: React.EventHandler>) => void, + onKeyDownShiftTab?: (e: React.EventHandler>) => void, + onKeyDownTab?: (e: React.EventHandler>) => void, + + // i18n + phrases?: { + clearDate: string | JSX.Element, + } + } + type SingleDatePickerInput = React.ClassicComponentClass; + var SingleDatePickerInput: React.ClassicComponentClass; + + + + + interface DayPickerShape{ + enableOutsideDays?: boolean, + numberOfMonths?: number, + modifiers?: any, + orientation?: ScrollableOrientationShape, + withPortal?: boolean, + hidden?: boolean, + initialVisibleMonth?: () => moment.Moment, + + navPrev?: string | JSX.Element, + navNext?: string | JSX.Element, + + onDayClick?: (day: any, e: React.EventHandler>) => void, + onDayMouseEnter?: (day: any, e: React.EventHandler>) => void, + onDayMouseLeave?: (day: any, e: React.EventHandler>) => void, + onPrevMonthClick?: (e: React.EventHandler>) => void, + onNextMonthClick?: (e: React.EventHandler>) => void, + onOutsideClick?: (e: MouseEvent) => void, + + renderDay?: (day: any) => (string | JSX.Element), + + // i18n + monthFormat?: string, + } + type DayPicker = React.ClassicComponentClass; + var DayPicker: React.ClassicComponentClass; + + + + interface DayPickerRangeControllerShape{ + startDate?: momentPropTypes.momentObj, + endDate?: momentPropTypes.momentObj, + onDatesChange?: (arg: { startDate: any, endDate: any }) => void, + + focusedInput?: FocusedInputShape, + onFocusChange?: (arg: FocusedInputShape) => void, + + keepOpenOnDateSelect?: boolean, + minimumNights?: number, + isOutsideRange?: (day: any) => boolean, + isDayBlocked?: (day: any) => boolean, + isDayHighlighted?: (day: any) => boolean, + + // DayPicker props + enableOutsideDays?: boolean, + numberOfMonths?: number, + orientation?: ScrollableOrientationShape, + withPortal?: boolean, + hidden?: boolean, + initialVisibleMonth?: () => moment.Moment, + + navPrev?: string | JSX.Element, + navNext?: string | JSX.Element, + + onPrevMonthClick?: (e: React.EventHandler>) => void, + onNextMonthClick?: (e: React.EventHandler>) => void, + onOutsideClick?: (e: MouseEvent) => void, + renderDay?: (day: any) => (string | JSX.Element), + + // i18n + monthFormat?: string, + } + type DayPickerRangeController = React.ClassicComponentClass; + var DayPickerRangeController: React.ClassicComponentClass; + + + interface CalendarMonthGridShape{ + enableOutsideDays?: boolean, + firstVisibleMonthIndex?: number, + initialMonth?: momentPropTypes.momentObj, + isAnimating?: boolean, + numberOfMonths?: number, + modifiers?: any, + orientation?: ScrollableOrientationShape, + onDayClick?: (day: any, e: React.EventHandler>) => void, + onDayMouseEnter?: (day: any, e: React.EventHandler>) => void, + onDayMouseLeave?: (day: any, e: React.EventHandler>) => void, + onMonthTransitionEnd?: ()=> void, + renderDay?: (day: any) => (string | JSX.Element), + transformValue?: string, + + // i18n + monthFormat?: string, + } + type CalendarMonthGrid = React.ClassicComponentClass; + var CalendarMonthGrid: React.ClassicComponentClass; + + + + interface CalendarMonthShape{ + month?: momentPropTypes.momentObj, + isVisible?: boolean, + enableOutsideDays?: boolean, + modifiers?: any, + orientation?: ScrollableOrientationShape, + onDayClick?: (day: any, e: React.EventHandler>) => void, + onDayMouseEnter?: (day: any, e: React.EventHandler>) => void, + onDayMouseLeave?: (day: any, e: React.EventHandler>) => void, + renderDay?: (day: any) => (string | JSX.Element), + + // i18n + monthFormat?: string, + } + type CalendarMonth = React.ClassicComponentClass; + var CalendarMonth: React.ClassicComponentClass; + + + interface CalendarDayShape{ + day?: momentPropTypes.momentObj, + isOutsideDay?: boolean, + modifiers?: any, + onDayClick?: (day: any, e: React.EventHandler>) => void, + onDayMouseEnter?: (day: any, e: React.EventHandler>) => void, + onDayMouseLeave?: (day: any, e: React.EventHandler>) => void, + renderDay?: (day: any) => (string | JSX.Element), + } + type CalendarDay = React.ClassicComponentClass; + var CalendarDay: React.ClassicComponentClass; + + + + + var isInclusivelyAfterDay: (a: moment.Moment, b: moment.Moment) => boolean; + var isInclusivelyBeforeDay: (a: moment.Moment, b: moment.Moment) => boolean; + var isNextDay: (a: moment.Moment, b: moment.Moment) => boolean; + var isSameDay: (a: moment.Moment, b: moment.Moment) => boolean; + + var toISODateString: (date: moment.MomentInput, currentFormat: moment.MomentFormatSpecification) => string | null; + var toLocalizedDateString: (date: moment.MomentInput, currentFormat: moment.MomentFormatSpecification) => string | null; + + var toMomentObject: (dateString: moment.MomentInput, customFormat: moment.MomentFormatSpecification) => moment.Moment | null; +} diff --git a/react-dates/package.json b/react-dates/package.json new file mode 100644 index 0000000000..d5ac741601 --- /dev/null +++ b/react-dates/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "moment": ">=2.17.1" + } +} \ No newline at end of file diff --git a/react-dates/react-dates-tests.tsx b/react-dates/react-dates-tests.tsx new file mode 100644 index 0000000000..b975b1124b --- /dev/null +++ b/react-dates/react-dates-tests.tsx @@ -0,0 +1,357 @@ +import * as React from "react"; +import * as moment from "moment"; + +import { + CalendarDay, + CalendarMonth, + CalendarMonthGrid, + SingleDatePickerInput, + SingleDatePicker, + DayPicker, + DayPickerRangeController, + DateRangePickerInput, + DateRangePickerInputController, + DateRangePicker, + isInclusivelyAfterDay, + isInclusivelyBeforeDay, + isNextDay, + isSameDay, + toISODateString, + toLocalizedDateString, + toMomentObject} from "react-dates"; + + +class CalendarDayRenderingMinimumTest extends React.Component<{}, {}> { + render() { + return + } +} + +class CalendarDayRenderingFullTest extends React.Component<{}, {}> { + render() { + return day.toString()} + onDayClick={(day,e) => {}} + onDayMouseEnter={(day,e) => {}} + onDayMouseLeave={(day,e) => {}} + /> + } +} + +class CalendarMonthMinimumTest extends React.Component<{}, {}> { + render() { + return + } +} + +class CalendarMonthFullTest extends React.Component<{}, {}> { + render() { + return day.toString()} + onDayClick={(day,e) => {}} + onDayMouseEnter={(day,e) => {}} + onDayMouseLeave={(day,e) => {}} + /> + } +} + + + + +class SingleDatePickerInputMinimumTest extends React.Component<{}, {}> { + render() { + return + } +} + +class SingleDatePickerInputFullTest extends React.Component<{}, {}> { + render() { + return {}} + onClearDate={e => {}} + onFocus={e => {}} + onKeyDownShiftTab={e => {}} + onKeyDownTab={e => {}} + phrases={{clearDate: "clear"}} + placeholder="test" + required={false} + screenReaderMessage="arial-test" + showCaret={true} + showClearDate={true} + /> + } +} + + + + +class SingleDatePickerMinimumTest extends React.Component<{}, {}> { + render() { + return + } +} + +class SingleDatePickerFullTest extends React.Component<{}, {}> { + render() { + return moment()} + placeholder="test" + required={false} + showClearDate={true} + isDayBlocked={(day:any)=> false} + isOutsideRange={(day:any)=> false} + keepOpenOnDateSelect={true} + navNext="next" + navPrev="prev" + withPortal={false} + onDateChange={d => {}} + focused={false} + phrases={{closeDatePicker: Close}} + reopenPickerOnClearDates={true} + screenReaderInputMessage="arial-test" + withFullScreenPortal={true} + onFocusChange={arg => {}} + onNextMonthClick={e => {}} + onPrevMonthClick={e => {}} + numberOfMonths={2} + orientation="horizontal" + monthFormat="MM" + renderDay={day => day.toString()} + /> + } +} + + + +class DayPickerRangeControllerMinimumTest extends React.Component<{}, {}> { + render() { + return + } +} + +class DayPickerRangeControllerFullTest extends React.Component<{}, {}> { + render() { + return moment()} + hidden={false} + isDayBlocked={(day:any)=> false} + isDayHighlighted={(day:any)=> false} + isOutsideRange={(day:any)=> false} + keepOpenOnDateSelect={true} + minimumNights={3} + navNext="next" + navPrev="prev" + withPortal={false} + onDatesChange={arg => {}} + onFocusChange={arg => {}} + onNextMonthClick={e => {}} + onPrevMonthClick={e => {}} + onOutsideClick={e => {}} + enableOutsideDays={true} + numberOfMonths={2} + orientation="horizontal" + monthFormat="MM" + renderDay={day => day.toString()} + /> + } +} + + +class DayPickerTest extends React.Component<{}, {}> { + render() { + return + } +} + +class DayPickerFullTest extends React.Component<{}, {}> { + render() { + return {}} + onDayMouseEnter={(day,e)=>{}} + onDayMouseLeave={(day,e)=>{}} + initialVisibleMonth={() => moment()} + hidden={false} + navNext="next" + navPrev="prev" + withPortal={false} + onNextMonthClick={e => {}} + onPrevMonthClick={e => {}} + onOutsideClick={e => {}} + enableOutsideDays={true} + numberOfMonths={2} + orientation="horizontal" + monthFormat="MM" + renderDay={day => day.toString()} + /> + } +} + + + + +class DateRangePickerInputMinimumTest extends React.Component<{}, {}> { + render() { + return + } +} + +class DateRangePickerInputFullTest extends React.Component<{}, {}> { + render() { + return {}} + onEndDateChange={e => {}} + onEndDateFocus={e => {}} + onEndDateTab={e => {}} + onStartDateChange={e => {}} + onStartDateFocus={e => {}} + onStartDateShiftTab={e => {}} + showDefaultInputIcon={true} + required={false} + screenReaderMessage="arial-test" + showCaret={true} + showClearDates={true} + phrases={{clearDates: "clear"}} + /> + } +} + + + + + +class DateRangePickerInputControllerMinimumTest extends React.Component<{}, {}> { + render() { + return + } +} + +class DateRangePickerInputControllerFullTest extends React.Component<{}, {}> { + render() { + return {}} + onEndDateChange={e => {}} + onEndDateFocus={e => {}} + onEndDateTab={e => {}} + onStartDateChange={e => {}} + onStartDateFocus={e => {}} + onStartDateShiftTab={e => {}} + showDefaultInputIcon={true} + required={false} + screenReaderMessage="arial-test" + showCaret={true} + showClearDates={true} + phrases={{clearDates: "clear"}} + startDate="1.1.2020" + endDate="1.1.2020" + /> + } +} + + + + + + + + + + + +class DateRangePickerMinimumTest extends React.Component<{}, {}> { + render() { + return + } +} + +class DateRangePickerFullTest extends React.Component<{}, {}> { + render() { + return {arg.startDate; arg.endDate;}} + displayFormat="dd.mm.yyyy" + enableOutsideDays={true} + horizontalMargin={20} + initialVisibleMonth={() => moment()} + isDayBlocked={(day:any)=> false} + isOutsideRange={(day:any)=> false} + keepOpenOnDateSelect={true} + withPortal={false} + reopenPickerOnClearDates={true} + screenReaderInputMessage="arial-test" + withFullScreenPortal={true} + onFocusChange={arg => {}} + onNextMonthClick={e => {}} + onPrevMonthClick={e => {}} + numberOfMonths={2} + orientation="horizontal" + monthFormat="MM" + renderDay={day => day.toString()} + /> + } +} + + +const isInclusivelyAfterDayResult: boolean = isInclusivelyAfterDay(moment(),moment()); +const isInclusivelyBeforeDayResult: boolean = isInclusivelyBeforeDay(moment(),moment()); +const isNextDayDayResult: boolean = isNextDay(moment(),moment()); +const isSameDayResult: boolean = isSameDay(moment(),moment()); +const toISODateStringResult: string | null = toISODateString(moment(), "dd.mm.yyyy"); +const toLocalizedDateStringResult: string | null = toLocalizedDateString(moment(), "dd.mm.yyyy"); +const toMomentObjectResult: moment.Moment | null = toMomentObject(moment(), "dd.mm.yyyy"); + + \ No newline at end of file diff --git a/antd/tsconfig.json b/react-dates/tsconfig.json similarity index 86% rename from antd/tsconfig.json rename to react-dates/tsconfig.json index 6b7785ac6c..7d246baede 100644 --- a/antd/tsconfig.json +++ b/react-dates/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "jsx": "react", "typeRoots": [ @@ -19,6 +19,6 @@ }, "files": [ "index.d.ts", - "antd-tests.tsx" + "react-dates-tests.tsx" ] -} \ No newline at end of file +} diff --git a/react-ga/react-ga-tests.tsx b/react-ga/react-ga-tests.tsx index 10770f04f5..0db1be21c2 100644 --- a/react-ga/react-ga-tests.tsx +++ b/react-ga/react-ga-tests.tsx @@ -1,7 +1,8 @@ -/// - import * as ga from "react-ga"; +declare function describe(desc: string, f: () => void): void; +declare function it(desc: string, f: () => void): void; + describe("Testing react-ga initialize object", () => { it("Able to initialize react-ga object", () => { ga.initialize("UA-65432-1"); diff --git a/react-highlighter/index.d.ts b/react-highlighter/index.d.ts index 74468c9b7c..6e34a4dbe3 100644 --- a/react-highlighter/index.d.ts +++ b/react-highlighter/index.d.ts @@ -2,6 +2,9 @@ // Project: https://github.com/helior/react-highlighter // Definitions by: Pedro Pereira // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// declare var Highlight: any; export = Highlight; diff --git a/react-native/index.d.ts b/react-native/index.d.ts index 2f95939db6..d18d311fa3 100644 --- a/react-native/index.d.ts +++ b/react-native/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-native 0.37 +// Type definitions for react-native 0.42 // Project: https://github.com/facebook/react-native // Definitions by: Needs A Maintainer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -5413,11 +5413,6 @@ declare module "react" { */ onScrollAnimationEnd?: () => void - /** - * When false, the content does not scroll. The default value is true - */ - scrollEnabled?: boolean // true - /** * This controls how often the scroll event will be fired while scrolling (in events per seconds). * A higher number yields better accuracy for code that is tracking the scroll position, @@ -5452,7 +5447,7 @@ declare module "react" { * This can be used for paginating through children that have lengths smaller than the scroll view. * Used in combination with snapToAlignment. */ - snapToInterval?: number + snapToInterval?: number[] /** * An array of child indices determining which children get docked to the @@ -5489,6 +5484,15 @@ declare module "react" { */ scrollPerfTag?: string + /** + * Used to override default value of overScroll mode. + + * Possible values: + * - 'auto' - Default value, allow a user to over-scroll this view only if the content is large enough to meaningfully scroll. + * - 'always' - Always allow a user to over-scroll this view. + * - 'never' - Never allow a user to over-scroll this view. + */ + overScrollMode?: 'auto' | 'always' | 'never' } export interface ScrollViewProperties extends ViewProperties, ScrollViewPropertiesIOS, ScrollViewPropertiesAndroid, Touchable, React.Props { @@ -5524,7 +5528,7 @@ declare module "react" { * and moves in synchrony with the touch; dragging upwards cancels the * dismissal. */ - keyboardDismissMode?: string + keyboardDismissMode?: 'none' | 'interactive' | 'on-drag' /** * When false tapping outside of the focused text input when the keyboard @@ -5532,16 +5536,16 @@ declare module "react" { * taps and the keyboard will not dismiss automatically. The default value * is false. */ - keyboardShouldPersistTaps?: boolean - - /** - * Called when scrollable content view of the ScrollView changes. - * Handler function is passed the content width and content height as parameters: (contentWidth, contentHeight) - * It's implemented using onLayout handler attached to the content container which this ScrollView renders. - * - */ - onContentSizeChange?: (w: number, h: number) => void - + keyboardShouldPersistTaps?: boolean | 'always' | 'never' | 'handled' + + /** + * Called when scrollable content view of the ScrollView changes. + * Handler function is passed the content width and content height as parameters: (contentWidth, contentHeight) + * It's implemented using onLayout handler attached to the content container which this ScrollView renders. + * + */ + onContentSizeChange?: (w: number, h: number) => void + /** * Fires at most once per frame during scrolling. * The frequency of the events can be contolled using the scrollEventThrottle prop. @@ -5575,6 +5579,11 @@ declare module "react" { */ pagingEnabled?: boolean + /** + * When false, the content does not scroll. The default value is true + */ + scrollEnabled?: boolean // true + /** * Experimental: When true offscreen child views (whose `overflow` value is * `hidden`) are removed from their native backing superview when offscreen. diff --git a/react-redux/index.d.ts b/react-redux/index.d.ts index 2d76aaac00..8daa310b51 100644 --- a/react-redux/index.d.ts +++ b/react-redux/index.d.ts @@ -49,14 +49,9 @@ export interface InferableComponentDecorator { export declare function connect(): InferableComponentDecorator; export declare function connect( - mapStateToProps: FuncOrSelf>, - mapDispatchToProps?: FuncOrSelf | MapDispatchToPropsObject> -): ComponentDecorator; - -export declare function connect( - mapStateToProps: FuncOrSelf>, - mapDispatchToProps: FuncOrSelf | MapDispatchToPropsObject>, - mergeProps: MergeProps, + mapStateToProps?: FuncOrSelf>, + mapDispatchToProps?: FuncOrSelf | MapDispatchToPropsObject>, + mergeProps?: MergeProps, options?: Options ): ComponentDecorator; diff --git a/react-redux/react-redux-tests.tsx b/react-redux/react-redux-tests.tsx index bbe84289ff..5d1f32765f 100644 --- a/react-redux/react-redux-tests.tsx +++ b/react-redux/react-redux-tests.tsx @@ -258,8 +258,9 @@ function mergeProps(stateProps: TodoState, dispatchProps: DispatchProps, ownProp connect(mapStateToProps2, actionCreators, mergeProps)(TodoApp); - - +//https://github.com/DefinitelyTyped/DefinitelyTyped/issues/14622#issuecomment-279820358 +//Allow for undefined mapStateToProps +connect(undefined, mapDispatchToProps6)(TodoApp); interface TestProp { property1: number; diff --git a/react/index.d.ts b/react/index.d.ts index 234e3ec4f7..d3c254f875 100644 --- a/react/index.d.ts +++ b/react/index.d.ts @@ -242,10 +242,10 @@ declare namespace React { interface ComponentLifecycle { componentWillMount?(): void; componentDidMount?(): void; - componentWillReceiveProps?(nextProps: P, nextContext: any): void; - shouldComponentUpdate?(nextProps: P, nextState: S, nextContext: any): boolean; - componentWillUpdate?(nextProps: P, nextState: S, nextContext: any): void; - componentDidUpdate?(prevProps: P, prevState: S, prevContext: any): void; + componentWillReceiveProps?(nextProps: Readonly

, nextContext: any): void; + shouldComponentUpdate?(nextProps: Readonly

, nextState: Readonly, nextContext: any): boolean; + componentWillUpdate?(nextProps: Readonly

, nextState: Readonly, nextContext: any): void; + componentDidUpdate?(prevProps: Readonly

, prevState: Readonly, prevContext: any): void; componentWillUnmount?(): void; } diff --git a/redux-form/index.d.ts b/redux-form/index.d.ts index 590fe3a633..f36162d684 100644 --- a/redux-form/index.d.ts +++ b/redux-form/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for redux-form v6.3.1 +// Type definitions for redux-form v6.3.3 // Project: https://github.com/erikras/redux-form -// Definitions by: Carson Full , Daniel Lytkin +// Definitions by: Carson Full // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 diff --git a/redux-form/lib/reduxForm.d.ts b/redux-form/lib/reduxForm.d.ts index 512797a39c..dc13fa9a9b 100644 --- a/redux-form/lib/reduxForm.d.ts +++ b/redux-form/lib/reduxForm.d.ts @@ -48,14 +48,14 @@ export interface Config { asyncBlurFields?: string[]; /** - * a function that takes all the form values, the dispatch function, and - * the props given to your component, and returns a Promise that will - * resolve if the validation is passed, or will reject with an object of - * validation errors in the form { field1: , field2: }. + * a function that takes all the form values, the dispatch function, + * the props given to your component and the current blurred field, + * and returns a Promise that will resolve if the validation is passed, + * or will reject with an object of validation errors in the form { field1: , field2: }. * * See Asynchronous Blur Validation Example for more details. */ - asyncValidate?(values: FormData, dispatch: Dispatch, props: P): Promise; + asyncValidate?(values: FormData, dispatch: Dispatch, props: P, blurredField: string): Promise; /** * Whether or not to automatically destroy your form's state in the Redux diff --git a/redux-ui/index.d.ts b/redux-ui/index.d.ts index 3b1f8f4a58..1c3468233d 100644 --- a/redux-ui/index.d.ts +++ b/redux-ui/index.d.ts @@ -2,7 +2,9 @@ // Project: https://github.com/tonyhb/redux-ui // Definitions by: Andy Shu Xin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 +/// import * as Redux from 'redux'; export interface uiParams { diff --git a/reflux/reflux-tests.ts b/reflux/reflux-tests.ts index 7a392282fa..150e40db03 100644 --- a/reflux/reflux-tests.ts +++ b/reflux/reflux-tests.ts @@ -1,5 +1,4 @@ import Reflux = require("reflux"); -import React = require("react"); var syncActions = Reflux.createActions([ "statusUpdate", diff --git a/request/index.d.ts b/request/index.d.ts index d576c82e3b..e65c8308d6 100644 --- a/request/index.d.ts +++ b/request/index.d.ts @@ -145,6 +145,7 @@ declare namespace request { export interface RequestResponse extends http.IncomingMessage { request: Options; + body: any; } export interface HttpArchiveRequest { diff --git a/samchon-framework/index.d.ts b/samchon-framework/index.d.ts index 558efd674a..fa540e033d 100644 --- a/samchon-framework/index.d.ts +++ b/samchon-framework/index.d.ts @@ -1,10811 +1,13 @@ -// Type definitions for Samchon Framework 2.0 +// Type definitions for Samchon Framework v2.0.x // Project: https://github.com/samchon/framework // Definitions by: Jeongho Nam // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// +// Samchon-Framework is renamed to Samchon declare module "samchon-framework" { + import samchon = require("samchon"); export = samchon; -} - -/** - * # Samchon-Framework - * - * - * - * - * Samchon, a OON (Object-Oriented Network) framework. - * - * With Samchon Framework, you can implement distributed processing system within framework of OOD like handling S/W - * objects (classes). You can realize cloud and distributed system very easily with provided system templates and even - * integration with C++ is possible. - * - * The goal, ultimate utilization model of Samchon Framework is, building cloud system with NodeJS and taking heavy works - * to C++ distributed systems with provided modules (those are system templates). - * - * @git https://github.com/samchon/framework - * @author Jeongho Nam - */ -declare namespace samchon { - /** - * Running on Node. - * - * Test whether the JavaScript is running on Node. - * - * @references http://stackoverflow.com/questions/17575790/environment-detection-node-js-or-browser - */ - function is_node(): boolean; -} -declare namespace samchon.collections { - /** - * A {@link Vector} who can detect element I/O events. - * - * Below is the list of methods who are dispatching {@link CollectionEvent}: - * - *insert* typed events: - * - {@link assign} - * - {@link insert} - * - {@link push} - * - {@link push_back} - * - {@link unshift} - * - *erase* typed events: - * - {@link assign} - * - {@link clear} - * - {@link erase} - * - {@link pop_back} - * - {@link shift} - * - {@link pop} - * - {@link splice} - * - *refresh* typed events: - * - {@link refresh} - * - * #### [Inherited] {@link Vector} - * {@link Vector Vectors}s are sequence containers representing arrays that can change in size. - * - * Just like arrays, {@link Vector}s use contiguous storage locations for their elements, which means that their - * elements can also be accessed using offsets on regular pointers to its elements, and just as efficiently as in - * arrays. But unlike arrays, their size can change dynamically, with their storage being handled automatically - * by the container. - * - * Internally, {@link Vector}s use a dynamically allocated array to store their elements. This array may need to - * be reallocated in order to grow in size when new elements are inserted, which implies allocating a new array - * and moving all elements to it. This is a relatively expensive task in terms of processing time, and thus, - * {@link Vector}s do not reallocate each time an element is added to the container. - * - * Instead, {@link Vector} containers may allocate some extra storage to accommodate for possible growth, and - * thus the container may have an actual {@link capacity} greater than the storage strictly needed to contain its - * elements (i.e., its {@link size}). Libraries can implement different strategies for growth to balance between - * memory usage and reallocations, but in any case, reallocations should only happen at logarithmically growing - * intervals of {@link size} so that the insertion of individual elements at the end of the {@link Vector} can be - * provided with amortized constant time complexity (see {@link push_back push_back()}). - * - * Therefore, compared to arrays, {@link Vector}s consume more memory in exchange for the ability to manage - * storage and grow dynamically in an efficient way. - * - * Compared to the other dynamic sequence containers ({@link Deque}s, {@link List}s), {@link Vector Vectors} are - * very efficient accessing its elements (just like arrays) and relatively efficient adding or removing elements - * from its end. For operations that involve inserting or removing elements at positions other than the end, they - * perform worse than the others, and have less consistent iterators and references than {@link List}s. - * - * - * - * - * - *

Container properties

- *
- *
Sequence
- *
- * Elements in sequence containers are ordered in a strict linear sequence. Individual elements are - * accessed by their position in this sequence. - *
- * - *
Dynamic array
- *
- * Allows direct access to any element in the sequence, even through pointer arithmetics, and provides - * relatively fast addition/removal of elements at the end of the sequence. - *
- *
- * - * @param Type of the elements. - * - * @reference http://www.cplusplus.com/reference/vector/vector - * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) - * @author Jeongho Nam - */ - class ArrayCollection extends std.Vector implements ICollection { - /** - * A chain object taking responsibility of dispatching events. - */ - private event_dispatcher_; - /** - * @inheritdoc - */ - push(...items: T[]): number; - /** - * @inheritdoc - */ - push_back(val: T): void; - /** - * @hidden - */ - protected _Insert_by_repeating_val(position: std.VectorIterator, n: number, val: T): std.VectorIterator; - /** - * @hidden - */ - protected _Insert_by_range>(position: std.VectorIterator, begin: InputIterator, end: InputIterator): std.VectorIterator; - /** - * @hidden - */ - protected _Erase_by_range(first: std.VectorIterator, last: std.VectorIterator): std.VectorIterator; - /** - * @hidden - */ - private notify_insert(first, last); - /** - * @hidden - */ - private notify_erase(first, last); - /** - * @inheritdoc - */ - hasEventListener(type: string): boolean; - /** - * @inheritdoc - */ - dispatchEvent(event: library.BasicEvent): boolean; - /** - * @inheritdoc - */ - refresh(): void; - /** - * @inheritdoc - */ - refresh(it: std.VectorIterator): void; - /** - * @inheritdoc - */ - refresh(first: std.VectorIterator, last: std.VectorIterator): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener): void; - addEventListener(type: "insert", listener: CollectionEventListener): void; - addEventListener(type: "erase", listener: CollectionEventListener): void; - addEventListener(type: "refresh", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; - addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; - addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener): void; - removeEventListener(type: "insert", listener: CollectionEventListener): void; - removeEventListener(type: "erase", listener: CollectionEventListener): void; - removeEventListener(type: "refresh", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; - removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; - removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - unshift(...items: U[]): number; - /** - * @inheritdoc - */ - pop(): T; - /** - * @inheritdoc - */ - splice(start: number): T[]; - /** - * @inheritdoc - */ - splice(start: number, deleteCount: number, ...items: T[]): T[]; - } -} -declare namespace samchon.library { - /** - * A basic event class of Samchon Framework. - * - * @reference https://developer.mozilla.org/en-US/docs/Web/API/Event - * @handbook https://github.com/samchon/framework/wiki/TypeScript-Library-EventDispatcher - * @author Jeongho Nam - */ - class BasicEvent { - protected type_: string; - protected target_: IEventDispatcher; - private currentTarget_; - protected trusted_: boolean; - protected bubbles_: boolean; - protected cancelable_: boolean; - protected defaultPrevented_: boolean; - protected cancelBubble_: boolean; - private timeStamp_; - constructor(type: string, bubbles?: boolean, cancelable?: boolean); - /** - * @inheritdoc - */ - initEvent(type: string, bubbles: boolean, cancelable: boolean): void; - /** - * @inheritdoc - */ - /** - * @inheritdoc - */ - stopImmediatePropagation(): void; - /** - * @inheritdoc - */ - stopPropagation(): void; - /** - * @inheritdoc - */ - readonly type: string; - /** - * @inheritdoc - */ - target: IEventDispatcher; - /** - * @inheritdoc - */ - readonly currentTarget: IEventDispatcher; - /** - * @inheritdoc - */ - readonly isTrusted: boolean; - /** - * @inheritdoc - */ - readonly bubbles: boolean; - /** - * @inheritdoc - */ - readonly cancelable: boolean; - /** - * @inheritdoc - */ - readonly eventPhase: number; - /** - * @inheritdoc - */ - readonly defaultPrevented: boolean; - /** - * @inheritdoc - */ - readonly srcElement: Element; - /** - * @inheritdoc - */ - readonly cancelBubble: boolean; - /** - * @inheritdoc - */ - readonly timeStamp: number; - /** - * Don't know what it is. - */ - readonly returnValue: boolean; - } -} -declare namespace samchon.collections { - /** - * Type of function pointer for listener of {@link CollectionEvent CollectionEvents}. - */ - type CollectionEventListener = (event: CollectionEvent) => void; -} -declare namespace samchon.collections { - /** - * An event occured in a {@link ICollection collection} object. - * - * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) - * @author Jeongho Nam - */ - class CollectionEvent extends library.BasicEvent { - /** - * @hidden - */ - private first_; - /** - * @hidden - */ - private last_; - /** - * @hidden - */ - private temporary_container_; - /** - * @hidden - */ - private origin_first_; - /** - * Initialization Constructor. - * - * @param type Type of collection event. - * @param first An {@link Iterator} to the initial position in this {@link CollectionEvent}. - * @param last An {@link Iterator} to the final position in this {@link CollectionEvent}. - */ - constructor(type: string, first: std.Iterator, last: std.Iterator); - constructor(type: "insert", first: std.Iterator, last: std.Iterator); - constructor(type: "erase", first: std.Iterator, last: std.Iterator); - constructor(type: "refresh", first: std.Iterator, last: std.Iterator); - /** - * Associative target, the {@link ICollection collection}. - */ - readonly target: ICollection; - /** - * An {@link Iterator} to the initial position in this {@link CollectionEvent}. - */ - readonly first: std.Iterator; - /** - * An {@link Iterator} to the final position in this {@link CollectionEvent}. - */ - readonly last: std.Iterator; - /** - * @inheritdoc - */ - preventDefault(): void; - } -} -declare namespace samchon.collections.CollectionEvent { - const INSERT: "insert"; - const ERASE: "erase"; - const REFRESH: "refresh"; -} -declare namespace samchon.collections { - /** - * A {@link Deque} who can detect element I/O events. - * - * Below is the list of methods who are dispatching {@link CollectionEvent}: - * - *insert* typed events: - * - {@link assign} - * - {@link insert} - * - {@link push} - * - {@link push_front} - * - {@link push_back} - * - *erase* typed events: - * - {@link assign} - * - {@link clear} - * - {@link erase} - * - {@link pop_front} - * - {@link pop_back} - * - *refresh* typed events: - * - {@link refresh} - * - * #### [Inherited] {@link Deque} - * {@link Deque} (usually pronounced like "*deck*") is an irregular acronym of **d**ouble-**e**nded **q**ueue. - * Double-ended queues are sequence containers with dynamic sizes that can be expanded or contracted on both ends - * (either its front or its back). - * - * Specific libraries may implement deques in different ways, generally as some form of dynamic array. But in any - * case, they allow for the individual elements to be accessed directly through random access iterators, with - * storage handled automatically by expanding and contracting the container as needed. - * - * Therefore, they provide a functionality similar to vectors, but with efficient insertion and deletion of - * elements also at the beginning of the sequence, and not only at its end. But, unlike {@link Vector Vectors}, - * {@link Deque Deques} are not guaranteed to store all its elements in contiguous storage locations: accessing - * elements in a deque by offsetting a pointer to another element causes undefined behavior. - * - * Both {@link Vector}s and {@link Deque}s provide a very similar interface and can be used for similar purposes, - * but internally both work in quite different ways: While {@link Vector}s use a single array that needs to be - * occasionally reallocated for growth, the elements of a {@link Deque} can be scattered in different chunks of - * storage, with the container keeping the necessary information internally to provide direct access to any of its - * elements in constant time and with a uniform sequential interface (through iterators). Therefore, - * {@link Deque Deques} are a little more complex internally than {@link Vector}s, but this allows them to grow - * more efficiently under certain circumstances, especially with very long sequences, where reallocations become - * more expensive. - * - * For operations that involve frequent insertion or removals of elements at positions other than the beginning or - * the end, {@link Deque Deques} perform worse and have less consistent iterators and references than - * {@link List Lists}. - * - * - * - * - * - *

Container properties

- *
- *
Sequence
- *
Elements in sequence containers are ordered in a strict linear sequence. Individual elements - * are accessed by their position in this sequence.
- * - *
Dynamic array
- *
Generally implemented as a dynamic array, it allows direct access to any element in the - * sequence and provides relatively fast addition/removal of elements at the beginning or the end - * of the sequence.
- *
- * - * @param Type of the elements. - * - * @reference http://www.cplusplus.com/reference/deque/deque/ - * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) - * @author Jeongho Nam - */ - class DequeCollection extends std.Deque implements ICollection { - /** - * A chain object taking responsibility of dispatching events. - */ - private event_dispatcher_; - /** - * @inheritdoc - */ - push(...items: T[]): number; - /** - * @inheritdoc - */ - push_back(val: T): void; - /** - * @hidden - */ - protected _Insert_by_repeating_val(position: std.DequeIterator, n: number, val: T): std.DequeIterator; - /** - * @hidden - */ - protected _Insert_by_range>(position: std.DequeIterator, begin: InputIterator, end: InputIterator): std.DequeIterator; - /** - * @inheritdoc - */ - pop_back(): void; - /** - * @hidden - */ - protected _Erase_by_range(first: std.DequeIterator, last: std.DequeIterator): std.DequeIterator; - /** - * @hidden - */ - private notify_insert(first, last); - /** - * @hidden - */ - private notify_erase(first, last); - /** - * @inheritdoc - */ - hasEventListener(type: string): boolean; - /** - * @inheritdoc - */ - dispatchEvent(event: library.BasicEvent): boolean; - /** - * @inheritdoc - */ - refresh(): void; - /** - * @inheritdoc - */ - refresh(it: std.DequeIterator): void; - /** - * @inheritdoc - */ - refresh(first: std.DequeIterator, last: std.DequeIterator): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener): void; - addEventListener(type: "insert", listener: CollectionEventListener): void; - addEventListener(type: "erase", listener: CollectionEventListener): void; - addEventListener(type: "refresh", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; - addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; - addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener): void; - removeEventListener(type: "insert", listener: CollectionEventListener): void; - removeEventListener(type: "erase", listener: CollectionEventListener): void; - removeEventListener(type: "refresh", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; - removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; - removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; - } -} -declare namespace samchon.collections { - /** - * A {@link HashMap} who can detect element I/O events. - * - * Below is the list of methods who are dispatching {@link MapCollectionEvent}: - * - *insert* typed events: - * - {@link assign} - * - {@link insert} - * - {@link insert_or_assign} - * - {@link emplace} - * - {@link set} - * - {@link push} - * - *erase* typed events: - * - {@link assign} - * - {@link clear} - * - {@link erase} - * - {@link extract} - * - *refresh* typed events: - * - {@link refresh} - * - * #### [Inherited] {@link HashMap} - * {@link HashMap HashMaps} are associative containers that store elements formed by the combination of a - * *key value* and a *mapped value*, and which allows for fast retrieval of individual elements based on their - * *keys*. - * - * In an {@link HashMap}, the *key value* is generally used to uniquely identify the element, while the - * *mapped value* is an object with the content associated to this *key*. Types of *key* and *mapped value* may - * differ. - * - * Internally, the elements in the {@link HashMap} are not sorted in any particular order with respect to either - * their *key* or *mapped values*, but organized into *buckets* depending on their hash values to allow for fast - * access to individual elements directly by their *key values* (with a constant average time complexity on - * average). - * - * {@link HashMap} containers are faster than {@link TreeMap} containers to access individual elements by their - * *key*, although they are generally less efficient for range iteration through a subset of their elements. - * - * - * - * - * - *

Container properties

- *
- *
Associative
- *
Elements in associative containers are referenced by their *key* and not by their absolute - * position in the container.
- * - *
Hashed
- *
Hashed containers organize their elements using hash tables that allow for fast access to elements - * by their *key*.
- * - *
Map
- *
Each element associates a *key* to a *mapped value*: - * *Keys* are meant to identify the elements whose main content is the *mapped value*.
- * - *
Unique keys
- *
No two elements in the container can have equivalent keys.
- *
- * - * @param Type of the key values. - * Each element in an {@link HashMap} is uniquely identified by its key value. - * @param Type of the mapped value. - * Each element in an {@link HashMap} is used to store some data as its mapped value. - * - * @reference http://www.cplusplus.com/reference/unordered_map/unordered_map - * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) - * @author Jeongho Nam - */ - class HashMapCollection extends std.HashMap implements ICollection> { - /** - * A chain object taking responsibility of dispatching events. - */ - private event_dispatcher_; - /** - * @inheritdoc - */ - protected _Handle_insert(first: std.MapIterator, last: std.MapIterator): void; - /** - * @inheritdoc - */ - protected _Handle_erase(first: std.MapIterator, last: std.MapIterator): void; - /** - * @inheritdoc - */ - hasEventListener(type: string): boolean; - /** - * @inheritdoc - */ - dispatchEvent(event: library.BasicEvent): boolean; - /** - * @inheritdoc - */ - refresh(): void; - /** - * @inheritdoc - */ - refresh(it: std.MapIterator): void; - /** - * @inheritdoc - */ - refresh(first: std.MapIterator, last: std.MapIterator): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener): void; - addEventListener(type: "insert", listener: MapCollectionEventListener): void; - addEventListener(type: "erase", listener: MapCollectionEventListener): void; - addEventListener(type: "refresh", listener: MapCollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - addEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; - addEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; - addEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener): void; - removeEventListener(type: "insert", listener: MapCollectionEventListener): void; - removeEventListener(type: "erase", listener: MapCollectionEventListener): void; - removeEventListener(type: "refresh", listener: MapCollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - removeEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; - removeEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; - removeEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; - } -} -declare namespace samchon.collections { - /** - * A {@link HashMultiMap} who can detect element I/O events. - * - * Below is the list of methods who are dispatching {@link MapCollectionEvent}: - * - *insert* typed events: - * - {@link assign} - * - {@link insert} - * - {@link emplace} - * - {@link push} - * - *erase* typed events: - * - {@link assign} - * - {@link clear} - * - {@link erase} - * - *refresh* typed events: - * - {@link refresh} - * - * #### [Inherited] {@link HashMultiMap} - * {@link HashMultiMap HashMultiMap}s are associative containers that store elements formed by the combination of - * a *key value* and a *mapped value*, much like {@link HashMultiMap} containers, but allowing different elements - * to have equivalent *keys*. - * - * In an {@link HashMultiMap}, the *key value* is generally used to uniquely identify the element, while the - * *mapped value* is an object with the content associated to this *key*. Types of *key* and *mapped value* may - * differ. - * - * Internally, the elements in the {@link HashMultiMap} are not sorted in any particular order with respect to - * either their *key* or *mapped values*, but organized into *buckets* depending on their hash values to allow for - * fast access to individual elements directly by their *key values* (with a constant average time complexity on - * average). - * - * Elements with equivalent *keys* are grouped together in the same bucket and in such a way that an iterator can - * iterate through all of them. Iterators in the container are doubly linked iterators. - * - * - * - * - * - *

Container properties

- *
- *
Associative
- *
Elements in associative containers are referenced by their *key* and not by their absolute - * position in the container.
- * - *
Hashed
- *
Hashed containers organize their elements using hash tables that allow for fast access to elements - * by their *key*.
- * - *
Map
- *
Each element associates a *key* to a *mapped value*: - * *Keys* are meant to identify the elements whose main content is the *mapped value*.
- * - *
Multiple equivalent keys
- *
The container can hold multiple elements with equivalent *keys*.
- *
- * - * @param Type of the key values. - * Each element in an {@link HashMultiMap} is identified by a key value. - * @param Type of the mapped value. - * Each element in an {@link HashMultiMap} is used to store some data as its mapped value. - * - * @reference http://www.cplusplus.com/reference/unordered_map/unordered_multimap - * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) - * @author Jeongho Nam - */ - class HashMultiMapCollection extends std.HashMap implements ICollection> { - /** - * A chain object taking responsibility of dispatching events. - */ - private event_dispatcher_; - /** - * @inheritdoc - */ - protected _Handle_insert(first: std.MapIterator, last: std.MapIterator): void; - /** - * @inheritdoc - */ - protected _Handle_erase(first: std.MapIterator, last: std.MapIterator): void; - /** - * @inheritdoc - */ - hasEventListener(type: string): boolean; - /** - * @inheritdoc - */ - dispatchEvent(event: library.BasicEvent): boolean; - /** - * @inheritdoc - */ - refresh(): void; - /** - * @inheritdoc - */ - refresh(it: std.MapIterator): void; - /** - * @inheritdoc - */ - refresh(first: std.MapIterator, last: std.MapIterator): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener): void; - addEventListener(type: "insert", listener: MapCollectionEventListener): void; - addEventListener(type: "erase", listener: MapCollectionEventListener): void; - addEventListener(type: "refresh", listener: MapCollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - addEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; - addEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; - addEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener): void; - removeEventListener(type: "insert", listener: MapCollectionEventListener): void; - removeEventListener(type: "erase", listener: MapCollectionEventListener): void; - removeEventListener(type: "refresh", listener: MapCollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - removeEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; - removeEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; - removeEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; - } -} -declare namespace samchon.collections { - /** - * A {@link HashMultiSet} who can detect element I/O events. - * - * Below is the list of methods who are dispatching {@link CollectionEvent}: - * - *insert* typed events: - * - {@link assign} - * - {@link insert} - * - {@link push} - * - *erase* typed events: - * - {@link assign} - * - {@link clear} - * - {@link erase} - * - *refresh* typed events: - * - {@link refresh} - * - * #### [Inherited] {@link HashMultiSet} - * {@link HashMultiSet HashMultiSets} are containers that store elements in no particular order, allowing fast - * retrieval of individual elements based on their value, much like {@link HashMultiSet} containers, but allowing - * different elements to have equivalent values. - * - * In an {@link HashMultiSet}, the value of an element is at the same time its *key*, used to identify it. *Keys* - * are immutable, therefore, the elements in an {@link HashMultiSet} cannot be modified once in the container - - * they can be inserted and removed, though. - * - * Internally, the elements in the {@link HashMultiSet} are not sorted in any particular, but organized into - * *buckets* depending on their hash values to allow for fast access to individual elements directly by their - * *values* (with a constant average time complexity on average). - * - * Elements with equivalent values are grouped together in the same bucket and in such a way that an iterator can - * iterate through all of them. Iterators in the container are doubly linked iterators. - * - * - * - * - * - *

Container properties

- *
- *
Associative
- *
Elements in associative containers are referenced by their *key* and not by their absolute - * position in the container.
- * - *
Hashed
- *
Hashed containers organize their elements using hash tables that allow for fast access to elements - * by their *key*.
- * - *
Set
- *
The value of an element is also the *key* used to identify it.
- * - *
Multiple equivalent keys
- *
The container can hold multiple elements with equivalent *keys*.
- *
- * - * @param Type of the elements. - * Each element in an {@link UnorderedMultiSet} is also identified by this value.. - * - * @reference http://www.cplusplus.com/reference/unordered_set/unordered_multiset - * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) - * @author Jeongho Nam - */ - class HashMultiSetCollection extends std.HashMultiSet implements ICollection { - /** - * A chain object taking responsibility of dispatching events. - */ - private event_dispatcher_; - /** - * @inheritdoc - */ - protected _Handle_insert(first: std.SetIterator, last: std.SetIterator): void; - /** - * @inheritdoc - */ - protected _Handle_erase(first: std.SetIterator, last: std.SetIterator): void; - /** - * @inheritdoc - */ - hasEventListener(type: string): boolean; - /** - * @inheritdoc - */ - dispatchEvent(event: library.BasicEvent): boolean; - /** - * @inheritdoc - */ - refresh(): void; - /** - * @inheritdoc - */ - refresh(it: std.SetIterator): void; - /** - * @inheritdoc - */ - refresh(first: std.SetIterator, last: std.SetIterator): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener): void; - addEventListener(type: "insert", listener: CollectionEventListener): void; - addEventListener(type: "erase", listener: CollectionEventListener): void; - addEventListener(type: "refresh", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; - addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; - addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener): void; - removeEventListener(type: "insert", listener: CollectionEventListener): void; - removeEventListener(type: "erase", listener: CollectionEventListener): void; - removeEventListener(type: "refresh", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; - removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; - removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; - } -} -declare namespace samchon.collections { - /** - * A {@link HashSet} who can detect element I/O events. - * - * Below is the list of methods who are dispatching {@link CollectionEvent}: - * - *insert* typed events: - * - {@link assign} - * - {@link insert} - * - {@link push} - * - {@link insert_or_assign} - * - *erase* typed events: - * - {@link assign} - * - {@link clear} - * - {@link erase} - * - {@link extract} - * - *refresh* typed events: - * - {@link refresh} - * - * #### [Inherited] {@link HashSet} - * {@link HashSet HashSets} are containers that store unique elements in no particular order, and which allow for - * fast retrieval of individual elements based on their value. - * - * In an {@link HashSet}, the value of an element is at the same time its *key*, that identifies it uniquely. - * Keys are immutable, therefore, the elements in an {@link HashSet} cannot be modified once in the container - - * they can be inserted and removed, though. - * - * Internally, the elements in the {@link HashSet} are not sorted in any particular order, but organized into - * buckets depending on their hash values to allow for fast access to individual elements directly by their - * *values* (with a constant average time complexity on average). - * - * {@link HashSet} containers are faster than {@link TreeSet} containers to access individual elements by their - * *key*, although they are generally less efficient for range iteration through a subset of their elements. - * - * - * - * - * - *

Container properties

- *
- *
Associative
- *
Elements in associative containers are referenced by their *key* and not by their absolute - * position in the container.
- * - *
Hashed
- *
Hashed containers organize their elements using hash tables that allow for fast access to elements - * by their *key*.
- * - *
Set
- *
The value of an element is also the *key* used to identify it.
- * - *
Unique keys
- *
No two elements in the container can have equivalent *keys*.
- *
- * - * @param Type of the elements. - * Each element in an {@link HashSet} is also uniquely identified by this value. - * - * @reference http://www.cplusplus.com/reference/unordered_set/unordered_set - * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) - * @author Jeongho Nam - */ - class HashSetCollection extends std.HashSet implements ICollection { - /** - * A chain object taking responsibility of dispatching events. - */ - private event_dispatcher_; - /** - * @inheritdoc - */ - protected _Handle_insert(first: std.SetIterator, last: std.SetIterator): void; - /** - * @inheritdoc - */ - protected _Handle_erase(first: std.SetIterator, last: std.SetIterator): void; - /** - * @inheritdoc - */ - hasEventListener(type: string): boolean; - /** - * @inheritdoc - */ - dispatchEvent(event: library.BasicEvent): boolean; - /** - * @inheritdoc - */ - refresh(): void; - /** - * @inheritdoc - */ - refresh(it: std.SetIterator): void; - /** - * @inheritdoc - */ - refresh(first: std.SetIterator, last: std.SetIterator): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener): void; - addEventListener(type: "insert", listener: CollectionEventListener): void; - addEventListener(type: "erase", listener: CollectionEventListener): void; - addEventListener(type: "refresh", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; - addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; - addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener): void; - removeEventListener(type: "insert", listener: CollectionEventListener): void; - removeEventListener(type: "erase", listener: CollectionEventListener): void; - removeEventListener(type: "refresh", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; - removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; - removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; - } -} -/** - * Collections, elements I/O detectable STL containers. - * - * STL Containers | Collections - * ---------------------|------------------- - * {@link Vector} | {@link ArrayCollection} - * {@link List} | {@link ListCollection} - * {@link Deque} | {@link DequeCollection} - * | - * {@link TreeSet} | {@link TreeSetCollection} - * {@link HashSet} | {@link HashSetCollection} - * {@link TreeMultiSet} | {@link TreeMultiSetCollection} - * {@link HashMultiSet} | {@link HashMultiSetCollection} - * | - * {@link TreeMap} | {@link TreeMapCollection} - * {@link HashMap} | {@link HashMapCollection} - * {@link TreeMultiMap} | {@link TreeMultiMapCollection} - * {@link HashMultiMap} | {@link HashMultiMapCollection} - * - * @author Jeongho Nam - */ -declare namespace samchon.collections { - /** - * An interface for {@link IContainer containers} who can detect element I/O events. - * - * Below are list of methods who are dispatching {@link CollectionEvent}: - * - *insert* typed events: - * - {@link assign} - * - {@link insert} - * - {@link push} - * - *erase* typed events: - * - {@link assign} - * - {@link clear} - * - {@link erase} - * - *refresh* typed events: - * - {@link refresh} - * - * @author Jeongho Nam - */ - interface ICollection extends std.base.IContainer, library.IEventDispatcher { - /** - * Dispatch a {@link CollectionEvent} with *refresh* typed. - * - * {@link ICollection} dispatches {@link CollectionEvent} typed *insert* or *erase* whenever elements I/O has - * occured. However, unlike those elements I/O events, content change in element level can't be detected. - * There's no way to detect those events automatically by {@link IContainer}. - * - * If you want to dispatch those typed events (notifying change on contents in element level), you've to - * dispatch *refresh* typed event manually, by yourself. Call {@link refresh refresh()} with specified - * iterators who're pointing the elements whose content have changed. Then a {@link CollectionEvent} with - * *refresh* typed will be dispatched. - * - * If you don't specify any iterator, then the range of the *refresh* event will be all elements in this - * {@link ICollection collection}; {@link begin begin()} to {@link end end()}. - */ - refresh(): void; - /** - * Dispatch a {@link CollectionEvent} with *refresh* typed. - * - * {@link ICollection} dispatches {@link CollectionEvent} typed *insert* or *erase* whenever elements I/O has - * occured. However, unlike those elements I/O events, content change in element level can't be detected. - * There's no way to detect those events automatically by {@link IContainer}. - * - * If you want to dispatch those typed events (notifying change on contents in element level), you've to - * dispatch *refresh* typed event manually, by yourself. Call {@link refresh refresh()} with specified - * iterators who're pointing the elements whose content have changed. Then a {@link CollectionEvent} with - * *refresh* typed will be dispatched. - * - * @param it An iterator targeting the content changed element. - */ - refresh(it: std.Iterator): void; - /** - * Dispatch a {@link CollectionEvent} with *refresh* typed. - * - * {@link ICollection} dispatches {@link CollectionEvent} typed *insert* or *erase* whenever elements I/O has - * occured. However, unlike those elements I/O events, content change in element level can't be detected. - * There's no way to detect those events automatically by {@link IContainer}. - * - * If you want to dispatch those typed events (notifying change on contents in element level), you've to - * dispatch *refresh* typed event manually, by yourself. Call {@link refresh refresh()} with specified - * iterators who're pointing the elements whose content have changed. Then a {@link CollectionEvent} with - * *refresh* typed will be dispatched. - * - * @param first An Iterator to the initial position in a sequence of the content changed elmeents. - * @param last An {@link Iterator} to the final position in a sequence of the content changed elements. The range - * used is [*first*, *last*), which contains all the elements between *first* and - * *last*, including the element pointed by *first* but not the element pointed by - * *last*. - */ - refresh(first: std.Iterator, last: std.Iterator): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener): void; - addEventListener(type: "insert", listener: CollectionEventListener): void; - addEventListener(type: "erase", listener: CollectionEventListener): void; - addEventListener(type: "refresh", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; - addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; - addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener): void; - removeEventListener(type: "insert", listener: CollectionEventListener): void; - removeEventListener(type: "erase", listener: CollectionEventListener): void; - removeEventListener(type: "refresh", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; - removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; - removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; - } - /** - * @hidden - */ - namespace ICollection { - /** - * @hidden - */ - function _Dispatch_CollectionEvent(collection: ICollection, type: string, first: std.Iterator, last: std.Iterator): void; - /** - * @hidden - */ - function _Dispatch_MapCollectionEvent(collection: ICollection>, type: string, first: std.MapIterator, last: std.MapIterator): void; - } -} -declare namespace samchon.collections { - /** - * A {@link List} who can detect element I/O events. - * - * Below is the list of methods who are dispatching {@link CollectionEvent}: - * - *insert* typed events: - * - {@link assign} - * - {@link insert} - * - {@link push} - * - {@link push_front} - * - {@link push_back} - * - {@link merge} - * - *erase* typed events: - * - {@link assign} - * - {@link clear} - * - {@link erase} - * - {@link pop_front} - * - {@link pop_back} - * - {@link unique} - * - {@link remove} - * - {@link remove_if} - * - {@link splice} - * - *refresh* typed events: - * - {@link refresh} - * - {@link sort} - * - * #### [Inherited] {@link List} - * {@link List Lists} are sequence containers that allow constant time insert and erase operations anywhere within - * the sequence, and iteration in both directions. - * - * List containers are implemented as doubly-linked lists; Doubly linked lists can store each of the elements they - * contain in different and unrelated storage locations. The ordering is kept internally by the association to - * each element of a link to the element preceding it and a link to the element following it. - * - * They are very similar to forward_list: The main difference being that forward_list objects are single-linked - * lists, and thus they can only be iterated forwards, in exchange for being somewhat smaller and more efficient. - * - * Compared to other base standard sequence containers (array, vector and deque), lists perform generally better - * in inserting, extracting and moving elements in any position within the container for which an iterator has - * already been obtained, and therefore also in algorithms that make intensive use of these, like sorting - * algorithms. - * - * The main drawback of lists and forward_lists compared to these other sequence containers is that they lack - * direct access to the elements by their position; For example, to access the sixth element in a list, one has to - * iterate from a known position (like the beginning or the end) to that position, which takes linear time in the - * distance between these. They also consume some extra memory to keep the linking information associated to each - * element (which may be an important factor for large lists of small-sized elements). - * - * - * - * - * - *

Container properties

- *
- *
Sequence
- *
Elements in sequence containers are ordered in a strict linear sequence. Individual elements are accessed by - * their position in this sequence.
- * - *
Doubly-linked list
- *
Each element keeps information on how to locate the next and the previous elements, allowing constant time - * insert and erase operations before or after a specific element (even of entire ranges), but no direct random - * access.
- *
- * - * @param Type of the elements. - * - * @reference http://www.cplusplus.com/reference/list/list/ - * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) - * @author Jeongho Nam - */ - class ListCollection extends std.List implements ICollection { - /** - * A chain object taking responsibility of dispatching events. - */ - private event_dispatcher_; - /** - * @inheritdoc - */ - push(...items: T[]): number; - /** - * @inheritdoc - */ - push_front(val: T): void; - /** - * @inheritdoc - */ - push_back(val: T): void; - /** - * @hidden - */ - protected _Insert_by_repeating_val(position: std.ListIterator, n: number, val: T): std.ListIterator; - /** - * @hidden - */ - protected _Insert_by_range>(position: std.ListIterator, begin: InputIterator, end: InputIterator): std.ListIterator; - /** - * @inheritdoc - */ - pop_front(): void; - /** - * @inheritdoc - */ - pop_back(): void; - /** - * @hidden - */ - protected _Erase_by_range(first: std.ListIterator, last: std.ListIterator): std.ListIterator; - /** - * @hidden - */ - private notify_insert(first, last); - /** - * @hidden - */ - private notify_erase(first, last); - /** - * @inheritdoc - */ - hasEventListener(type: string): boolean; - /** - * @inheritdoc - */ - dispatchEvent(event: library.BasicEvent): boolean; - /** - * @inheritdoc - */ - refresh(): void; - /** - * @inheritdoc - */ - refresh(it: std.ListIterator): void; - /** - * @inheritdoc - */ - refresh(first: std.ListIterator, last: std.ListIterator): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener): void; - addEventListener(type: "insert", listener: CollectionEventListener): void; - addEventListener(type: "erase", listener: CollectionEventListener): void; - addEventListener(type: "refresh", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; - addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; - addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener): void; - removeEventListener(type: "insert", listener: CollectionEventListener): void; - removeEventListener(type: "erase", listener: CollectionEventListener): void; - removeEventListener(type: "refresh", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; - removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; - removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; - } -} -declare namespace samchon.collections { - type MapCollectionEventListener = (event: MapCollectionEvent) => void; - /** - * An event occured in a {@link MapContainer map container} object. - * - * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) - * @author Jeongho Nam - */ - class MapCollectionEvent extends CollectionEvent> { - /** - * @inheritdoc - */ - readonly first: std.MapIterator; - /** - * @inheritdoc - */ - readonly last: std.MapIterator; - } -} -declare namespace samchon.collections { - /** - * A {@link TreeMap} who can detect element I/O events. - * - * Below is the list of methods who are dispatching {@link MapCollectionEvent}: - * - *insert* typed events: - * - {@link assign} - * - {@link insert} - * - {@link insert_or_assign} - * - {@link emplace} - * - {@link set} - * - {@link push} - * - *erase* typed events: - * - {@link assign} - * - {@link clear} - * - {@link erase} - * - {@link extract} - * - *refresh* typed events: - * - {@link refresh} - * - * #### [Inherited] {@link TreeMap} - * {@link TreeMap TreeMaps} are associative containers that store elements formed by a combination of a - * *key value* (*Key*) and a *mapped value* (*T*), following order. - * - * In a {@link TreeMap}, the *key values* are generally used to sort and uniquely identify the elements, while the - * *mapped values* store the content associated to this key. The types of *key* and *mapped value* may differ, and - * are grouped together in member type *value_type*, which is a {@link Pair} type combining both: - * - * ```typedef Pair value_type;``` - * - * Internally, the elements in a {@link TreeMap} are always sorted by its *key* following a *strict weak ordering* - * criterion indicated by its internal comparison method {@link less}. - * - * {@link TreeMap} containers are generally slower than {@link HashMap HashMap} containers to access individual - * elements by their *key*, but they allow the direct iteration on subsets based on their order. - * - * {@link TreeMap}s are typically implemented as binary search trees. - * - * - * - * - * - *

Container properties

- *
- *
Associative
- *
Elements in associative containers are referenced by their *key* and not by their absolute - * position in the container.
- * - *
Ordered
- *
The elements in the container follow a strict order at all times. All inserted elements are - * given a position in this order.
- * - *
Map
- *
Each element associates a *key* to a *mapped value*: - * *Keys* are meant to identify the elements whose main content is the *mapped value*.
- * - *
Unique keys
- *
No two elements in the container can have equivalent *keys*.
- *
- * - * @param Type of the keys. Each element in a map is uniquely identified by its key value. - * @param Type of the mapped value. Each element in a map stores some data as its mapped value. - * - * @reference http://www.cplusplus.com/reference/map/map - * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) - * @author Jeongho Nam - */ - class TreeMapCollection extends std.TreeMap implements ICollection> { - /** - * A chain object taking responsibility of dispatching events. - */ - private event_dispatcher_; - /** - * @inheritdoc - */ - protected _Handle_insert(first: std.MapIterator, last: std.MapIterator): void; - /** - * @inheritdoc - */ - protected _Handle_erase(first: std.MapIterator, last: std.MapIterator): void; - /** - * @inheritdoc - */ - hasEventListener(type: string): boolean; - /** - * @inheritdoc - */ - dispatchEvent(event: library.BasicEvent): boolean; - /** - * @inheritdoc - */ - refresh(): void; - /** - * @inheritdoc - */ - refresh(it: std.MapIterator): void; - /** - * @inheritdoc - */ - refresh(first: std.MapIterator, last: std.MapIterator): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener): void; - addEventListener(type: "insert", listener: MapCollectionEventListener): void; - addEventListener(type: "erase", listener: MapCollectionEventListener): void; - addEventListener(type: "refresh", listener: MapCollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - addEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; - addEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; - addEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener): void; - removeEventListener(type: "insert", listener: MapCollectionEventListener): void; - removeEventListener(type: "erase", listener: MapCollectionEventListener): void; - removeEventListener(type: "refresh", listener: MapCollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - removeEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; - removeEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; - removeEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; - } -} -declare namespace samchon.collections { - /** - * A {@link TreeMultiMap} who can detect element I/O events. - * - * Below is the list of methods who are dispatching {@link MapCollectionEvent}: - * - *insert* typed events: - * - {@link assign} - * - {@link insert} - * - {@link emplace} - * - {@link push} - * - *erase* typed events: - * - {@link assign} - * - {@link clear} - * - {@link erase} - * - *refresh* typed events: - * - {@link refresh} - * - * #### [Inherited] {@link TreeMultiMap} - * {@link TreeMultiMap TreeMultiMaps} are associative containers that store elements formed by a combination of a - * *key value* and a *mapped value*, following a specific order, and where multiple elements can have equivalent - * keys. - * - * In a {@link TreeMultiMap}, the *key values* are generally used to sort and uniquely identify the elements, - * while the *mapped values* store the content associated to this *key*. The types of *key* and *mapped value* may - * differ, and are grouped together in member type ```value_type```, which is a {@link Pair} type combining both: - * - * ```typedef Pair value_type;``` - * - * Internally, the elements in a {@link TreeMultiMap}are always sorted by its key following a strict weak ordering - * criterion indicated by its internal comparison method (of {@link less}). - * - * {@link TreeMultiMap}containers are generally slower than {@link HashMap} containers to access individual - * elements by their *key*, but they allow the direct iteration on subsets based on their order. - * - * {@link TreeMultiMap TreeMultiMaps} are typically implemented as binary search trees. - * - * < - * img src="http://samchon.github.io/typescript-stl/images/design/class_diagram/map_containers.png" style="max-width: 100%" /> - * - * - *

Container properties

- *
- *
Associative
- *
- * Elements in associative containers are referenced by their *key* and not by their absolute - * position in the container. - *
- * - *
Ordered
- *
- * The elements in the container follow a strict order at all times. All inserted elements are - * given a position in this order. - *
- * - *
Map
- *
- * Each element associates a *key* to a *mapped value*: - * *Keys* are meant to identify the elements whose main content is the *mapped value*. - *
- * - *
Multiple equivalent keys
- *
Multiple elements in the container can have equivalent *keys*.
- *
- * - * @param Type of the keys. Each element in a map is uniquely identified by its key value. - * @param Type of the mapped value. Each element in a map stores some data as its mapped value. - * - * @reference http://www.cplusplus.com/reference/map/multimap - * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) - * @author Jeongho Nam - */ - class TreeMultiMapCollection extends std.TreeMultiMap implements ICollection> { - /** - * A chain object taking responsibility of dispatching events. - */ - private event_dispatcher_; - /** - * @inheritdoc - */ - protected _Handle_insert(first: std.MapIterator, last: std.MapIterator): void; - /** - * @inheritdoc - */ - protected _Handle_erase(first: std.MapIterator, last: std.MapIterator): void; - /** - * @inheritdoc - */ - hasEventListener(type: string): boolean; - /** - * @inheritdoc - */ - dispatchEvent(event: library.BasicEvent): boolean; - /** - * @inheritdoc - */ - refresh(): void; - /** - * @inheritdoc - */ - refresh(it: std.MapIterator): void; - /** - * @inheritdoc - */ - refresh(first: std.MapIterator, last: std.MapIterator): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener): void; - addEventListener(type: "insert", listener: MapCollectionEventListener): void; - addEventListener(type: "erase", listener: MapCollectionEventListener): void; - addEventListener(type: "refresh", listener: MapCollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - addEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; - addEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; - addEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener): void; - removeEventListener(type: "insert", listener: MapCollectionEventListener): void; - removeEventListener(type: "erase", listener: MapCollectionEventListener): void; - removeEventListener(type: "refresh", listener: MapCollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - removeEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; - removeEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; - removeEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; - } -} -declare namespace samchon.collections { - /** - * A {@link TreeMultiSet} who can detect element I/O events. - * - * Below is the list of methods who are dispatching {@link CollectionEvent}: - * - *insert* typed events: - * - {@link assign} - * - {@link insert} - * - {@link push} - * - *erase* typed events: - * - {@link assign} - * - {@link clear} - * - {@link erase} - * - *refresh* typed events: - * - {@link refresh} - * - * #### [Inherited] {@link TreeMultiSet} - * {@link TreeMultiSet TreeMultiSets} are containers that store elements following a specific order, and where - * multiple elements can have equivalent values. - * - * In a {@link TreeMultiSet}, the value of an element also identifies it (the value is itself the *key*, of type - * *T*). The value of the elements in a {@link TreeMultiSet} cannot be modified once in the container (the - * elements are always const), but they can be inserted or removed from the container. - * - * Internally, the elements in a {@link TreeMultiSet TreeMultiSets} are always sorted following a strict weak - * ordering criterion indicated by its internal comparison method (of {@link IComparable.less less}). - * - * {@link TreeMultiSet} containers are generally slower than {@link HashMultiSet} containers to access individual - * elements by their *key*, but they allow the direct iteration on subsets based on their order. - * - *

{@link TreeMultiSet TreeMultiSets} are typically implemented as binary search trees.

- * - *

- *

- * - *

Container properties

- *
- *
Associative
- *
- * Elements in associative containers are referenced by their *key* and not by their absolute - * position in the container. - *
- * - *
Ordered
- *
- * The elements in the container follow a strict order at all times. All inserted elements are - * given a position in this order. - *
- * - *
Set
- *
The value of an element is also the *key* used to identify it.
- * - *
Multiple equivalent keys
- *
Multiple elements in the container can have equivalent *keys*.
- *
- * - * @param Type of the elements. Each element in a {@link TreeMultiSet} container is also identified - * by this value (each value is itself also the element's *key*). - * - * @reference http://www.cplusplus.com/reference/set/multiset - * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) - * @author Jeongho Nam - */ - class TreeMultiSetCollection extends std.TreeMultiSet implements ICollection { - /** - * A chain object taking responsibility of dispatching events. - */ - private event_dispatcher_; - /** - * @inheritdoc - */ - protected _Handle_insert(first: std.SetIterator, last: std.SetIterator): void; - /** - * @inheritdoc - */ - protected _Handle_erase(first: std.SetIterator, last: std.SetIterator): void; - /** - * @inheritdoc - */ - hasEventListener(type: string): boolean; - /** - * @inheritdoc - */ - dispatchEvent(event: library.BasicEvent): boolean; - /** - * @inheritdoc - */ - refresh(): void; - /** - * @inheritdoc - */ - refresh(it: std.SetIterator): void; - /** - * @inheritdoc - */ - refresh(first: std.SetIterator, last: std.SetIterator): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener): void; - addEventListener(type: "insert", listener: CollectionEventListener): void; - addEventListener(type: "erase", listener: CollectionEventListener): void; - addEventListener(type: "refresh", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; - addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; - addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener): void; - removeEventListener(type: "insert", listener: CollectionEventListener): void; - removeEventListener(type: "erase", listener: CollectionEventListener): void; - removeEventListener(type: "refresh", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; - removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; - removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; - } -} -declare namespace samchon.collections { - /** - * A {@link TreeMap} who can detect element I/O events. - * - * Below is the list of methods who are dispatching {@link CollectionEvent}: - * - *insert* typed events: - * - {@link assign} - * - {@link insert} - * - {@link insert_or_assign} - * - {@link push} - * - *erase* typed events: - * - {@link assign} - * - {@link clear} - * - {@link erase} - * - {@link extract} - * - *refresh* typed events: - * - {@link refresh} - * - * #### [Inherited] {@link TreeSet} - * {@link TreeSet TreeSets} are containers that store unique elements following a specific order. - * - * In a {@link TreeSet}, the value of an element also identifies it (the value is itself the *key*, of type *T*), - * and each value must be unique. The value of the elements in a {@link TreeSet} cannot be modified once in the - * container (the elements are always const), but they can be inserted or removed from the container. - * - * Internally, the elements in a {@link TreeSet} are always sorted following a specific strict weak ordering - * criterion indicated by its internal comparison method (of {@link less}). - * - * {@link TreeSet} containers are generally slower than {@link HashSet} containers to access individual elements - * by their *key*, but they allow the direct iteration on subsets based on their order. - * - * {@link TreeSet}s are typically implemented as binary search trees. - * - * - * - * - * - *

Container properties

- *
- *
Associative
- *
- * Elements in associative containers are referenced by their *key* and not by their absolute - * position in the container. - *
- * - *
Ordered
- *
- * The elements in the container follow a strict order at all times. All inserted elements are - * given a position in this order. - *
- * - *
Set
- *
The value of an element is also the *key* used to identify it.
- * - *
Unique keys
- *
No two elements in the container can have equivalent *keys*.
- *
- * - * @param Type of the elements. - * Each element in an {@link TreeSet} is also uniquely identified by this value. - * - * @reference http://www.cplusplus.com/reference/set/set - * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) - * @author Jeongho Nam - */ - class TreeSetCollection extends std.TreeSet implements ICollection { - /** - * A chain object taking responsibility of dispatching events. - */ - private event_dispatcher_; - /** - * @inheritdoc - */ - protected _Handle_insert(first: std.SetIterator, last: std.SetIterator): void; - /** - * @inheritdoc - */ - protected _Handle_erase(first: std.SetIterator, last: std.SetIterator): void; - /** - * @inheritdoc - */ - hasEventListener(type: string): boolean; - /** - * @inheritdoc - */ - dispatchEvent(event: library.BasicEvent): boolean; - /** - * @inheritdoc - */ - refresh(): void; - /** - * @inheritdoc - */ - refresh(it: std.SetIterator): void; - /** - * @inheritdoc - */ - refresh(first: std.SetIterator, last: std.SetIterator): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener): void; - addEventListener(type: "insert", listener: CollectionEventListener): void; - addEventListener(type: "erase", listener: CollectionEventListener): void; - addEventListener(type: "refresh", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; - addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; - addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener): void; - removeEventListener(type: "insert", listener: CollectionEventListener): void; - removeEventListener(type: "erase", listener: CollectionEventListener): void; - removeEventListener(type: "refresh", listener: CollectionEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; - removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; - removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; - } -} -declare namespace samchon.library { - /** - * Case generator. - * - * {@link CaseGenerator} is an abstract case generator being used like a matrix. - *
    - *
  • n��r(n^r) -> {@link CombinedPermutationGenerator}
  • - *
  • nPr -> {@link PermutationGenerator}
  • - *
  • n! -> {@link FactorialGenerator}
  • - *
- * - * @author Jeongho Nam - */ - abstract class CaseGenerator { - /** - * Size, the number of all cases. - */ - protected size_: number; - /** - * N, size of the candidates. - */ - protected n_: number; - /** - * R, size of elements of each case. - */ - protected r_: number; - /** - * Construct from size of N and R. - * - * @param n Size of candidates. - * @param r Size of elements of each case. - */ - constructor(n: number, r: number); - /** - * Get size of all cases. - * - * @return Get a number of the all cases. - */ - size(): number; - /** - * Get size of the N. - */ - n(): number; - /** - * Get size of the R. - */ - r(): number; - /** - * Get index'th case. - * - * @param index Index number - * @return The row of the index'th in combined permuation case - */ - abstract at(index: number): number[]; - } - /** - * A combined-permutation case generator. - * - * n��r - * - * @author Jeongho Nam - */ - class CombinedPermutationGenerator extends CaseGenerator { - /** - * An array using for dividing each element index. - */ - private divider_array; - /** - * Construct from size of N and R. - * - * @param n Size of candidates. - * @param r Size of elements of each case. - */ - constructor(n: number, r: number); - at(index: number): number[]; - } - /** - * A permutation case generator. - * - * nPr - * - * @author Jeongho Nam - */ - class PermuationGenerator extends CaseGenerator { - /** - * Construct from size of N and R. - * - * @param n Size of candidates. - * @param r Size of elements of each case. - */ - constructor(n: number, r: number); - /** - * @inheritdoc - */ - at(index: number): number[]; - } - /** - * Factorial case generator. - * - * n! = nPn - * - * @author Jeongho Nam - */ - class FactorialGenerator extends PermuationGenerator { - /** - * Construct from factorial size N. - * - * @param n Factoria size N. - */ - constructor(n: number); - } -} -declare namespace samchon.library { - type BasicEventListener = (event: BasicEvent) => void; - /** - * The IEventDispatcher interface defines methods for adding or removing event listeners, checks whether specific - * types of event listeners are registered, and dispatches events. - * - * The event target serves as the local point for how events flow through the display list hierarchy. When an - * event such as a mouse click or a key press occurs, an event object is dispatched into the event flow from the - * root of the display list. The event object makes a round-trip journey to the event target, which is - * conceptually divided into three phases: the capture phase includes the journey from the root to the last node - * before the event target's node; the target phase includes only the event target node; and the bubbling phase - * includes any subsequent nodes encountered on the return trip to the root of the display list. - * - * In general, the easiest way for a user-defined class to gain event dispatching capabilities is to extend - * {@link EventDispatcher}. If this is impossible (that is, if the class is already extending another class), you - * can instead implement the {@link IEventDispatcher} interface, create an {@link EventDispatcher} member, and - * write simple hooks to route calls into the aggregated {@link EventDispatcher}. - * - * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/events/IEventDispatcher.html - * @handbook https://github.com/samchon/framework/wiki/TypeScript-Library-EventDispatcher - * @author Migrated by Jeongho Nam - */ - interface IEventDispatcher { - /** - * Checks whether the {@link EventDispatcher} object has any listeners registered for a specific type of event. - * This allows you to determine where an {@link EventDispatcher} object has altered handling of an event type - * in the event flow hierarchy. To determine whether a specific event type actually triggers an event listener, - * use {@link willTrigger willTrigger()}. - * - * The difference between {@link hasEventListener hasEventListener()} and {@link willTrigger willTrigger()} is - * that {@link hasEventListener} examines only the object to which it belongs, whereas {@link willTrigger} - * examines the entire event flow for the event specified by the type parameter. - * - * @param type The type of event. - */ - hasEventListener(type: string): boolean; - /** - * Dispatches an event into the event flow. - * - * The event target is the {@link EventDispatcher} object upon which the {@link dispatchEvent dispatchEvent()} - * method is called. - * - * @param event The {@link BasicEvent} object that is dispatched into the event flow. If the event is being - * redispatched, a clone of the event is created automatically. After an event is dispatched, its - * target property cannot be changed, so you must create a new copy - * of the event for redispatching to work. - */ - dispatchEvent(event: library.BasicEvent): boolean; - /** - * Registers an event listener object with an {@link EventDispatcher} object so that the listener receives - * notification of an event. You can register event listeners on all nodes in the display list for a specific - * type of event, phase, and priority. - * - * After you successfully register an event listener, you cannot change its priority through additional calls - * to {@link addEventListener addEventListener()|} To change a listener's priority, you must first call - * {@link removeEventListener removeEventListener()}. Then you can register the listener again with the new - * priority level. - * - * Keep in mind that after the listener is registered, subsequent calls to {@link addEventListener} with a - * different type or useCapture value result in the creation of a separate listener registration. For example, - * if you first register a listener with useCapture set to true, it listens only during the capture phase. If - * you call {@link addEventListener} again using the same listener object, but with useCapture set to false, - * you have two separate listeners: one that listens during the capture phase and another that listens during - * the target and bubbling phases. - * - * You cannot register an event listener for only the target phase or the bubbling phase. Those phases are - * coupled during registration because bubbling applies only to the ancestors of the target node. - * - * If you no longer need an event listener, remove it by calling {@link removeEventListener}, or memory - * problems could result. Event listeners are not automatically removed from memory because the garbage - * collector does not remove the listener as long as the dispatching object exists (unless the - * useWeakReference parameter is set to true). - * - * Copying an {@link EventDispatcher} instance does not copy the event listeners attached to it. (If your n - * ewly created node needs an event listener, you must attach the listener after creating the node.) However, - * if you move an {@link EventDispatcher} instance, the event listeners attached to it move along with it. - * - * If the event listener is being registered on a node while an event is also being processed on this node, - * the event listener is not triggered during the current phase but may be triggered during a later phase in - * the event flow, such as the bubbling phase. - * - * If an event listener is removed from a node while an event is being processed on the node, it is still - * triggered by the current actions. After it is removed, the event listener is never invoked again (unless it - * is registered again for future processing). - * - * @param event The type of event. - * @param listener The listener function that processes the event. - * This function must accept an Event object as its only parameter and must return - * nothing. - */ - addEventListener(type: string, listener: library.BasicEventListener): void; - /** - * Registers an event listener object with an {@link EventDispatcher} object so that the listener receives - * notification of an event. You can register event listeners on all nodes in the display list for a specific - * type of event, phase, and priority. - * - * After you successfully register an event listener, you cannot change its priority through additional calls - * to {@link addEventListener addEventListener()|} To change a listener's priority, you must first call - * {@link removeEventListener removeEventListener()}. Then you can register the listener again with the new - * priority level. - * - * Keep in mind that after the listener is registered, subsequent calls to {@link addEventListener} with a - * different type or useCapture value result in the creation of a separate listener registration. For example, - * if you first register a listener with useCapture set to true, it listens only during the capture phase. If - * you call {@link addEventListener} again using the same listener object, but with useCapture set to false, - * you have two separate listeners: one that listens during the capture phase and another that listens during - * the target and bubbling phases. - * - * You cannot register an event listener for only the target phase or the bubbling phase. Those phases are - * coupled during registration because bubbling applies only to the ancestors of the target node. - * - * If you no longer need an event listener, remove it by calling {@link removeEventListener}, or memory - * problems could result. Event listeners are not automatically removed from memory because the garbage - * collector does not remove the listener as long as the dispatching object exists (unless the - * useWeakReference parameter is set to true). - * - * Copying an {@link EventDispatcher} instance does not copy the event listeners attached to it. (If your n - * ewly created node needs an event listener, you must attach the listener after creating the node.) However, - * if you move an {@link EventDispatcher} instance, the event listeners attached to it move along with it. - * - * If the event listener is being registered on a node while an event is also being processed on this node, - * the event listener is not triggered during the current phase but may be triggered during a later phase in - * the event flow, such as the bubbling phase. - * - * If an event listener is removed from a node while an event is being processed on the node, it is still - * triggered by the current actions. After it is removed, the event listener is never invoked again (unless it - * is registered again for future processing). - * - * @param event The type of event. - * @param listener The listener function that processes the event. - * This function must accept an Event object as its only parameter and must return - * nothing. - * @param thisArg The object to be used as the **this** object. - */ - addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - /** - * Removes a listener from the {@link EventDispatcher} object. If there is no matching listener registered - * with the {@link EventDispatcher} object, a call to this method has no effect. - * - * @param type The type of event. - * @param listener The listener object to remove. - */ - removeEventListener(type: string, listener: library.BasicEventListener): void; - /** - * Removes a listener from the {@link EventDispatcher} object. If there is no matching listener registered - * with the {@link EventDispatcher} object, a call to this method has no effect. - * - * @param type The type of event. - * @param listener The listener object to remove. - * @param thisArg The object to be used as the **this** object. - */ - removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - } - /** - * The {@link EventDispatcher} class is the base class for all classes that dispatch events. The - * {@link EventDispatcher} class implements the {@link IEventDispatcher} interface and is the base class for the - * {@link DisplayObject} class. The {@link EventDispatcher} class allows any object on the display list to be an - * event target and as such, to use the methods of the {@link IEventDispatcher} interface. - * - * The event target serves as the local point for how events flow through the display list hierarchy. When an - * event such as a mouse click or a key press occurs, an event object is dispatched into the event flow from the - * root of the display list. The event object makes a round-trip journey to the event target, which is - * conceptually divided into three phases: the capture phase includes the journey from the root to the last node - * before the event target's node; the target phase includes only the event target node; and the bubbling phase - * includes any subsequent nodes encountered on the return trip to the root of the display list. - * - * In general, the easiest way for a user-defined class to gain event dispatching capabilities is to extend - * {@link EventDispatcher}. If this is impossible (that is, if the class is already extending another class), you - * can instead implement the {@link IEventDispatcher} interface, create an {@link EventDispatcher} member, and - * write simple hooks to route calls into the aggregated {@link EventDispatcher}. - * - * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/events/EventDispatcher.html - * @author Migrated by Jeongho Nam - */ - class EventDispatcher implements IEventDispatcher { - /** - * @hidden - */ - private event_dispatcher_; - /** - * @hidden - */ - private event_listeners_; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from the origin event dispatcher. - * - * @param dispatcher The origin object who issuing events. - */ - constructor(dispatcher: IEventDispatcher); - /** - * @inheritdoc - */ - hasEventListener(type: string): boolean; - /** - * @inheritdoc - */ - dispatchEvent(event: library.BasicEvent): boolean; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener): void; - /** - * @inheritdoc - */ - addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener): void; - /** - * @inheritdoc - */ - removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; - } -} -declare namespace samchon.library { - /** - * The {@link FileReference} class provides a means to load and save files in browser level. - * - * The {@link FileReference} class provides a means to {@link load} and {@link save} files in browser level. A - * browser-system dialog box prompts the user to select a file to {@link load} or a location for {@link svae}. Each - * {@link FileReference} object refers to a single file on the user's disk and has properties that contain - * information about the file's size, type, name, creation date, modification date, and creator type (Macintosh only). - * - * - * FileReference instances are created in the following ways: - *
    - *
  • - * When you use the new operator with the {@link FileReference} constructor: - * let myFileReference: FileReference = new FileReference(); - *
  • - *
  • - * When you call the {@link FileReferenceList.browse} method, which creates an array of {@link FileReference} - * objects. - *
  • - *
- * - * During a load operation, all the properties of a {@link FileReference} object are populated by calls to the - * {@link FileReference.browse} or {@link FileReferenceList.browse} methods. During a save operation, the name - * property is populated when the select event is dispatched; all other properties are populated when the complete - * event is dispatched. - * - * The {@link browse browse()} method opens an browser-system dialog box that prompts the user to select a file - * for {@link load}. The {@link FileReference.browse} method lets the user select a single file; the - * {@link FileReferenceList.browse} method lets the user select multiple files. After a successful call to the - * {@link browse browse()} method, call the {@link FileReference.load} method to load one file at a time. The - * {@link FileReference.save} method prompts the user for a location to save the file and initiates downloading from - * a binary or string data. - * - * The {@link FileReference} and {@link FileReferenceList} classes do not let you set the default file location - * for the dialog box that the {@link browse} or {@link save} methods generate. The default location shown in the - * dialog box is the most recently browsed folder, if that location can be determined, or the desktop. The classes do - * not allow you to read from or write to the transferred file. They do not allow the browser that initiated the - * {@link load} or {@link save} to access the loaded or saved file or the file's location on the user's disk. - * - * @references http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/FileReference.html - * @author Jeongho Nam - */ - class FileReference extends EventDispatcher { - /** - * @hidden - */ - private file_; - /** - * @hidden - */ - private data_; - /** - * Default Constructor. - */ - constructor(); - /** - * The data from the loaded file after a successful call to the {@link load load()} method. - * - * If the {@link FileReference} object was not populated (by a valid call to {@link FileReference.browse}), - * an {@link LogicError exception} will be thrown when you try to get the value of this property. - * - * All the properties of a {@link FileReference} object are populated by calling the {@link browse browse()}. - * - */ - readonly data: any; - /** - * The name of the file on the local disk. - * - * If the {@link FileReference} object was not populated (by a valid call to {@link FileReference.browse}), - * an {@link LogicError exception} will be thrown when you try to get the value of this property. - * - * All the properties of a {@link FileReference} object are populated by calling the {@link browse browse()}. - * - */ - readonly name: string; - /** - * The filename extension. - * - * A file's extension is the part of the name following (and not including) the final dot ("."). If - * there is no dot in the filename, the extension is null. - * - * If the {@link FileReference} object was not populated (by a valid call to {@link FileReference.browse}), - * an {@link LogicError exception} will be thrown when you try to get the value of this property. - * - * All the properties of a {@link FileReference} object are populated by calling the {@link browse browse()}. - * - */ - readonly extension: string; - /** - * The file type, metadata of the {@link extension}. - * - * If the {@link FileReference} object was not populated (by a valid call to {@link FileReference.browse}), - * an {@link LogicError exception} will be thrown when you try to get the value of this property. - * - * All the properties of a {@link FileReference} object are populated by calling the {@link browse browse()}. - * - */ - readonly type: string; - /** - * The size of the file on the local disk in bytes. - * - * If the {@link FileReference} object was not populated (by a valid call to {@link FileReference.browse}), - * an {@link LogicError exception} will be thrown when you try to get the value of this property. - * - * All the properties of a {@link FileReference} object are populated by calling the {@link browse browse()}. - * - */ - readonly size: number; - /** - * The date that the file on the local disk was last modified. - * - * If the {@link FileReference} object was not populated (by a valid call to {@link FileReference.browse}), - * an {@link LogicError exception} will be thrown when you try to get the value of this property. - * - * All the properties of a {@link FileReference} object are populated by calling the {@link browse browse()}. - * - */ - readonly modificationDate: Date; - /** - * Displays a file-browsing dialog box that lets the user select a file to upload. The dialog box is native - * to the user's browser system. The user can select a file on the local computer or from other systems, for - * example, through a UNC path on Windows. - * - * When you call this method and the user successfully selects a file, the properties of this - * {@link FileReference} object are populated with the properties of that file. Each subsequent time that the - * {@link FileReference.browse} method is called, the {@link FileReference} object's properties are reset to - * the file that the user selects in the dialog box. Only one {@link browse browse()} can be performed at a time - * (because only one dialog box can be invoked at a time). - * - * Using the *typeFilter parameter*, you can determine which files the dialog box displays. - * - * @param typeFilter An array of filter strings used to filter the files that are displayed in the dialog box. - * If you omit this parameter, all files are displayed. - */ - browse(...typeFilter: string[]): void; - /** - * Starts the load of a local file selected by a user. - * - * You must call the {@link FileReference.browse} or {@link FileReferenceList.browse} method before you call - * the {@link load load()} method. - * - * Listeners receive events to indicate the progress, success, or failure of the load. Although you can use - * the {@link FileReferenceList} object to let users select multiple files to load, you must {@link load} the - * {@link FileReferenceList files} one by one. To {@link load} the files one by one, iterate through the - * {@link FileReferenceList.fileList} array of {@link FileReference} objects. - * - * If the file finishes loading successfully, its contents are stored in the {@link data} property. - */ - load(): void; - /** - * Save a file to local filesystem. - * - * {@link FileReference.save} implemented the save function by downloading a file from a hidden anchor tag. - * However, the plan, future's {@link FileReference} will follow such rule: - * - * Opens a dialog box that lets the user save a file to the local filesystem. - * - * The {@link save save()} method first opens an browser-system dialog box that asks the user to enter a - * filename and select a location on the local computer to save the file. When the user selects a location and - * confirms the save operation (for example, by clicking Save), the save process begins. Listeners receive events - * to indicate the progress, success, or failure of the save operation. To ascertain the status of the dialog box - * and the save operation after calling {@link save save()}, your code must listen for events such as cancel, - * open, progress, and complete. - * - * When the file is saved successfully, the properties of the {@link FileReference} object are populated with - * the properties of the local file. The complete event is dispatched if the save is successful. - * - * Only one {@link browse browse()} or {@link save()} session can be performed at a time (because only one - * dialog box can be invoked at a time). - * - * @param data The data to be saved. The data can be in one of several formats, and will be treated appropriately. - * @param fileName File name to be saved. - */ - save(data: string, fileName: string): void; - /** - * Save a file to local filesystem. - * - * {@link FileReference.save} implemented the save function by downloading a file from a hidden anchor tag. - * However, the plan, future's {@link FileReference} will follow such rule: - * - * Opens a dialog box that lets the user save a file to the local filesystem. - * - * The {@link save save()} method first opens an browser-system dialog box that asks the user to enter a - * filename and select a location on the local computer to save the file. When the user selects a location and - * confirms the save operation (for example, by clicking Save), the save process begins. Listeners receive events - * to indicate the progress, success, or failure of the save operation. To ascertain the status of the dialog box - * and the save operation after calling {@link save save()}, your code must listen for events such as cancel, - * open, progress, and complete. - * - * When the file is saved successfully, the properties of the {@link FileReference} object are populated with - * the properties of the local file. The complete event is dispatched if the save is successful. - * - * Only one {@link browse browse()} or {@link save()} session can be performed at a time (because only one - * dialog box can be invoked at a time). - * - * @param data The data to be saved. The data can be in one of several formats, and will be treated appropriately. - * @param fileName File name to be saved. - */ - static save(data: string, fileName: string): void; - } - /** - * The {@link FileReferenceList} class provides a means to let users select one or more files for - * {@link FileReference.load loading}. A {@link FileReferenceList} object represents a group of one or more local - * files on the user's disk as an array of {@link FileReference} objects. For detailed information and important - * considerations about {@link FileReference} objects and the FileReference class, which you use with - * {@link FileReferenceList}, see the {@link FileReference} class. - * - * To work with the {@link FileReferenceList} class: - *
    - *
  • Instantiate the class: var myFileRef = new FileReferenceList();
  • - *
  • - * Call the {@link FileReferenceList.browse} method, which opens a dialog box that lets the user select one or - * more files for upload: myFileRef.browse(); - *
  • - *
  • - * After the {@link browse browse()} method is called successfully, the {@link fileList} property of the - * {@link FileReferenceList} object is populated with an array of {@link FileReference} objects. - *
  • - *
  • Call {@link FileReference.load} on each element in the {@link fileList} array.
  • - *
- * - * The {@link FileReferenceList} class includes a {@link browse browse()} method and a {@link fileList} property - * for working with multiple files. - * - * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/FileReferenceList.html - * @author Jeongho Nam - */ - class FileReferenceList extends EventDispatcher { - /** - * @hidden - */ - file_list: std.Vector; - /** - * Default Constructor. - */ - constructor(); - /** - * An array of {@link FileReference} objects. - * - * When the {@link FileReferenceList.browse} method is called and the user has selected one or more files - * from the dialog box that the {@link browse browse()} method opens, this property is populated with an array of - * {@link FileReference} objects, each of which represents the files the user selected. - * - * The {@link fileList} property is populated anew each time {@link browse browse()} is called on that - * {@link FileReferenceList} object. - */ - readonly fileList: std.Vector; - /** - * Displays a file-browsing dialog box that lets the user select one or more local files to upload. The - * dialog box is native to the user's browser system. - * - * When you call this method and the user successfully selects files, the {@link fileList} property of this - * {@link FileReferenceList} object is populated with an array of {@link FileReference} objects, one for each - * file that the user selects. Each subsequent time that the {@link FileReferenceList.browse} method is called, - * the {@link FileReferenceList.fileList} property is reset to the file(s) that the user selects in the dialog - * box. - * - * Using the *typeFilter* parameter, you can determine which files the dialog box displays. - * - * Only one {@link FileReference.browse}, {@link FileReference.load}, or {@link FileReferenceList.browse} - * session can be performed at a time on a {@link FileReferenceList} object (because only one dialog box can be - * opened at a time). - * - * @param typeFilter An array of filter strings used to filter the files that are displayed in the dialog box. - * If you omit this parameter, all files are displayed. - */ - browse(...typeFilter: string[]): void; - } -} -declare namespace samchon.library { - /** - * A genetic algorithm class. - * - * In the field of artificial intelligence, a genetic algorithm (GA) is a search heuristic that mimics the - * process of natural selection. This heuristic (also sometimes called a metaheuristic) is routinely used to generate - * useful solutions to optimization and search problems. - * - * Genetic algorithms belong to the larger class of evolutionary algorithms (EA), which generate solutions to - * optimization problems using techniques inspired by natural evolution, such as inheritance, {@link mutate mutation}, - * {@link selection}, and {@link crossover}. - * - * @reference https://en.wikipedia.org/wiki/Genetic_algorithm - * @author Jeongho Nam - */ - class GeneticAlgorithm { - /** - * Whether each element (Gene) is unique in their GeneArray. - */ - private unique_; - /** - * Rate of mutation. - * - * The {@link mutation_rate} determines the percentage of occurence of mutation in GeneArray. - * - *
    - *
  • When {@link mutation_rate} is too high, it is hard to ancitipate studying on genetic algorithm.
  • - *
  • - * When {@link mutation_rate} is too low and initial set of genes (GeneArray) is far away from optimal, the - * evolution tends to wandering outside of he optimal. - *
  • - *
- */ - private mutation_rate_; - /** - * Number of tournaments in selection. - */ - private tournament_; - /** - * Initialization Constructor. - * - * @param unique Whether each Gene is unique in their GeneArray. - * @param mutation_rate Rate of mutation. - * @param tournament Number of tournaments in selection. - */ - constructor(unique?: boolean, mutation_rate?: number, tournament?: number); - /** - * Evolove *GeneArray*. - * - * Convenient method accessing to {@link evolvePopulation evolvePopulation()}. - * - * @param individual An initial set of genes; sequence listing. - * @param population Size of population in a generation. - * @param generation Size of generation in evolution. - * @param compare A comparison function returns whether left gene is more optimal. - * - * @return An evolved *GeneArray*, optimally. - * - * @see {@link GAPopulation.compare} - */ - evolveGeneArray>(individual: GeneArray, population: number, generation: number, compare?: (left: T, right: T) => boolean): GeneArray; - /** - * Evolve *population*, a mass of *GeneArraies*. - * - * @param population An initial population. - * @param compare A comparison function returns whether left gene is more optimal. - * - * @return An evolved population. - * - * @see {@link GAPopulation.compare} - */ - evolvePopulation>(population: GAPopulation, compare?: (left: T, right: T) => boolean): GAPopulation; - /** - * Select the best GeneArray in *population* from tournament. - * - * {@link selection Selection} is the stage of a genetic algorithm in which individual genomes are chosen - * from a population for later breeding (using {@linlk crossover} operator). A generic {@link selection} - * procedure may be implemented as follows: - * - *
    - *
  1. - * The fitness function is evaluated for each individual, providing fitness values, which are then - * normalized. ization means dividing the fitness value of each individual by the sum of all fitness - * values, so that the sum of all resulting fitness values equals 1. - *
  2. - *
  3. The population is sorted by descending fitness values.
  4. - *
  5. - * Accumulated normalized fitness values are computed (the accumulated fitness value of an individual is the - * sum of its own fitness value plus the fitness values of all the previous individuals). The accumulated - * fitness of the last individual should be 1 (otherwise something went wrong in the normalization step). - *
  6. - *
  7. A random number R between 0 and 1 is chosen.
  8. - *
  9. The selected individual is the first one whose accumulated normalized value is greater than R.
  10. - *
- * - * @param population The target of tournament. - * @return The best genes derived by the tournament. - * - * @reference https://en.wikipedia.org/wiki/Selection_(genetic_algorithm) - */ - private selection(population); - /** - * Create a new GeneArray by crossing over two *GeneArray*(s). - * - * {@link crossover} is a genetic operator used to vary the programming of a chromosome or chromosomes from - * one generation to the next. It is analogous to reproduction and biological crossover, upon which genetic - * algorithms are based. - * - * {@link crossover Cross over} is a process of taking more than one parent solutions and producing a child - * solution from them. There are methods for selection of the chromosomes. - * - * @param parent1 A parent sequence listing - * @param parent2 A parent sequence listing - * - * @reference https://en.wikipedia.org/wiki/Crossover_(genetic_algorithm) - */ - private crossover(parent1, parent2); - /** - * Cause a mutation on the *GeneArray*. - * - * {@link mutate Mutation} is a genetic operator used to maintain genetic diversity from one generation of a - * population of genetic algorithm chromosomes to the next. It is analogous to biological mutation. - * - * {@link mutate Mutation} alters one or more gene values in a chromosome from its initial state. In - * {@link mutate mutation}, the solution may change entirely from the previous solution. Hence GA can come to - * better solution by using {@link mutate mutation}. - * - * {@link mutate Mutation} occurs during evolution according to a user-definable mutation probability. This - * probability should be set low. If it is set too high, the search will turn into a primitive random search. - * - *

Note

- * Muttion is pursuing diversity. Mutation is useful for avoiding the following problem. - * - * When initial set of genes(GeneArray) is far away from optimail, without mutation (only with selection and - * crossover), the genetic algorithm has a tend to wandering outside of the optimal. - * - * Genes in the GeneArray will be swapped following percentage of the {@link mutation_rate}. - * - * @param individual A container of genes to mutate - * - * @reference https://en.wikipedia.org/wiki/Mutation_(genetic_algorithm) - * @see {@link mutation_rate} - */ - private mutate(individual); - } - /** - * A population in a generation. - * - * {@link GAPopulation} is a class representing population of candidate genes (sequence listing) having an array - * of GeneArray as a member. {@link GAPopulation} also manages initial set of genes and handles fitting test direclty - * by the method {@link fitTest fitTest()}. - * - * The success of evolution of genetic algorithm is depend on the {@link GAPopulation}'s initial set and fitting - * test. (*GeneArray* and {@link compare}.) - * - *

Warning

- * Be careful for the mistakes of direction or position of the {@link compare}. - * Most of logical errors failed to access optimal solution are occured from those mistakes. - * - * @param Type of gene elements. - * @param An array containing genes as elments; sequnce listing. - * - * @author Jeongho Nam - */ - class GAPopulation> { - /** - * Genes representing the population. - */ - private children_; - /** - * A comparison function returns whether left gene is more optimal, greater. - * - * Default value of this {@link compare} is {@link std.greater}. It means to compare two array - * (GeneArray must be a type of {@link std.base.IArrayContainer}). Thus, you've to keep follwing rule. - * - *
    - *
  • GeneArray is implemented from {@link std.base.IArrayContainer}.
  • - *
      - *
    • {@link std.Vector}
    • - *
    • {@link std.Deque}
    • - *
    - *
  • GeneArray has custom public less(obj: T): boolean; function.
  • - *
- * - * If you don't want to follow the rule or want a custom comparison function, you have to realize a - * comparison function. - */ - private compare_; - /** - * Private constructor with population. - * - * Private constructor of GAPopulation does not create {@link children}. (candidate genes) but only assigns - * *null* repeatedly following the *population size*. - * - * This private constructor is designed only for {@link GeneticAlgorithm}. Don't create {@link GAPopulation} - * with this constructor, by yourself. - * - * @param size Size of the population. - */ - constructor(size: number); - /** - * Construct from a {@link GeneArray} and *size of the population*. - * - * This public constructor creates *GeneArray(s)* as population (size) having shuffled genes which are - * came from the initial set of genes (*geneArray*). It uses {@link std.greater} as default comparison function. - * - * - * @param geneArray An initial sequence listing. - * @param size The size of population to have as children. - */ - constructor(geneArray: GeneArray, size: number); - /** - * Constructor from a GeneArray, size of the poluation and custom comparison function. - * - * This public constructor creates *GeneArray(s)* as population (size) having shuffled genes which are - * came from the initial set of genes (*geneArray*). The *compare* is used for comparison function. - * - * - * @param geneArray An initial sequence listing. - * @param size The size of population to have as children. - * @param compare A comparison function returns whether left gene is more optimal. - */ - constructor(geneArray: GeneArray, size: number, compare: (left: GeneArray, right: GeneArray) => boolean); - children(): std.Vector; - /** - * Test fitness of each *GeneArray* in the {@link population}. - * - * @return The best *GeneArray* in the {@link population}. - */ - fitTest(): GeneArray; - /** - * @hidden - */ - private clone(obj); - } -} -declare namespace samchon.library { - /** - * A utility class supporting static methods of string. - * - * The {@link StringUtil} utility class is an all-static class with methods for working with string objects. - * You do not create instances of {@link StringUtil}; instead you call methods such as the - * ```StringUtil.substitute()``` method. - * - * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/utils/StringUtil.html - * @author Jeongho Nam - */ - class StringUtil { - /** - * Generate a substring. - * - * Extracts a substring consisting of the characters from specified start to end. - * It's same with str.substring( ? = (str.find(start) + start.size()), str.find(end, ?) ) - * - * ```typescript - * let str: string = StringUtil.between("ABCD(EFGH)IJK", "(", ")"); - * console.log(str); // PRINTS "EFGH" - * ``` - * - * - If start is not specified, extracts from begin of the string to end. - * - If end is not specified, extracts from start to end of the string. - * - If start and end are all omitted, returns str, itself. - * - * @param str Target string to be applied between. - * @param start A string for separating substring at the front. - * @param end A string for separating substring at the end. - * - * @return substring by specified terms. - */ - static between(str: string, start?: string, end?: string): string; - /** - * Fetch substrings. - * - * Splits a string into an array of substrings dividing by specified delimeters of start and end. - * It's the array of substrings adjusted the between. - * - *
    - *
  • If startStr is omitted, it's same with the split by endStr not having last item.
  • - *
  • If endStr is omitted, it's same with the split by startStr not having first item.
  • - *
  • If startStr and endStar are all omitted, returns *str*.
  • - *
- * - * @param str Target string to split by between. - * @param start A string for separating substring at the front. - * If omitted, it's same with split(end) not having last item. - * @param end A string for separating substring at the end. - * If omitted, it's same with split(start) not having first item. - * @return An array of substrings. - */ - static betweens(str: string, start?: string, end?: string): Array; - /** - * An array containing whitespaces. - */ - private static SPACE_ARRAY; - /** - * Remove all designated characters from the beginning and end of the specified string. - * - * @param str The string whose designated characters should be trimmed. - * @param args Designated character(s). - * - * @return Updated string where designated characters was removed from the beginning and end. - */ - static trim(str: string, ...args: string[]): string; - /** - * Remove all designated characters from the beginning of the specified string. - * - * @param str The string should be trimmed. - * @param delims Designated character(s). - * - * @return Updated string where designated characters was removed from the beginning - */ - static ltrim(str: string, ...args: string[]): string; - /** - * Remove all designated characters from the end of the specified string. - * - * @param str The string should be trimmed. - * @param delims Designated character(s). - * - * @return Updated string where designated characters was removed from the end. - */ - static rtrim(str: string, ...args: string[]): string; - /** - * Substitute {n} tokens within the specified string. - * - * @param format The string to make substitutions in. This string can contain special tokens of the form - * {n}, where n is a zero based index, that will be replaced with the - * additional parameters found at that index if specified. - * @param args Additional parameters that can be substituted in the *format* parameter at each - * {n} location, where n is an integer (zero based) index value into - * the array of values specified. - * - * @return New string with all of the {n} tokens replaced with the respective arguments specified. - */ - static substitute(format: string, ...args: any[]): string; - /** - * Returns a string specified word is replaced. - * - * @param str Target string to replace - * @param before Specific word you want to be replaced - * @param after Specific word you want to replace - * - * @return A string specified word is replaced - */ - static replaceAll(str: string, before: string, after: string): string; - /** - * Returns a string specified words are replaced. - * - * @param str Target string to replace - * @param pairs A specific word's pairs you want to replace and to be replaced - * - * @return A string specified words are replaced - */ - static replaceAll(str: string, ...pairs: std.Pair[]): string; - /** - * Replace all HTML spaces to a literal space. - * - * @param str Target string to replace. - */ - static removeHTMLSpaces(str: string): string; - /** - * Repeat a string. - * - * Returns a string consisting of a specified string concatenated with itself a specified number of times. - * - * @param str The string to be repeated. - * @param n The repeat count. - * - * @return The repeated string. - */ - static repeat(str: string, n: number): string; - /** - * Number to formatted string with "," sign. - * - * Returns a string converted from the number rounded off from specified precision with "," symbols. - * - * @param val A number wants to convert to string. - * @param precision Target precision of round off. - * - * @return A string who represents the number with roundoff and "," symbols. - */ - static numberFormat(val: number, precision?: number): string; - static percentFormat(val: number, precision?: number): string; - } -} -declare namespace samchon.library { - /** - * URLVariables class is for representing variables of HTTP. - * - * {@link URLVariables} class allows you to transfer variables between an application and server. - * - * When transfering, {@link URLVariables} will be converted to a *URI* string. - * - URI: Uniform Resource Identifier - * - * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/URLVariables.html - * @author Migrated by Jeongho Nam - */ - class URLVariables extends std.HashMap { - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from a URL-encoded string. - * - * The {@link decode decode()} method is automatically called to convert the string to properties of the {@link URLVariables} object. - * - * @param str A URL-encoded string containing name/value pairs. - */ - constructor(str: string); - /** - * Converts the variable string to properties of the specified URLVariables object. - * - * @param str A URL-encoded query string containing name/value pairs. - */ - decode(str: string): void; - /** - * Returns a string containing all enumerable variables, in the MIME content encoding application/x-www-form-urlencoded. - */ - toString(): string; - } -} -declare namespace samchon.library { - /** - * A tree-structured XML object. - * - * The {@link XML| class contains methods and properties for working with XML objects. The {@link XML} class (along - * with the {@link XMLList}) implements the powerful XML-handling standards defined in ECMAScript for XML (E4X) - * specification (ECMA-357 edition 2). - * - * An XML object, it is composed with three members; {@link getTag tag}, {@link getProperty properties} and - * {@link getValue value}. As you know, XML is a tree structured data expression method. The tree-stucture; - * {@link XML} class realizes it by extending ```std.HashMap```. Child {@link XML} objects are - * contained in the matched {@link XMLList} object being grouped by their {@link getTag tag name}. The - * {@link XMLList} objects, they're stored in the {@link std.HashMap} ({@link XML} itself) with its **key**; common - * {@link getTag tag name} of children {@link XML} objects. - * - * ```typescript - * class XML extends std.HashMap - * { - * private tag_: string; - * private properties_: std.HashMap; - * private value_: string; - * } - * ``` - * - * ```xml - * - * - * - * {value} - * {value} - * {value} - * - * - * - * - * ``` - * - * Use the {@link toString toString()} method to return a string representation of the {@link XML} object regardless - * of whether the {@link XML} object has simple content or complex content. - * - * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/XML.html - * @handbook https://github.com/samchon/framework/wiki/TypeScript-Library-XML - * @author Jeongho Nam - */ - class XML extends std.HashMap { - /** - * @hidden - */ - private tag_; - /** - * @hidden - */ - private value_; - /** - * @hidden - */ - private property_map_; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from string. - * - * Creates {@link XML} object by parsing a string who represents xml structure. - * - * @param str A string represents XML structure. - */ - constructor(str: string); - /** - * @hidden - */ - private parse(str); - /** - * @hidden - */ - private parse_tag(str); - /** - * @hidden - */ - private parse_properties(str); - /** - * @hidden - */ - private parse_value(str); - /** - * @hidden - */ - private parse_children(str); - /** - * Get tag. - * - * ```xml - * {value} - * ``` - * - * @return tag. - */ - getTag(): string; - /** - * Get value. - * - * ```xml - * {VALUE} - * ``` - * - * @return value. - */ - getValue(): string; - /** - * Get iterator to property element. - * - * Searches the {@link getPropertyMap properties} for an element with a identifier equivalent to key - * and returns an iterator to it if found, otherwise it returns an iterator to {@link HashMap.end end()}. - * - *

Two keys are considered equivalent if the properties' comparison object returns false reflexively - * (i.e., no matter the order in which the elements are passed as arguments).

- * - * Another member function, {@link hasProperty hasProperty()} can be used to just check whether a particular - * key exists. - * - * ```xml - * {value} - * ``` - * - * @param key Key to be searched for - * @return An iterator to the element, if an element with specified key is found, or - * {@link end HashMap.end()} otherwise. - */ - findProperty(key: string): std.MapIterator; - /** - * Test whether a property exists. - * - * ```xml - * {value} - * ``` - * - * @return Whether a property has the *key* exists or not. - */ - hasProperty(key: string): boolean; - /** - * Get property. - * - * Get property by its *key*, property name. If the matched *key* does not exist, then exception - * {@link std.OutOfRange} is thrown. Thus, it would better to test whether the *key* exits or not by calling the - * {@link hasProperty hasProperty()} method before calling this {@link getProperty getProperty()}. - * - * This method can be substituted by {@link getPropertyMap getPropertyMap()} such below: - * - ```getPropertyMap().get(key, value);``` - * - ```getPropertyMap().find(key).second;``` - * - * ```xml - * {value} - * ``` - * - * @return Value of the matched property. - */ - getProperty(key: string): string; - /** - * Get property map. - * - * ```xml - * {value} - * ``` - * - * @return {@link HashMap} containing properties' keys and values. - */ - getPropertyMap(): std.HashMap; - /** - * Set tag. - * - * Set tag name, identifier of this {@link XML} object. - * - * If this {@link XML} object is belonged to, a child of, an {@link XMLList} and its related {@link XML} objects, - * then calling this {@link setTag setTag()} method direclty is not recommended. Erase this {@link XML} object - * from parent objects and insert this object again. - * - * ```xml - * {value} - * ``` - * - * @param val To be new {@link getTag tag}. - */ - setTag(val: string): void; - /** - * Set value. - * - * ```xml - * {VALUE} - * ``` - * - * @param val To be new {@link getValue value}. - */ - setValue(val: string): void; - /** - * Set property. - * - * Set a property *value* with its *key*. If the *key* already exists, then the *value* will be overwritten to - * the property. Otherwise the *key* is not exist yet, then insert the *key* and *value* {@link Pair pair} to - * {@link getPropertyMao property map}. - * - * This method can be substituted by {@link getPropertyMap getPropertyMap()} such below: - * - ```getPropertyMap().set(key, value);``` - * - ```getPropertyMap().emplace(key, value);``` - * - ```getPropertyMap().insert([key, value]);``` - * - ```getPropertyMap().insert(std.make_pair(key, value));``` - * - * ```xml - * {value} - * ``` - * - * @param key Key, identifier of property to be newly inserted. - * @param value Value of new property to be newly inserted. - */ - setProperty(key: string, value: string): void; - /** - * Erase property. - * - * Erases a property by its *key*, property name. If the matched *key* does not exist, then exception - * {@link std.OutOfRange} is thrown. Thus, it would better to test whether the *key* exits or not by calling the - * {@link hasProperty hasProperty()} method before calling this {@link eraseProperty eraseProperty()}. - * - * This method can be substituted by ``getPropertyMap().erase(key)````. - * - * ```xml - * {value} - * ``` - * - * @param key Key of the property to erase - * @throw {@link std.OutOfRange} - */ - eraseProperty(key: string): void; - /** - * @hidden - */ - push(...args: std.Pair[]): number; - /** - * @hidden - */ - push(...args: [string, XMLList][]): number; - push(...xmls: XML[]): number; - push(...xmlLists: XMLList[]): number; - /** - * Add all properties from other {@link XML} object. - * - * All the properties in the *obj* are copied to this {@link XML} object. If this {@link XML} object has same - * property key in the *obj*, then value of the property will be replaced to *obj*'s own. If you don't want to - * overwrite properties with same key, then use {@link getPropertyMap getPropertyMap()} method. - * - * ```typescript - * let x: library.XML; - * let y: library.XML; - * - * x.addAllProperties(y); // duplicated key exists, then overwrites - * x.getPropertyMap().insert(y.getPropertyMap().begin(), y.getPropertyMap().end()); - * // ducpliated key, then ignores. only non-duplicateds are copied. - * ``` - * - * ```xml - * {value} - * ``` - * - * @param obj Target {@link XML} object to copy properties. - */ - insertAllProperties(obj: XML): void; - /** - * Clear properties. - * - * Remove all properties. It's same with calling ```getPropertyMap().clear()```. - * - * ```xml - * {value} - * ``` - */ - clearProperties(): void; - /** - * @hidden - */ - private compute_min_index(...args); - /** - * @hidden - */ - private decode_value(str); - /** - * @hidden - */ - private encode_value(str); - /** - * @hidden - */ - private decode_property(str); - /** - * @hidden - */ - private encode_property(str); - /** - * {@link XML} object to xml string. - * - * Returns a string representation of the {@link XML} object. - * - * @param tab Number of tabs to spacing. - * @return The string representation of the {@link XML} object. - */ - toString(tab?: number): string; - } -} -declare namespace samchon.library { - /** - * List of {@link XML} objects with same tag. - * - * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/XMLList.html - * @handbook https://github.com/samchon/framework/wiki/TypeScript-Library-XML - * @author Jeongho Nam - */ - class XMLList extends std.Deque { - /** - * Get tag. - */ - getTag(): string; - /** - * {@link XMLList XML objects} to string. - * - * Returns a string representation of the {@link XMLList XML objects}. - * - * @param tab Number of tabs to spacing. - * @return The string representation of the {@link XMLList XML objects}. - */ - toString(level?: number): string; - } -} -declare namespace samchon.protocol { - /** - * An interface of entity. - * - * Entity is a class for standardization of expression method using on network I/O by XML. If - * Invoke is a standard message protocol of Samchon Framework which must be kept, Entity is a - * recommended semi-protocol of message for expressing a data class. Following the semi-protocol - * Entity is not imposed but encouraged. - * - * As we could get advantages from standardization of message for network I/O with Invoke, - * we can get additional advantage from standardizing expression method of data class with Entity. - * We do not need to know a part of network communication. Thus, with the Entity, we can only - * concentrate on entity's own logics and relationships between another entities. Entity does not - * need to how network communications are being done. - * - * I say repeatedly. Expression method of Entity is recommended, but not imposed. It's a semi - * protocol for network I/O but not a essential protocol must be kept. The expression method of - * Entity, using on network I/O, is expressed by XML string. - * - * If your own network system has a critical performance issue on communication data class, - * it would be better to using binary communication (with ByteArray). - * Don't worry about the problem! Invoke also provides methods for binary data (ByteArray). - * - * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_message_protocol.png) - * - * @author Jeongho Nam - */ - interface IEntity { - /** - * Construct data of the Entity from a XML object. - * - * Overrides the construct() method and fetch data of member variables from the XML. - * - * By recommended guidance, data representing member variables are contained in properties - * of the put XML object. - * - * @param xml An xml used to contruct data of entity. - */ - construct(xml: library.XML): void; - /** - * Get a key that can identify the Entity uniquely. - * - * If identifier of the Entity is not atomic value, returns a paired or tuple object - * that can represents the composite identifier. - * - * - * class Point extends Entity - * { - * private x: number; - * private y: number; - * - * public key(): std.Pair - * { - * return std.make_pair(this.x, this.y); - * } - * } - * - */ - key(): any; - /** - * A tag name when represented by XML. - * - * - */ - TAG(): string; - /** - * Get a XML object represents the Entity. - * - * A member variable (not object, but atomic value like number, string or date) is categorized - * as a property within the framework of entity side. Thus, when overriding a toXML() method and - * archiving member variables to an XML object to return, puts each variable to be a property - * belongs to only a XML object. - * - * Don't archive the member variable of atomic value to XML::value causing enormouse creation - * of XML objects to number of member variables. An Entity must be represented by only a XML - * instance (tag). - * - *

Standard Usage.

- * - * - * - * - * - * - * - *

Non-standard usage abusing value.

- * - * - * jhnam88 - * Jeongho Nam - * 1988-03-11 - * - * - * master - * Administartor - * 2011-07-28 - * - * - * - * @return An XML object representing the Entity. - */ - toXML(): library.XML; - } - /** - * @hidden - */ - namespace IEntity { - function construct(entity: IEntity, xml: library.XML, ...prohibited_names: string[]): void; - function toXML(entity: IEntity, ...prohibited_names: string[]): library.XML; - } - /** - * An entity, a standard data class. - * - * Entity is a class for standardization of expression method using on network I/O by XML. If - * Invoke is a standard message protocol of Samchon Framework which must be kept, Entity is a - * recommended semi-protocol of message for expressing a data class. Following the semi-protocol - * Entity is not imposed but encouraged. - * - * As we could get advantages from standardization of message for network I/O with Invoke, - * we can get additional advantage from standardizing expression method of data class with Entity. - * We do not need to know a part of network communication. Thus, with the Entity, we can only - * concentrate on entity's own logics and relationships between another entities. Entity does not - * need to how network communications are being done. - * - * I say repeatedly. Expression method of Entity is recommended, but not imposed. It's a semi - * protocol for network I/O but not a essential protocol must be kept. The expression method of - * Entity, using on network I/O, is expressed by XML string. - * - * If your own network system has a critical performance issue on communication data class, - * it would be better to using binary communication (with ByteArray). - * Don't worry about the problem! Invoke also provides methods for binary data (ByteArray). - * - * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_message_protocol.png) - * - * @author Jeongho Nam - */ - abstract class Entity implements IEntity { - /** - * Default Constructor. - */ - constructor(); - construct(xml: library.XML): void; - /** - * @inheritdoc - */ - key(): any; - /** - * @inheritdoc - */ - abstract TAG(): string; - /** - * @inheritdoc - */ - toXML(): library.XML; - } -} -declare namespace samchon.protocol { - /** - * @inheritdoc - */ - interface IEntityCollection extends IEntityGroup, collections.ICollection { - } -} -declare namespace samchon.protocol { - /** - * @inheritdoc - */ - abstract class EntityArrayCollection extends collections.ArrayCollection implements IEntityCollection { - /** - * @inheritdoc - */ - construct(xml: library.XML): void; - /** - * @inheritdoc - */ - abstract createChild(xml: library.XML): T; - /** - * @inheritdoc - */ - key(): any; - /** - * @inheritdoc - */ - has(key: any): boolean; - /** - * @inheritdoc - */ - count(key: any): number; - /** - * @inheritdoc - */ - get(key: any): T; - /** - * @inheritdoc - */ - abstract TAG(): string; - /** - * @inheritdoc - */ - abstract CHILD_TAG(): string; - /** - * @inheritdoc - */ - toXML(): library.XML; - } -} -declare namespace samchon.protocol { - /** - * @inheritdoc - */ - abstract class EntityListCollection extends collections.ListCollection implements IEntityCollection { - /** - * @inheritdoc - */ - construct(xml: library.XML): void; - /** - * @inheritdoc - */ - abstract createChild(xml: library.XML): T; - /** - * @inheritdoc - */ - key(): any; - /** - * @inheritdoc - */ - has(key: any): boolean; - /** - * @inheritdoc - */ - count(key: any): number; - /** - * @inheritdoc - */ - get(key: any): T; - /** - * @inheritdoc - */ - abstract TAG(): string; - /** - * @inheritdoc - */ - abstract CHILD_TAG(): string; - /** - * @inheritdoc - */ - toXML(): library.XML; - } -} -declare namespace samchon.protocol { - /** - * @inheritdoc - */ - abstract class EntityDequeCollection extends collections.DequeCollection implements IEntityCollection { - /** - * @inheritdoc - */ - construct(xml: library.XML): void; - /** - * @inheritdoc - */ - abstract createChild(xml: library.XML): T; - /** - * @inheritdoc - */ - key(): any; - /** - * @inheritdoc - */ - has(key: any): boolean; - /** - * @inheritdoc - */ - count(key: any): number; - /** - * @inheritdoc - */ - get(key: any): T; - /** - * @inheritdoc - */ - abstract TAG(): string; - /** - * @inheritdoc - */ - abstract CHILD_TAG(): string; - /** - * @inheritdoc - */ - toXML(): library.XML; - } -} -/** - * A template for External Systems Manager. - * - * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) - * @author Jeongho Nam - */ -declare namespace samchon.templates.external { - /** - * An array and manager of {@link ExternalSystem external system drivers}. - * - * The {@link ExternalSystemArray} is an abstract class containing and managing external system drivers, - * {@link ExternalSystem} objects. Within framewokr of network, {@link ExternalSystemArray} represents your system - * and children {@link ExternalSystem} objects represent remote, external systems connected with your system. - * With this {@link ExternalSystemArray}, you can manage multiple external systems as a group. - * - * You can specify this {@link ExternalSystemArray} class to be *a server accepting external clients* or - * *a client connecting to external servers*. Even both of them is also possible. - * - * - {@link ExternalClientArray}: A server accepting {@link ExternalSystem external clients}. - * - {@link ExternalServerArray}: A client connecting to {@link ExternalServer external servers}. - * - {@link ExternalServerClientArray}: Both of them. Accepts {@link ExternalSystem external clients} and connects to - * {@link ExternalServer external servers} at the same time. - * - * - * - * - * - * #### Proxy Pattern - * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
    - *
  • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
  • - *
  • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
  • - *
  • Those strategy is called *Proxy Pattern*.
  • - *
- * - * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) - * @author Jeongho Nam - */ - abstract class ExternalSystemArray extends protocol.EntityDequeCollection implements protocol.IProtocol { - /** - * Default Constructor. - */ - constructor(); - /** - * @hidden - */ - private handle_system_erase(event); - /** - * Test whether the role exists. - * - * @param name Name, identifier of target {@link ExternalSystemRole role}. - * - * @return Whether the role has or not. - */ - hasRole(name: string): boolean; - /** - * Get a role. - * - * @param name Name, identifier of target {@link ExternalSystemRole role}. - * - * @return The specified role. - */ - getRole(name: string): ExternalSystemRole; - /** - * Send an {@link Invoke} message. - * - * @param invoke An {@link Invoke} message to send. - */ - sendData(invoke: protocol.Invoke): void; - /** - * Handle an {@Invoke} message have received. - * - * @param invoke An {@link Invoke} message have received. - */ - replyData(invoke: protocol.Invoke): void; - /** - * Tag name of the {@link ExternalSytemArray} in {@link XML}. - * - * @return *systemArray*. - */ - TAG(): string; - /** - * Tag name of {@link ExternalSystem children elements} belonged to the {@link ExternalSytemArray} in {@link XML}. - * - * @return *system*. - */ - CHILD_TAG(): string; - } -} -/** - * A template for Parallel Processing System. - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ -declare namespace samchon.templates.parallel { - /** - * Master of Parallel Processing System. - * - * The {@link ParallelSystemArray} is an abstract class containing and managing remote parallel **slave** system - * drivers, {@link ParallelSystem} objects. Within framework of network, {@link ParallelSystemArray} represents your - * system, a **Master** of *Parallel Processing System* that requesting *parallel process* to **slave** systems and the - * children {@link ParallelSystem} objects represent the remote **slave** systems, who is being requested the - * *parallel processes*. - * - * You can specify this {@link ParallelSystemArray} class to be *a server accepting parallel clients* or - * *a client connecting to parallel servers*. Even both of them is possible. Extends one of them below and overrides - * abstract factory method(s) creating the child {@link ParallelSystem} object. - * - * - {@link ParallelClientArray}: A server accepting {@link ParallelSystem parallel clients}. - * - {@link ParallelServerArray}: A client connecting to {@link ParallelServer parallel servers}. - * - {@link ParallelServerClientArray}: Both of them. Accepts {@link ParallelSystem parallel clients} and connects to - * {@link ParallelServer parallel servers} at the same time. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices - * will be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * - * - * - * - * #### Proxy Pattern - * This class {@link ParallelSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link ParallelSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *Proxy Pattern*: - * - * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
    - *
  • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
  • - *
  • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
  • - *
  • Those strategy is called *Proxy Pattern*.
  • - *
- * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ - abstract class ParallelSystemArray extends external.ExternalSystemArray { - /** - * @hidden - */ - private history_sequence_; - /** - * Default Constructor. - */ - constructor(); - /** - * Send an {@link Invoke} message with segment size. - * - * Sends an {@link Invoke} message requesting a **parallel process** with its *segment size*. The {@link Invoke} - * message will be delivered to children {@link ParallelSystem} objects with the *piece size*, which is divided - * from the *segment size*, basis on their {@link ParallelSystem.getPerformance performance indices}. - * - * - If segment size is 100, - * - The segment will be allocated such below: - * - * Name | Performance index | Number of pieces to be allocated | Formula - * --------|-------------------|----------------------------------|-------------- - * Snail | 1 | 10 | 100 / 10 * 1 - * Cheetah | 4 | 40 | 100 / 10 * 4 - * Rabbit | 3 | 30 | 100 / 10 * 3 - * Turtle | 2 | 20 | 100 / 10 * 2 - * - * When the **parallel process** has completed, then this {@link ParallelSystemArraY} will estimate - * {@link ParallelSystem.getPerformance performance indices} of {@link ParallelSystem} objects basis on their - * execution time. - * - * @param invoke An {@link Invoke} message requesting parallel process. - * @param size Number of pieces to segment. - * - * @return Number of {@link ParallelSystem slave systems} participating in the *Parallel Process*. - * - * @see {@link sendPieceData}, {@link ParallelSystem.getPerformacen} - */ - sendSegmentData(invoke: protocol.Invoke, size: number): number; - /** - * Send an {@link Invoke} message with range of pieces. - * - * Sends an {@link Invoke} message requesting a **parallel process** with its *range of pieces [first, last)*. - * The {@link Invoke} will be delivered to children {@link ParallelSystem} objects with the newly computed - * *range of sub-pieces*, which is divided from the *range of pieces (first to last)*, basis on their - * {@link ParallelSystem.getPerformance performance indices}. - * - * - If indices of pieces are 0 to 50, - * - The sub-pieces will be allocated such below: - * - * Name | Performance index | Range of sub-pieces to be allocated | Formula - * --------|-------------------|-------------------------------------|------------------------ - * Snail | 1 | ( 0, 5] | (50 - 0) / 10 * 1 - * Cheetah | 4 | ( 5, 25] | (50 - 0) / 10 * 4 + 5 - * Rabbit | 3 | (25, 40] | (50 - 0) / 10 * 3 + 25 - * Turtle | 2 | (40, 50] | (50 - 0) / 10 * 2 + 40 - * - * When the **parallel process** has completed, then this {@link ParallelSystemArraY} will estimate - * {@link ParallelSystem.getPerformance performance indices} of {@link ParallelSystem} objects basis on their - * execution time. - * - * @param invoke An {@link Invoke} message requesting parallel process. - * @param first Initial piece's index in a section. - * @param last Final piece's index in a section. The range used is [*first*, *last*), which contains - * all the pieces' indices between *first* and *last*, including the piece pointed by index - * *first*, but not the piece pointed by the index *last*. - * - * @return Number of {@link ParallelSystem slave systems} participating in the *Parallel Process*. - * - * @see {@link sendSegmentData}, {@link ParallelSystem.getPerformacen} - */ - sendPieceData(invoke: protocol.Invoke, first: number, last: number): number; - /** - * @hidden - */ - protected _Complete_history(history: protocol.InvokeHistory): boolean; - /** - * @hidden - */ - protected _Normalize_performance(): void; - } -} -/** - * A template for Distributed Processing System. - * - * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ -declare namespace samchon.templates.distributed { - /** - * Master of Distributed Processing System. - * - * The {@link DistributedSystemArray} is an abstract class containing and managing remote distributed **slave** system - * drivers, {@link DistributedSystem} objects. Within framework of network, {@link DistributedSystemArray} represents - * your system, a **Master** of *Distributed Processing System* that requesting *distributed process* to **slave** - * systems and the children {@link DistributedSystem} objects represent the remote **slave** systems, who is being - * requested the *distributed processes*. - * - * You can specify this {@link DistributedSystemArray} class to be *a server accepting distributed clients* or - * *a client connecting to distributed servers*. Even both of them is possible. Extends one of them below and overrides - * abstract factory method(s) creating the child {@link DistributedSystem} object. - * - * - {@link DistributedClientArray}: A server accepting {@link DistributedSystem distributed clients}. - * - {@link DistributedServerArray}: A client connecting to {@link DistributedServer distributed servers}. - * - {@link DistributedServerClientArray}: Both of them. Accepts {@link DistributedSystem distributed clients} and - * connects to {@link DistributedServer distributed servers} at the same time. - * - * The {@link DistributedSystemArray} contains {@link DistributedProcess} objects directly. You can request a - * **distributed process** through the {@link DistributedProcess} object. You can access the - * {@link DistributedProcess} object(s) with those methods: - * - * - {@link hasProcess} - * - {@link getProcess} - * - {@link insertProcess} - * - {@link eraseProcess} - * - {@link getProcessMap} - * - * When you need the **distributed process**, call the {@link DistributedProcess.sendData} method. Then the - * {@link DistributedProcess} will find the most idle {@link DistributedSystem} object who represents a distributed - * **slave **system. The {@link Invoke} message will be sent to the most idle {@link DistributedSystem} object. When - * the **distributed process** has completed, then {@link DistributedSystem.getPerformance performance index} and - * {@link DistributedProcess.getResource resource index} of related objects will be revaluated. - * - * - * - * - * - * #### Parallel Process - * This {@link DistributedSystemArray} class is derived from the {@link ParallelSystemArray} class, so you can request - * a **parallel process**, too. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices will - * be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * #### Proxy Pattern - * This class {@link DistributedSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link DistributedSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *Proxy Pattern*: - * - * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
    - *
  • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
  • - *
  • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
  • - *
  • Those strategy is called *Proxy Pattern*.
  • - *
- * - * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - abstract class DistributedSystemArray extends parallel.ParallelSystemArray { - /** - * @hidden - */ - private process_map_; - /** - * Default Constructor. - */ - constructor(); - /** - * @inheritdoc - */ - construct(xml: library.XML): void; - /** - * Factory method creating a child {@link DistributedProcess process} object. - * - * @param xml {@link XML} represents the {@link DistributedProcess child} object. - * @return A new {@link DistributedProcess} object. - */ - protected abstract createProcess(xml: library.XML): DistributedProcess; - /** - * Get process map. - * - * Gets an {@link HashMap} containing {@link DistributedProcess} objects with their *key*. - * - * @return An {@link HasmMap> containing pairs of string and {@link DistributedProcess} object. - */ - getProcessMap(): std.HashMap; - /** - * Test whether the process exists. - * - * @param name Name, identifier of target {@link DistributedProcess process}. - * - * @return Whether the process has or not. - */ - hasProcess(name: string): boolean; - /** - * Get a process. - * - * @param name Name, identifier of target {@link DistributedProcess process}. - * - * @return The specified process. - */ - getProcess(name: string): DistributedProcess; - /** - * Insert a process. - * - * @param process A process to be inserted. - * @return Success flag. - */ - insertProcess(process: DistributedProcess): boolean; - /** - * Erase a process. - * - * @param name Name, identifier of target {@link DistributedProcess process}. - */ - eraseProcess(name: string): boolean; - /** - * @hidden - */ - protected _Complete_history(history: protocol.InvokeHistory): boolean; - /** - * @hidden - */ - private estimate_process_resource(history); - /** - * @hidden - */ - private estimate_system_performance(history); - /** - * @hidden - */ - protected _Normalize_performance(): void; - /** - * @inheritdoc - */ - toXML(): library.XML; - } -} -declare namespace samchon.templates.distributed { - /** - * Mediator of Distributed Processing System. - * - * The {@link DistributedSystemArrayMediator} class be a master for its slave systems, and be a slave to its master - * system at the same time. This {@link DistributedSystemArrayMediator} be a master system, containing and managing - * {@link DistributedSystem} objects, which represent distributed slave systems, by extending - * {@link DistributedSystemArray} class. Also, be a slave system through {@link getMediator mediator} object, which is - * derived from the {@link SlaveSystem} class. - * - * As a master, you can specify this {@link DistributedSystemArrayMediator} class to be a master server accepting - * slave clients or a master client to connecting slave servers. Even both of them is possible. Extends one - * of them below and overrides abstract factory method(s) creating the child {@link DistributedSystem} object. - * - * - {@link DistributedClientArrayMediator}: A server accepting {@link DistributedSystem distributed clients}. - * - {@link DistributedServerArrayMediator}: A client connecting to {@link DistributedServer distributed servers}. - * - {@link DistributedServerClientArrayMediator}: Both of them. Accepts {@link DistributedSystem distributed clients} and - * connects to {@link DistributedServer distributed servers} at the same time. - * - * As a slave, you can specify this {@link DistributedSystemArrayMediator} to be a client slave connecting to master - * server or a server slave accepting master client by overriding the {@link createMediator} method. - * Overrides the {@link createMediator createMediator()} method and return one of them: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * #### [Inherited] {@link DistributedSystemArray} - * The {@link DistributedSystemArray} is an abstract class containing and managing remote distributed **slave** system - * drivers, {@link DistributedSystem} objects. Within framework of network, {@link DistributedSystemArray} represents - * your system, a **Master** of *Distributed Processing System* that requesting *distributed process* to **slave** - * systems and the children {@link DistributedSystem} objects represent the remote **slave** systems, who is being - * requested the *distributed processes*. - * - * The {@link DistributedSystemArray} contains {@link DistributedProcess} objects directly. You can request a - * **distributed process** through the {@link DistributedProcess} object. You can access the - * {@link DistributedProcess} object(s) with those methods: - * - * - {@link hasProcess} - * - {@link getProcess} - * - {@link insertProcess} - * - {@link eraseProcess} - * - {@link getProcessMap} - * - * When you need the **distributed process**, call the {@link DistributedProcess.sendData} method. Then the - * {@link DistributedProcess} will find the most idle {@link DistributedSystem} object who represents a distributed - * **slave **system. The {@link Invoke} message will be sent to the most idle {@link DistributedSystem} object. When - * the **distributed process** has completed, then {@link DistributedSystem.getPerformance performance index} and - * {@link DistributedProcess.getResource resource index} of related objects will be revaluated. - * - * - * - * - * - * #### Parallel Process - * This {@link DistributedSystemArray} class is derived from the {@link ParallelSystemArray} class, so you can request - * a **parallel process**, too. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices will - * be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * #### Proxy Pattern - * This class {@link DistributedSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link DistributedSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *Proxy Pattern*: - * - * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
    - *
  • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
  • - *
  • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
  • - *
  • Those strategy is called *Proxy Pattern*.
  • - *
- * - * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - abstract class DistributedSystemArrayMediator extends DistributedSystemArray { - /** - * @hidden - */ - private mediator_; - /** - * Default Constructor. - */ - constructor(); - /** - * Factory method creating a {@link MediatorSystem} object. - * - * The {@link createMediator createMediator()} is an abstract method creating the {@link MediatorSystem} object. - * - * You know what? this {@link DistributedSystemArrayMediator} class be a master for its slave systems, and be a - * slave to its master system at the same time. The {@link MediatorSystem} object makes it possible; be a slave - * system. This {@link createMediator} determines specific type of the {@link MediatorSystem}. - * - * Overrides the {@link createMediator createMediator()} method to create and return one of them following which - * protocol and which type of remote connection (server or client) will be used: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * @return A newly created {@link MediatorSystem} object. - */ - protected abstract createMediator(): parallel.MediatorSystem; - /** - * Start mediator. - * - * If the {@link getMediator mediator} is a type of server, then opens the server accepting master client. - * Otherwise, the {@link getMediator mediator} is a type of client, then connects the master server. - */ - protected startMediator(): void; - /** - * Get {@link MediatorSystem} object. - * - * When you need to send an {@link Invoke} message to the master system of this - * {@link DistributedSystemArrayMediator}, then send to the {@link MediatorSystem} through this - * {@link getMediator}. - * - * ```typescript - * this.getMediator().sendData(...); - * ``` - * - * @return The {@link MediatorSystem} object. - */ - getMediator(): parallel.MediatorSystem; - /** - * @hidden - */ - protected _Complete_history(history: parallel.PRInvokeHistory): boolean; - } -} -declare namespace samchon.protocol { - /** - * An interface taking full charge of network communication. - * - * {@link ICommunicator} is an interface for communicator classes who take full charge of network communication with - * remote system, without reference to whether the remote system is a server or a client. Type of the - * {@link ICommunicator} is specified to {@link IServerConnector} and {@link IClientDriver} whether the remote system - * is a server (that I've to connect) or a client (a client connected to my server). - * - * Whenever a replied message comes from the remote system, the message will be converted to an {@link Invoke} class - * and the {@link Invoke} object will be shifted to the {@link IProtocol listener}'s - * {@link IProtocol.replyData IProtocol.replyData()} method. - * - * - * - * - * - * @see {@link IClientDriver}, {@link IServerConnector}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#icommunicator) - * @author Jeongho Nam - */ - interface ICommunicator extends IProtocol { - /** - * Callback function for connection closed. - */ - onClose: Function; - /** - * Close connection. - */ - close(): void; - /** - * Test connection. - * - * Test whether this {@link ICommunicator communicator} object is connected with the remote system. If the - * connection is alive, then returns ```true```. Otherwise, the connection is not alive or this - * {@link ICommunicator communicator has not connected with the remote system yet, then returns ```false```. - * - * @return true if connected, otherwise false. - */ - isConnected(): boolean; - /** - * Send message. - * - * Send {@link Invoke} message to remote system. - * - * @param invoke An {@link Invoke} message to send. - */ - sendData(invoke: protocol.Invoke): void; - /** - * Handle replied message. - * - * Handles replied {@link Invoke} message recived from remove system. The {@link Invoke} message will be shifted - * to the {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} by this method. - * - * @param invoke An {@link Invoke} message received from remote system. - */ - replyData(invoke: protocol.Invoke): void; - } -} -declare namespace samchon.protocol { - /** - * An abstract, basic class for communicators. - * - * {@link CommunicatorBase} is an abstract class implemented from the {@link ICommunicator}. Mechanism of converting - * raw data to {@link Invoke} messag has realized in this abstract class. Type of this {@link CommunicatorBase} class - * is specified to as below following which protocol is used. - * - * - {@link Communicator}: Samchon Framework's own protocool. - * - {@link WebCommunicator}: Web-socket protocol - * - {@link SharedWorkerCommunicator}: SharedWorker's message protocol. - * - * #### [Inherited] {@link ICommunicator} - * {@link ICommunicator} is an interface for communicator classes who take full charge of network communication with - * remote system, without reference to whether the remote system is a server or a client. Type of the - * {@link ICommunicator} is specified to {@link IServerConnector} and {@link IClientDriver} whether the remote system - * is a server (that I've to connect) or a client (a client connected to my server). - * - * Whenever a replied message comes from the remote system, the message will be converted to an {@link Invoke} class - * and the {@link Invoke} object will be shifted to the {@link IProtocol listener}'s - * {@link IProtocol.replyData IProtocol.replyData()} method. - * - * - * - * - * - * @see {@link IClientDriver}, {@link IServerConnector}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#icommunicator) - * @author Jeongho Nam - */ - abstract class CommunicatorBase implements ICommunicator { - /** - * @hidden - */ - protected listener_: IProtocol; - /** - * @inheritdoc - */ - onClose: Function; - /** - * @hidden - */ - protected connected_: boolean; - /** - * @hidden - */ - private binary_invoke_; - /** - * @hidden - */ - private binary_parameters_; - /** - * @hidden - */ - private unhandled_invokes; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from *listener*. - * - * @param listener An {@link IProtocol} object to listen {@link Invoke} messages. - */ - constructor(listener: IProtocol); - /** - * @inheritdoc - */ - abstract close(): void; - /** - * @inheritdoc - */ - isConnected(): boolean; - /** - * @hidden - */ - protected is_binary_invoke(): boolean; - /** - * @inheritdoc - */ - abstract sendData(invoke: Invoke): void; - /** - * @inheritdoc - */ - replyData(invoke: Invoke): void; - /** - * @hidden - */ - protected handle_string(str: string): void; - /** - * @hidden - */ - protected handle_binary(binary: Uint8Array): void; - } -} -declare namespace samchon.protocol { - /** - * A communicator following Samchon Framework's own protocol. - * - * {@link Communicator} is an abstract class following Samchon Framework's own protocol. This {@link Communicator} - * class is specified to {@link ServerConnector} and {@link ClientDriver} whether the remote system is a server (that - * my system is connecting to) or a client (a client conneting to to my server). - * - * Note that, if one of this or remote system is web-browser based, then you don't have to use this - * {@link Communicator} class who follows Samchon Framework's own protocol. Web-browser supports only Web-socket - * protocol. Thus in that case, you have to use {@link WebCommunicator} instead. - * - * #### [Inherited] {@link ICommunicator} - * {@link ICommunicator} is an interface for communicator classes who take full charge of network communication with - * remote system, without reference to whether the remote system is a server or a client. Type of the - * {@link ICommunicator} is specified to {@link IServerConnector} and {@link IClientDriver} whether the remote system - * is a server (that I've to connect) or a client (a client connected to my server). - * - * Whenever a replied message comes from the remote system, the message will be converted to an {@link Invoke} class - * and the {@link Invoke} object will be shifted to the {@link IProtocol listener}'s - * {@link IProtocol.replyData IProtocol.replyData()} method. - * - * - * - * - * - * @see {@link ClientDriver}, {@link ServerConnector}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#icommunicator) - * @author Jeongho Nam - */ - abstract class Communicator extends CommunicatorBase { - /** - * @hidden - */ - protected socket_: socket.socket; - /** - * @hidden - */ - private header_bytes_; - /** - * @hidden - */ - private data_; - /** - * @hidden - */ - private data_index_; - /** - * @hidden - */ - private listening_; - /** - * @inheritdoc - */ - close(): void; - /** - * @hidden - */ - protected start_listen(): void; - /** - * @hidden - */ - private handle_error(); - /** - * @hidden - */ - private handle_close(); - /** - * @inheritdoc - */ - sendData(invoke: Invoke): void; - /** - * @hidden - */ - private listen_piece(piece); - /** - * @hidden - */ - private listen_header(piece, piece_index); - /** - * @hidden - */ - private listen_data(piece, piece_index); - } -} -declare namespace samchon.protocol { - /** - * A communicator following Web-socket protocol. - * - * {@link WebCommunicator} is an abstract class following Web-socket protocol. This {@link WebCommunicator} class is - * specified to {@link WebServerConnector} and {@link WebClientDriver} whether the remote system is a server (that my - * system is connecting to) or a client (a client conneting to to my server). - * - * Note that, one of this or remote system is web-browser based, then there's not any alternative choice. Web browser - * supports only Web-socket protocol. In that case, you've use this {@link WebCommunicator} class. - * - * #### [Inherited] {@link ICommunicator} - * {@link ICommunicator} is an interface for communicator classes who take full charge of network communication with - * remote system, without reference to whether the remote system is a server or a client. Type of the - * {@link ICommunicator} is specified to {@link IServerConnector} and {@link IClientDriver} whether the remote system - * is a server (that I've to connect) or a client (a client connected to my server). - * - * Whenever a replied message comes from the remote system, the message will be converted to an {@link Invoke} class - * and the {@link Invoke} object will be shifted to the {@link IProtocol listener}'s - * {@link IProtocol.replyData IProtocol.replyData()} method. - * - * - * - * - * - * @see {@link WebClientDriver}, {@link WebServerConnector}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#icommunicator) - * @author Jeongho Nam - */ - abstract class WebCommunicator extends CommunicatorBase { - /** - * @hidden - */ - protected connection_: websocket.connection; - /** - * @inheritdoc - */ - close(): void; - /** - * @inheritdoc - */ - sendData(invoke: Invoke): void; - /** - * @hidden - */ - protected handle_message(message: websocket.IMessage): void; - /** - * @hidden - */ - protected handle_close(): void; - } -} -declare namespace samchon.protocol { - /** - * A communicator for shared worker. - * - * {@link DedicatedWorkerCommunicator} is an abstract class for communication between DedicatedWorker and Web-browser. - * This {@link DedicatedWorkerCommunicator} is specified to {@link DedicatedWorkerServerConnector} and - * {@link DedicatedWorkerClientDriver} whether the remote system is a server (that my system is connecting to) or a - * client (a client conneting to to my server). - * - * #### Why DedicatedWorker be a server? - * In JavaScript environment, there's no way to implement multi-threading function. Instead, JavaScript supports the - * **Worker**, creating a new process. However, the **Worker** does not shares memory addresses. To integrate the - * **Worker** with its master, only communication with string or binary data is allowed. Doesn't it seem like a network - * communication? Furthermore, there's not any difference between the worker communication and network communication. - * It's the reason why Samchon Framework considers the **Worker** as a network node. - * - * The class {@link DedicatedWorkerCommunicator} is designed make such relationship. From now on, DedicatedWorker is a - * {@link DedicatedWorkerServer server} and {@link DedicatedWorkerServerConnector browser} is a client. Integrate the - * server and clients with this {@link DedicatedWorkerCommunicator}. - * - * #### [Inherited] {@link ICommunicator} - * {@link ICommunicator} is an interface for communicator classes who take full charge of network communication with - * remote system, without reference to whether the remote system is a server or a client. Type of the - * {@link ICommunicator} is specified to {@link IServerConnector} and {@link IClientDriver} whether the remote system - * is a server (that I've to connect) or a client (a client connected to my server). - * - * Whenever a replied message comes from the remote system, the message will be converted to an {@link Invoke} class - * and the {@link Invoke} object will be shifted to the {@link IProtocol listener}'s - * {@link IProtocol.replyData IProtocol.replyData()} method. - * - * - * - * - * - * @see {@link DedicatedWorkerClientDriver}, {@link DedicatedWorkerServerConnector}, {@link IProtocol} - * @reference https://developer.mozilla.org/en-US/docs/Web/API/DedicatedWorker - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#icommunicator) - * @author Jeongho Nam - */ - abstract class DedicatedWorkerCommunicator extends CommunicatorBase { - /** - * @hidden - */ - protected handle_message(event: MessageEvent): void; - } -} -declare namespace samchon.protocol { - /** - * A communicator for shared worker. - * - * {@link SharedWorkerCommunicator} is an abstract class for communication between SharedWorker and Web-browser. This - * {@link SharedWorkerCommunicator} is specified to {@link SharedWorkerServerConnector} and - * {@link SharedWorkerClientDriver} whether the remote system is a server (that my system is connecting to) or a client - * (a client conneting to to my server). - * - * Note that, SharedWorker is a conception only existed in web-browser. This {@link SharedWorkerCommunicator} is not - * supported in NodeJS. Only web-browser environment can utilize this {@link SharedWorkerCommunicator}. - * - * #### Why SharedWorker be a server? - * SharedWorker, it allows only an instance (process) to be created whether the SharedWorker is declared in a browser - * or multiple browsers. To integrate them, messages are being sent and received. Doesn't it seem like a relationship - * between a server and clients? Thus, Samchon Framework consider the SharedWorker as a server and browsers as - * clients. - * - * The class {@link SharedWorkerCommunicator} is designed make such relationship. From now on, SharedWorker is a - * {@link SharedWorkerServer server} and {@link SharedWorkerServerConnector browsers} are clients. Integrate the - * server and clients with this {@link SharedWorkerCommunicator}. - * - * #### [Inherited] {@link ICommunicator} - * {@link ICommunicator} is an interface for communicator classes who take full charge of network communication with - * remote system, without reference to whether the remote system is a server or a client. Type of the - * {@link ICommunicator} is specified to {@link IServerConnector} and {@link IClientDriver} whether the remote system - * is a server (that I've to connect) or a client (a client connected to my server). - * - * Whenever a replied message comes from the remote system, the message will be converted to an {@link Invoke} class - * and the {@link Invoke} object will be shifted to the {@link IProtocol listener}'s - * {@link IProtocol.replyData IProtocol.replyData()} method. - * - * - * - * - * - * @see {@link SharedWorkerClientDriver}, {@link SharedWorkerServerConnector}, {@link IProtocol} - * @reference https://developer.mozilla.org/en-US/docs/Web/API/SharedWorker - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#icommunicator) - * @author Jeongho Nam - */ - abstract class SharedWorkerCommunicator extends CommunicatorBase { - /** - * @hidden - */ - protected port_: MessagePort; - /** - * @inheritdoc - */ - close(): void; - /** - * @inheritdoc - */ - sendData(invoke: Invoke): void; - /** - * @hidden - */ - protected handle_message(event: MessageEvent): void; - } -} -declare namespace samchon.protocol { - /** - * An interface for communicator with remote client. - * - * {@link IClientDriver} is a type of {@link ICommunicator}, specified for communication with remote client who has - * connected in a {@link IServer server}. It takes full charge of network communication with the remote client. - * - * The {@link IClientDriver} object is created and delivered from {@link IServer} and - * {@link IServer.addClient IServer.addClient()}. Those are derived types from this {@link IClientDriver}, being - * created by the matched {@link IServer} object. - * - * Protocol | Derived Type | Created By - * ------------------------|-------------------------------------|---------------------------- - * Samchon Framework's own | {@link ClientDriver} | {@link Server} - * Web-socket protocol | {@link WebClientDriver} | {@link WebServer} - * DedicatedWorker | {@link DedicatedWorkerClinetDriver} | {@link DedicatedWorkerServer} - * SharedWorker | {@link SharedWorkerClientDriver} | {@link SharedWorkerServer} - * - * When you've got an {@link IClientDriver} object from the {@link IServer.addClient IServer.addClient()}, then - * specify {@link IProtocol listener} with {@link IClient.listen IClient.listen()}. Whenever a replied message comes - * from the remote system, the message will be converted to an {@link Invoke} class and the {@link Invoke} object - * will be shifted to the {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} method. - * Below code is an example specifying and managing the {@link IProtocol listener} objects. - * - * - https://github.com/samchon/framework/blob/master/ts/examples/calculator/calculator-server.ts - * - * - * - * - * - * @see {@link IServer}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iclientdriver) - * @author Jeongho Nam - */ - interface IClientDriver extends ICommunicator { - /** - * Listen message from the newly connected client. - * - * Starts listening message from the newly connected client. Replied message from the connected client will be - * converted to {@link Invoke} classes and shifted to the *listener*'s {@link IProtocol.replyData replyData()} - * method. - * - * @param listener A listener object to listen replied message from newly connected client in - * {@link IProtocol.replyData replyData()} as an {@link Invoke} object. - */ - listen(listener: IProtocol): void; - } -} -declare namespace samchon.protocol { - /** - * Communicator with remote client. - * - * {@link ClientDriver} is a class taking full charge of network communication with remote client who follows Samchon - * Framework's own protocol. This {@link ClientDriver} object is always created by {@link Server} class. When you got - * this {@link ClientDriver} object from the {@link Server.addClient Server.addClient()}, then specify - * {@link IProtocol listener} with the {@link ClientDriver.listen ClientDriver.listen()} method. - * - * #### [Inherited] {@link IClientDriver} - * {@link IClientDriver} is a type of {@link ICommunicator}, specified for communication with remote client who has - * connected in a {@link IServer server}. It takes full charge of network communication with the remote client. - * - * The {@link IClientDriver} object is created and delivered from {@link IServer} and - * {@link IServer.addClient IServer.addClient()}. Those are derived types from this {@link IClientDriver}, being - * created by the matched {@link IServer} object. - * - * Protocol | Derived Type | Created By - * ------------------------|-------------------------------------|---------------------------- - * Samchon Framework's own | {@link ClientDriver} | {@link Server} - * Web-socket protocol | {@link WebClientDriver} | {@link WebServer} - * DedicatedWorker | {@link DedicatedWorkerClinetDriver} | {@link DedicatedWorkerServer} - * SharedWorker | {@link SharedWorkerClientDriver} | {@link SharedWorkerServer} - * - * When you've got an {@link IClientDriver} object from the {@link IServer.addClient IServer.addClient()}, then - * specify {@link IProtocol listener} with {@link IClient.listen IClient.listen()}. Whenever a replied message comes - * from the remote system, the message will be converted to an {@link Invoke} class and the {@link Invoke} object - * will be shifted to the {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} method. - * Below code is an example specifying and managing the {@link IProtocol listener} objects. - * - * - https://github.com/samchon/framework/blob/master/ts/examples/calculator/calculator-server.ts - * - * - * - * - * - * @see {@link Server}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iclientdriver) - * @author Jeongho Nam - */ - class ClientDriver extends Communicator implements IClientDriver { - /** - * Construct from a socket. - */ - constructor(socket: socket.socket); - /** - * @inheritdoc - */ - listen(listener: IProtocol): void; - } -} -declare namespace samchon.protocol { - /** - * Communicator with remote web-client. - * - * {@link WebClientDriver} is a class taking full charge of network communication with remote client who follows - * Web-socket protocol. This {@link WebClientDriver} object is always created by {@link WebServer} class. When you - * got this {@link WebClientDriver} object from the {@link WebServer.addClient WebServer.addClient()}, then specify - * {@link IProtocol listener} with the {@link WebClientDriver.listen WebClientDriver.listen()} method. - * - * Unlike other protocol, Web-socket protocol's clients notify two parameters on their connection; - * {@link getSessionID session-id} and {@link getPath path}. The {@link getSessionID session-id} can be used to - * identify *user* of each client, and the {@link getPath path} can be used which type of *service* that client wants. - * In {@link service} module, you can see the best utilization case of them. - * - {@link service.User}: utlization of the {@link getSessionID session-id}. - * - {@link service.Service}: utilization of the {@link getPath path}. - * - * #### [Inherited] {@link IClientDriver} - * {@link IClientDriver} is a type of {@link ICommunicator}, specified for communication with remote client who has - * connected in a {@link IServer server}. It takes full charge of network communication with the remote client. - * - * The {@link IClientDriver} object is created and delivered from {@link IServer} and - * {@link IServer.addClient IServer.addClient()}. Those are derived types from this {@link IClientDriver}, being - * created by the matched {@link IServer} object. - * - * Protocol | Derived Type | Created By - * ------------------------|-------------------------------------|---------------------------- - * Samchon Framework's own | {@link ClientDriver} | {@link Server} - * Web-socket protocol | {@link WebClientDriver} | {@link WebServer} - * DedicatedWorker | {@link DedicatedWorkerClinetDriver} | {@link DedicatedWorkerServer} - * SharedWorker | {@link SharedWorkerClientDriver} | {@link SharedWorkerServer} - * - * When you've got an {@link IClientDriver} object from the {@link IServer.addClient IServer.addClient()}, then - * specify {@link IProtocol listener} with {@link IClient.listen IClient.listen()}. Whenever a replied message comes - * from the remote system, the message will be converted to an {@link Invoke} class and the {@link Invoke} object - * will be shifted to the {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} method. - * Below code is an example specifying and managing the {@link IProtocol listener} objects. - * - * - https://github.com/samchon/framework/blob/master/ts/examples/calculator/calculator-server.ts - * - * - * - * - * - * @see {@link WebServer}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iclientdriver) - * @author Jeongho Nam - */ - class WebClientDriver extends WebCommunicator implements IClientDriver { - /** - * @hidden - */ - private path_; - /** - * @hidden - */ - private session_id_; - /** - * @hidden - */ - private listening_; - /** - * Initialization Constructor. - * - * @param connection Connection driver, a socket for web-socket. - * @param path Requested path. - * @param session_id Session ID, an identifier of the remote client. - */ - constructor(connection: websocket.connection, path: string, session_id: string); - /** - * @inheritdoc - */ - listen(listener: IProtocol): void; - /** - * Get requested path. - */ - getPath(): string; - /** - * Get session ID, an identifier of the remote client. - */ - getSessionID(): string; - } -} -declare namespace samchon.protocol { - /** - * Communicator with master web-browser. - * - * {@link DedicatedWorkerClientDriver} is a class taking full charge of network communication with web browsers. This - * {@link DedicatedWorkerClientDriver} object is always created by {@link DedicatedWorkerServer} class. When you got - * this {@link DedicatedWorkerClientDriver} object from - * {@link DedicatedWorkerServer.addClient DedicatedWorkerServer.addClient()}, then specify {@link IProtocol listener} - * with the {@link DedicatedWorkerClientDriver.listen DedicatedWorkerClientDriver.listen()} method. - * - * #### Why DedicatedWorker be a server? - * In JavaScript environment, there's no way to implement multi-threading function. Instead, JavaScript supports the - * **Worker**, creating a new process. However, the **Worker** does not shares memory addresses. To integrate the - * **Worker** with its master, only communication with string or binary data is allowed. Doesn't it seem like a network - * communication? Furthermore, there's not any difference between the worker communication and network communication. - * It's the reason why Samchon Framework considers the **Worker** as a network node. - * - * The class {@link DedicatedWorkerCommunicator} is designed make such relationship. From now on, DedicatedWorker is a - * {@link DedicatedWorkerServer server} and {@link DedicatedWorkerServerConnector browser} is a client. Integrate the - * server and clients with this {@link DedicatedWorkerCommunicator}. - * - * #### [Inherited] {@link IClientDriver} - * {@link IClientDriver} is a type of {@link ICommunicator}, specified for communication with remote client who has - * connected in a {@link IServer server}. It takes full charge of network communication with the remote client. - * - * The {@link IClientDriver} object is created and delivered from {@link IServer} and - * {@link IServer.addClient IServer.addClient()}. Those are derived types from this {@link IClientDriver}, being - * created by the matched {@link IServer} object. - * - * Protocol | Derived Type | Created By - * ------------------------|-------------------------------------|---------------------------- - * Samchon Framework's own | {@link ClientDriver} | {@link Server} - * Web-socket protocol | {@link WebClientDriver} | {@link WebServer} - * DedicatedWorker | {@link DedicatedWorkerClinetDriver} | {@link DedicatedWorkerServer} - * SharedWorker | {@link SharedWorkerClientDriver} | {@link SharedWorkerServer} - * - * When you've got an {@link IClientDriver} object from the {@link IServer.addClient IServer.addClient()}, then - * specify {@link IProtocol listener} with {@link IClient.listen IClient.listen()}. Whenever a replied message comes - * from the remote system, the message will be converted to an {@link Invoke} class and the {@link Invoke} object - * will be shifted to the {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} method. - * Below code is an example specifying and managing the {@link IProtocol listener} objects. - * - * - https://github.com/samchon/framework/blob/master/ts/examples/calculator/calculator-server.ts - * - * - * - * - * - * @see {@link DedicatedWorkerServer}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iclientdriver) - * @author Jeongho Nam - */ - class DedicatedWorkerClientDriver extends DedicatedWorkerCommunicator implements IClientDriver { - /** - * Default Constructor. - */ - constructor(); - /** - * @inheritdoc - */ - listen(listener: IProtocol): void; - /** - * @inheritdoc - */ - close(): void; - /** - * @inheritdoc - */ - sendData(invoke: Invoke): void; - } -} -declare namespace samchon.protocol { - /** - * Communicator with remote web-browser. - * - * {@link SharedWorkerClientDriver} is a class taking full charge of network communication with web browsers. This - * {@link SharedWorkerClientDriver} object is always created by {@link SharedWorkerServer} class. When you got this - * {@link SharedWorkerClientDriver} object from {@link SharedWorkerServer.addClient SharedWorkerServer.addClient()}, - * then specify {@link IProtocol listener} with the - * {@link SharedWorkerClientDriver.listen SharedWorkerClientDriver.listen()} method. - * - * #### Why SharedWorker be a server? - * SharedWorker, it allows only an instance (process) to be created whether the SharedWorker is declared in a browser - * or multiple browsers. To integrate them, messages are being sent and received. Doesn't it seem like a relationship - * between a server and clients? Thus, Samchon Framework consider the SharedWorker as a server and browsers as - * clients. - * - * The class {@link SharedWorkerCommunicator} is designed make such relationship. From now on, SharedWorker is a - * {@link SharedWorkerServer server} and {@link SharedWorkerServerConnector browsers} are clients. Integrate the - * server and clients with this {@link SharedWorkerCommunicator}. - * - * #### [Inherited] {@link IClientDriver} - * {@link IClientDriver} is a type of {@link ICommunicator}, specified for communication with remote client who has - * connected in a {@link IServer server}. It takes full charge of network communication with the remote client. - * - * The {@link IClientDriver} object is created and delivered from {@link IServer} and - * {@link IServer.addClient IServer.addClient()}. Those are derived types from this {@link IClientDriver}, being - * created by the matched {@link IServer} object. - * - * Protocol | Derived Type | Created By - * ------------------------|-------------------------------------|---------------------------- - * Samchon Framework's own | {@link ClientDriver} | {@link Server} - * Web-socket protocol | {@link WebClientDriver} | {@link WebServer} - * DedicatedWorker | {@link DedicatedWorkerClinetDriver} | {@link DedicatedWorkerServer} - * SharedWorker | {@link SharedWorkerClientDriver} | {@link SharedWorkerServer} - * - * When you've got an {@link IClientDriver} object from the {@link IServer.addClient IServer.addClient()}, then - * specify {@link IProtocol listener} with {@link IClient.listen IClient.listen()}. Whenever a replied message comes - * from the remote system, the message will be converted to an {@link Invoke} class and the {@link Invoke} object - * will be shifted to the {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} method. - * Below code is an example specifying and managing the {@link IProtocol listener} objects. - * - * - https://github.com/samchon/framework/blob/master/ts/examples/calculator/calculator-server.ts - * - * - * - * - * - * @see {@link SharedWorkerServer}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iclientdriver) - * @author Jeongho Nam - */ - class SharedWorkerClientDriver extends SharedWorkerCommunicator implements IClientDriver { - private listening_; - /** - * Construct from a MessagePort object. - */ - constructor(port: MessagePort); - /** - * @inheritdoc - */ - listen(listener: IProtocol): void; - } -} -declare namespace samchon.protocol { - /** - * A container of entity, and it's a type of entity, too. - * - * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_message_protocol.png) - * - * @handbook [Protocol - Standard Message](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Standard_Message) - * @author Jeongho Nam - */ - interface IEntityGroup extends IEntity, std.base.IContainer { - /** - * Construct data of the Entity from an XML object. - * - * Constructs the EntityArray's own member variables only from the input XML object. - * - * Do not consider about constructing children Entity objects' data in EntityArray::construct(). - * Those children Entity objects' data will constructed by their own construct() method. Even insertion - * of XML objects representing children are done by abstract method of EntityArray::toXML(). - * - * Constructs only data of EntityArray's own. - */ - construct(xml: library.XML): void; - /** - * Factory method of a child Entity. - * - * EntityArray::createChild() is a factory method creating a new child Entity which is belonged - * to the EntityArray. This method is called by EntityArray::construct(). The children construction - * methods Entity::construct() will be called by abstract method of the EntityArray::construct(). - * - * @return A new child Entity belongs to EntityArray. - */ - createChild(xml: library.XML): T; - /** - * Get iterator to element. - * - * Searches the container for an element with a identifier equivalent to *key* and returns an - * iterator to it if found, otherwise it returns an iterator to {@link end end()}. - * - * Two keys are considered equivalent if the container's comparison object returns false reflexively - * (i.e., no matter the order in which the elements are passed as arguments). - * - * Another member functions, {@link has has()} and {@link count count()}, can be used to just check - * whether a particular *key* exists. - * - * @param key Key to be searched for - * @return An iterator to the element, if an element with specified *key* is found, or - * {@link end end()} otherwise. - */ - /** - * Whether have the item or not. - * - * Indicates whether a map has an item having the specified identifier. - * - * @param key Key value of the element whose mapped value is accessed. - * - * @return Whether the map has an item having the specified identifier. - */ - has(key: any): boolean; - /** - * Count elements with a specific key. - * - * Searches the container for elements whose key is *key* and returns the number of elements found. - * - * @param key Key value to be searched for. - * - * @return The number of elements in the container with a *key*. - */ - count(key: any): number; - /** - * Get an element - * - * Returns a reference to the mapped value of the element identified with *key*. - * - * @param key Key value of the element whose mapped value is accessed. - * - * @throw exception out of range - * - * @return A reference object of the mapped value (_Ty) - */ - get(key: any): T; - /** - * A tag name of children objects. - */ - CHILD_TAG(): string; - /** - * Get an XML object represents the EntityArray. - * - * Archives the EntityArray's own member variables only to the returned XML object. - * - * Do not consider about archiving children Entity objects' data in EntityArray::toXML(). - * Those children Entity objects will converted to XML object by their own toXML() method. The - * insertion of XML objects representing children are done by abstract method of - * EntityArray::toXML(). - * - * Archives only data of EntityArray's own. - */ - toXML(): library.XML; - } - /** - * @hidden - */ - namespace IEntityGroup { - /** - * @hidden - */ - function construct(entityGroup: IEntityGroup, xml: library.XML, ...prohibited_names: string[]): void; - /** - * @hidden - */ - function toXML(entityGroup: IEntityGroup, ...prohibited_names: string[]): library.XML; - function has(entityGroup: IEntityGroup, key: any): boolean; - function count(entityGroup: IEntityGroup, key: any): number; - function get(entityGroup: IEntityGroup, key: any): T; - } -} -declare namespace samchon.protocol { - /** - * @inheritdoc - */ - abstract class EntityArray extends std.Vector implements IEntityGroup { - /** - * @inheritdoc - */ - construct(xml: library.XML): void; - /** - * @inheritdoc - */ - abstract createChild(xml: library.XML): T; - /** - * @inheritdoc - */ - key(): any; - /** - * @inheritdoc - */ - has(key: any): boolean; - /** - * @inheritdoc - */ - count(key: any): number; - /** - * @inheritdoc - */ - get(key: any): T; - /** - * @inheritdoc - */ - abstract TAG(): string; - /** - * @inheritdoc - */ - abstract CHILD_TAG(): string; - /** - * @inheritdoc - */ - toXML(): library.XML; - } -} -declare namespace samchon.protocol { - /** - * @inheritdoc - */ - abstract class EntityList extends std.List implements IEntityGroup { - /** - * @inheritdoc - */ - construct(xml: library.XML): void; - /** - * @inheritdoc - */ - abstract createChild(xml: library.XML): T; - /** - * @inheritdoc - */ - key(): any; - /** - * @inheritdoc - */ - has(key: any): boolean; - /** - * @inheritdoc - */ - count(key: any): number; - /** - * @inheritdoc - */ - get(key: any): T; - /** - * @inheritdoc - */ - abstract TAG(): string; - /** - * @inheritdoc - */ - abstract CHILD_TAG(): string; - /** - * @inheritdoc - */ - toXML(): library.XML; - } -} -declare namespace samchon.protocol { - /** - * @inheritdoc - */ - abstract class EntityDeque extends std.Deque implements IEntityGroup { - /** - * @inheritdoc - */ - construct(xml: library.XML): void; - /** - * @inheritdoc - */ - abstract createChild(xml: library.XML): T; - /** - * @inheritdoc - */ - key(): any; - /** - * @inheritdoc - */ - has(key: any): boolean; - /** - * @inheritdoc - */ - count(key: any): number; - /** - * @inheritdoc - */ - get(key: any): T; - /** - * @inheritdoc - */ - abstract TAG(): string; - /** - * @inheritdoc - */ - abstract CHILD_TAG(): string; - /** - * @inheritdoc - */ - toXML(): library.XML; - } -} -declare namespace samchon.protocol { - /** - * Standard message of network I/O. - * - * {@link Invoke} is a class used in network I/O in protocol package of Samchon Framework. - * - * The Invoke message has an XML structure like the result screen of provided example in below. - * We can enjoy lots of benefits by the normalized and standardized message structure used in - * network I/O. - * - * The greatest advantage is that we can make any type of network system, even how the system - * is enourmously complicated. As network communication message is standardized, we only need to - * concentrate on logical relationships between network systems. We can handle each network system - * like a object (class) in OOD. And those relationships can be easily designed by using design - * pattern. - * - * In Samchon Framework, you can make any type of network system with basic componenets - * (IProtocol, IServer and ICommunicator) by implemens or inherits them, like designing - * classes of S/W architecture. - * - * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_message_protocol.png) - * - * @see {@link IProtocol} - * @author Jeongho Nam - */ - class Invoke extends EntityArray { - /** - * Listener, represent function's name. - */ - private listener; - /** - * Default Constructor. - */ - constructor(); - constructor(listener: string); - /** - * Copy Constructor. - * - * @param invoke - */ - constructor(invoke: Invoke); - /** - * Construct from listener and parametric values. - * - * @param listener - * @param parameters - */ - constructor(listener: string, ...parameters: Array); - /** - * @inheritdoc - */ - createChild(xml: library.XML): InvokeParameter; - /** - * Get listener. - */ - getListener(): string; - /** - * Get arguments for Function.apply(). - * - * @return An array containing values of the contained parameters. - */ - getArguments(): Array; - /** - * Apply to a matched function. - * - * @param obj Target {@link IProtocol} object to find matched function. - * @return Whether succeded to find matched function. - */ - apply(obj: IProtocol): boolean; - /** - * Apply to a function. - * - * @param thisArg Owner of the function. - * @param func Function to call. - */ - apply(thisArg: IProtocol, func: Function): void; - /** - * @inheritdoc - */ - TAG(): string; - /** - * @inheritdoc - */ - CHILD_TAG(): string; - } -} -declare namespace samchon.protocol { - /** - * A parameter belongs to an Invoke. - * - * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_message_protocol.png) - * - * @author Jeongho Nam - */ - class InvokeParameter extends Entity { - /** - * Name of the parameter. - * - * @details Optional property, can be omitted. - */ - protected name: string; - /** - * Type of the parameter. - */ - protected type: string; - /** - * Value of the parameter. - */ - protected value: string | number | library.XML | Uint8Array; - /** - * Default Constructor. - */ - constructor(); - constructor(val: number); - constructor(val: string); - constructor(val: library.XML); - constructor(val: Uint8Array); - /** - * Construct from variable name and number value. - * - * @param name - * @param val - */ - constructor(name: string, val: number); - constructor(name: string, val: string); - constructor(name: string, val: library.XML); - constructor(name: string, val: Uint8Array); - /** - * @inheritdoc - */ - construct(xml: library.XML): void; - setValue(value: number): void; - setValue(value: string): void; - setValue(value: library.XML): void; - setValue(value: Uint8Array): void; - /** - * @inheritdoc - */ - key(): any; - /** - * Get name. - */ - getName(): string; - /** - * Get type. - */ - getType(): string; - /** - * Get value. - */ - getValue(): any; - /** - * @inheritdoc - */ - TAG(): string; - /** - * @inheritdoc - */ - toXML(): library.XML; - } -} -declare namespace samchon.protocol { - /** - * History of an {@link Invoke} message. - * - * The {@link InvokeHistory} is a class archiving history log of an {@link Invoke} message with elapsed time. This - * {@link InvokeHistory} class is used to report elapsed time of handling a requested process from **slave** to - * **master** system. - * - * The **master** system utilizes derived {@link InvokeHistory} objects to compute performance indices. - * - {@link ParallelSytem.getPerformance} - * - {@link DistributedProcess.getResource} - * - * @author Jeongho Nam - */ - class InvokeHistory extends protocol.Entity { - /** - * @hidden - */ - private uid; - /** - * @hidden - */ - private listener; - /** - * @hidden - */ - private start_time_; - /** - * @hidden - */ - private end_time_; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from an {@link Invoke} message. - * - * @param invoke An {@link Invoke} message requesting a *parallel or distributed process*. - */ - constructor(invoke: protocol.Invoke); - /** - * @inheritdoc - */ - construct(xml: library.XML): void; - /** - * Complete the history. - * - * Completes the history and determines the {@link getEndTime end time}. - */ - complete(): void; - key(): number; - /** - * Get unique ID. - */ - getUID(): number; - /** - * Get {@link Invoke.getListener listener} of the {@link Invoke} message. - */ - getListener(): string; - /** - * Get start time. - */ - getStartTime(): Date; - /** - * Get end time. - */ - getEndTime(): Date; - /** - * Compute elapsed time. - * - * @return nanoseconds. - */ - computeElapsedTime(): number; - /** - * @inheritdoc - */ - TAG(): string; - /** - * @inheritdoc - */ - toXML(): library.XML; - /** - * Convert to an {@link Invoke} message. - * - * Creates and returns an {@link Invoke} message that is used to reporting to the **master**. - */ - toInvoke(): protocol.Invoke; - } -} -declare namespace samchon.protocol { - /** - * An interface for {@link Invoke} message chain. - * - * {@link IProtocol} is an interface for {@link Invoke} message, which is standard message of network I/O in - * *Samchon Framework*, chain. The {@link IProtocol} interface is used to network drivers and some classes which are - * in a relationship of *Chain of Responsibility Pattern* with those network drivers. - * - * Implements {@link IProtocol} if the class sends and handles {@link Invoke} messages. Looking around source codes of - * the *Samchon Framework*, especially *Templates*, you can find out that all the classes and modules handling - * {@link Invoke} messages are always implementing this {@link IProtocol}. - * - * - * - * - * - * @see {@link Invoke} - * @handbook https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iprotocol - * @author Jeongho Nam - */ - interface IProtocol { - /** - * Sending message. - * - * Sends message to related system or shifts the responsibility to chain. - * - * @param invoke Invoke message to send - */ - replyData(invoke: Invoke): void; - /** - * Handling replied message. - * - * Handles replied message or shifts the responsibility to chain. - * - * @param invoke An {@link Invoke} message has received. - */ - sendData(invoke: Invoke): void; - } -} -declare namespace samchon.protocol { - /** - * An interface for a server. - * - * {@link IServer} is an interfaec for server classes who are providing methods for {@link open opening a server} and - * {@link IClientDriver accepting clients}. - * - * To open a server, extends one of derived class under below considedring which protocol to follow first. At next, - * overrides {@link addClient addClient()} method who accepts a newly connected client as an {@link IClientDriver} - * object. Then at last, call {@link open open()} method with specified port number. - * - * Protocol | Derived Type | Related {@link IClientDriver} - * ------------------------|-------------------------------|------------------------------------- - * Samchon Framework's own | {@link Server} | {@link ClientDriver} - * Web-socket protocol | {@link WebServer} | {@link WebClientDriver} - * DedicatedWorker | {@link DedicatedWorkerServer} | {@link DedicatedWorkerClientDriver} - * SharedWorker | {@link SharedWorkerServer} | {@link SharedWorkerClientDriver} - * - * Below codes and classes will be good examples for comprehending how to open a server and handle remote clients. - * - https://github.com/samchon/framework/blob/master/ts/examples/calculator/calculator-server.ts - * - https://github.com/samchon/framework/blob/master/ts/examples/chat-server/server.ts - * - {@link service.Server} - * - {@link external.ExternalClientArray} - * - {@link slave.SlaveServer} - * - * If you're embarrased because your class already extended another one, then use {@link IServerBase}. - * - * - * - * - * - * @see {@link IClientDriver}, {@link IServerBase} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserver) - * @author Jeongho Nam - */ - interface IServer { - /** - * Open server. - * - * @param port Port number to open. - */ - open(port: number): void; - /** - * Close server. - * - * Close opened server. All remote clients, have connected with this server, are also closed and their call back - * functions, for closed connection, {@link IClientDriver.onClose} are also called. - */ - close(): void; - /** - * Add a newly connected remote client. - * - * The {@link addClient addClient()} is an abstract method being called when a remote client is newly connected - * with {@link IClientDriver} object who communicates with the remote system. Overrides this method and defines - * what to do with the *driver*, a newly connected remote client. - * - * Below methods and example codes may be good for comprehending how to utilize this {@link addClient} method. - * - * - https://github.com/samchon/framework/blob/master/ts/examples/calculator/calculator-server.ts - * - https://github.com/samchon/framework/blob/master/ts/examples/chat-server/server.ts - * - {@link service.Server.addClient} - * - {@link external.ExternalClientArray.addClient} - * - {@link slave.SlaveServer.addClient} - * - * @param driver A {@link ICommunicator communicator} with (newly connected) remote client. - */ - addClient(driver: IClientDriver): void; - } -} -declare namespace samchon.protocol { - /** - * A server. - * - * The {@link Server} is an abstract class designed to open a server and accept clients who are following Samchon - * Framework's own protocol. Extends this {@link Server} class and overrides {@link addClient addClient()} method to - * define what to do with newly connected {@link ClientDriver remote clients}. - * - * #### [Inherited] {@link IServer} - * {@link IServer} is an interfaec for server classes who are providing methods for {@link open opening a server} and - * {@link IClientDriver accepting clients}. - * - * To open a server, extends one of derived class under below considedring which protocol to follow first. At next, - * overrides {@link addClient addClient()} method who accepts a newly connected client as an {@link IClientDriver} - * object. Then at last, call {@link open open()} method with specified port number. - * - * Protocol | Derived Type | Related {@link IClientDriver} - * ------------------------|-------------------------------|------------------------------------- - * Samchon Framework's own | {@link Server} | {@link ClientDriver} - * Web-socket protocol | {@link WebServer} | {@link WebClientDriver} - * DedicatedWorker | {@link DedicatedWorkerServer} | {@link DedicatedWorkerClientDriver} - * SharedWorker | {@link SharedWorkerServer} | {@link SharedWorkerClientDriver} - * - * Below codes and classes will be good examples for comprehending how to open a server and handle remote clients. - * - https://github.com/samchon/framework/blob/master/ts/examples/calculator/calculator-server.ts - * - https://github.com/samchon/framework/blob/master/ts/examples/chat-server/server.ts - * - {@link service.Server} - * - {@link external.ExternalClientArray} - * - {@link slave.SlaveServer} - * - * If you're embarrased because your class already extended another one, then use {@link IServerBase}. - * - * - * - * - * - * @see {@link ClientDriver}, {@link ServerBase} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserver) - * @author Jeongho Nam - */ - abstract class Server implements IServer { - /** - * @hidden - */ - private server; - /** - * @inheritdoc - */ - abstract addClient(driver: ClientDriver): void; - /** - * @inheritdoc - */ - open(port: number): void; - /** - * @inheritdoc - */ - close(): void; - /** - * @hidden - */ - private handle_connect(socket); - } -} -declare namespace samchon.protocol { - /** - * A web server. - * - * The {@link WebServer} is an abstract class designed to open a server and accept clients who are following - * web-socket protocol. Extends this {@link WebServer} class and overrides {@link addClient addClient()} method to - * define what to do with newly connected {@link WebClientDriver remote clients}. - * - * #### [Inherited] {@link IServer} - * {@link IServer} is an interfaec for server classes who are providing methods for {@link open opening a server} and - * {@link IClientDriver accepting clients}. - * - * To open a server, extends one of derived class under below considedring which protocol to follow first. At next, - * overrides {@link addClient addClient()} method who accepts a newly connected client as an {@link IClientDriver} - * object. Then at last, call {@link open open()} method with specified port number. - * - * Protocol | Derived Type | Related {@link IClientDriver} - * ------------------------|-------------------------------|------------------------------------- - * Samchon Framework's own | {@link Server} | {@link ClientDriver} - * Web-socket protocol | {@link WebServer} | {@link WebClientDriver} - * DedicatedWorker | {@link DedicatedWorkerServer} | {@link DedicatedWorkerClientDriver} - * SharedWorker | {@link SharedWorkerServer} | {@link SharedWorkerClientDriver} - * - * Below codes and classes will be good examples for comprehending how to open a server and handle remote clients. - * - https://github.com/samchon/framework/blob/master/ts/examples/calculator/calculator-server.ts - * - https://github.com/samchon/framework/blob/master/ts/examples/chat-server/server.ts - * - {@link service.Server} - * - {@link external.ExternalClientArray} - * - {@link slave.SlaveServer} - * - * If you're embarrased because your class already extended another one, then use {@link IServerBase}. - * - * - * - * - * - * @see {@link WebClientDriver}, {@link WebServerBase} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserver) - * @author Jeongho Nam - */ - abstract class WebServer implements IServer { - /** - * @hidden - */ - private http_server_; - /** - * @hidden - */ - private sequence_; - /** - * @hidden - */ - private my_port_; - /** - * Default Constructor. - */ - constructor(); - /** - * @inheritdoc - */ - open(port: number): void; - /** - * @inheritdoc - */ - close(): void; - /** - * @inheritdoc - */ - abstract addClient(driver: WebClientDriver): void; - /** - * @hidden - */ - private handle_request(request); - /** - * @hidden - */ - private get_session_id(cookies); - /** - * @hidden - */ - private issue_session_id(); - } -} -declare namespace samchon.protocol { - /** - * A SharedWorker server. - * - * The {@link DedicatedWorkerServer} is an abstract class is realized to open a DedicatedWorker server and accept - * web-browser client (master). Extends this {@link DedicatedWorkerServer} class and overrides - * {@link addClient addClient()} method to define what to do with a newly connected - * {@link DedicatedWorkerClientDriver remote client}. - * - * #### Why DedicatedWorker be a server? - * In JavaScript environment, there's no way to implement multi-threading function. Instead, JavaScript supports the - * **Worker**, creating a new process. However, the **Worker** does not shares memory addresses. To integrate the - * **Worker** with its master, only communication with string or binary data is allowed. Doesn't it seem like a network - * communication? Furthermore, there's not any difference between the worker communication and network communication. - * It's the reason why Samchon Framework considers the **Worker** as a network node. - * - * The class {@link DedicatedWorkerCommunicator} is designed make such relationship. From now on, DedicatedWorker is a - * {@link DedicatedWorkerServer server} and {@link DedicatedWorkerServerConnector browser} is a client. Integrate the - * server and clients with this {@link DedicatedWorkerCommunicator}. - * - * #### [Inherited] {@link IServer} - * {@link IServer} is an interfaec for server classes who are providing methods for {@link open opening a server} and - * {@link IClientDriver accepting clients}. - * - * To open a server, extends one of derived class under below considedring which protocol to follow first. At next, - * overrides {@link addClient addClient()} method who accepts a newly connected client as an {@link IClientDriver} - * object. Then at last, call {@link open open()} method with specified port number. - * - * Protocol | Derived Type | Related {@link IClientDriver} - * ------------------------|-------------------------------|------------------------------------- - * Samchon Framework's own | {@link Server} | {@link ClientDriver} - * Web-socket protocol | {@link WebServer} | {@link WebClientDriver} - * DedicatedWorker | {@link DedicatedWorkerServer} | {@link DedicatedWorkerClientDriver} - * SharedWorker | {@link SharedWorkerServer} | {@link SharedWorkerClientDriver} - * - * Below codes and classes will be good examples for comprehending how to open a server and handle remote clients. - * - https://github.com/samchon/framework/blob/master/ts/examples/calculator/calculator-server.ts - * - https://github.com/samchon/framework/blob/master/ts/examples/chat-server/server.ts - * - {@link service.Server} - * - {@link external.ExternalClientArray} - * - {@link slave.SlaveServer} - * - * If you're embarrased because your class already extended another one, then use {@link IServerBase}. - * - * - * - * - * - * @see {@link DedicatedWorkerClientDriver}, {@link DedicatedWorkerServerBase} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserver) - * @author Jeongho Nam - */ - abstract class DedicatedWorkerServer implements IServer { - /** - * @inheritdoc - */ - open(): void; - /** - * @inheritdoc - */ - close(): void; - /** - * @inheritdoc - */ - abstract addClient(driver: DedicatedWorkerClientDriver): void; - } -} -declare namespace samchon.protocol { - /** - * A SharedWorker server. - * - * The {@link SharedWorker} is an abstract class is realized to open a SharedWorker server and accept web-browser - * clients. Extends this {@link SharedWorkerServer} class and overrides {@link addClient addClient()} method to - * define what to do with newly connected {@link SharedWorkerClientDriver remote clients}. - * - * #### Why SharedWorker be a server? - * SharedWorker, it allows only an instance (process) to be created whether the SharedWorker is declared in a browser - * or multiple browsers. To integrate them, messages are being sent and received. Doesn't it seem like a relationship - * between a server and clients? Thus, Samchon Framework consider the SharedWorker as a server and browsers as - * clients. - * - * The class {@link SharedWorkerCommunicator} is designed make such relationship. From now on, SharedWorker is a - * {@link SharedWorkerServer server} and {@link SharedWorkerServerConnector browsers} are clients. Integrate the - * server and clients with this {@link SharedWorkerCommunicator}. - * - * #### [Inherited] {@link IServer} - * {@link IServer} is an interfaec for server classes who are providing methods for {@link open opening a server} and - * {@link IClientDriver accepting clients}. - * - * To open a server, extends one of derived class under below considedring which protocol to follow first. At next, - * overrides {@link addClient addClient()} method who accepts a newly connected client as an {@link IClientDriver} - * object. Then at last, call {@link open open()} method with specified port number. - * - * Protocol | Derived Type | Related {@link IClientDriver} - * ------------------------|-------------------------------|------------------------------------- - * Samchon Framework's own | {@link Server} | {@link ClientDriver} - * Web-socket protocol | {@link WebServer} | {@link WebClientDriver} - * DedicatedWorker | {@link DedicatedWorkerServer} | {@link DedicatedWorkerClientDriver} - * SharedWorker | {@link SharedWorkerServer} | {@link SharedWorkerClientDriver} - * - * Below codes and classes will be good examples for comprehending how to open a server and handle remote clients. - * - https://github.com/samchon/framework/blob/master/ts/examples/calculator/calculator-server.ts - * - https://github.com/samchon/framework/blob/master/ts/examples/chat-server/server.ts - * - {@link service.Server} - * - {@link external.ExternalClientArray} - * - {@link slave.SlaveServer} - * - * If you're embarrased because your class already extended another one, then use {@link IServerBase}. - * - * - * - * - * - * @see {@link SharedWorkerClientDriver}, {@link SharedWorkerServerBase} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserver) - * @author Jeongho Nam - */ - abstract class SharedWorkerServer implements IServer { - /** - * @inheritdoc - */ - abstract addClient(driver: SharedWorkerClientDriver): void; - /** - * @inheritdoc - */ - open(): void; - /** - * @inheritdoc - */ - close(): void; - /** - * @hidden - */ - private handle_connect(event); - } -} -declare namespace samchon.protocol { - /** - * An interface for substitute server classes. - * - * {@link IServerBase} is an interface for substitue server classes who subrogate server's role. - * - * The easiest way to defining a server class is to extending one of them below, who implemented the {@link IServer}. - * However, it is impossible (that is, if the class is already extending another class), you can instead implement - * the {@link IServer} interface, create an {@link IServerBase} member, and write simple hooks to route calls into - * the aggregated {@link IServerBase}. - * - * Protocol | {@link IServer} | {@link IServerBase} | {@link IClientDriver} - * ------------------------|-------------------------------|-----------------------------------|------------------------------------- - * Samchon Framework's own | {@link Server} | {@link ServerBase} | {@link ClientDriver} - * Web-socket protocol | {@link WebServer} | {@link WebServerBase} | {@link WebClientDriver} - * DedicatedWorker | {@link DedicatedWorkerServer} | {@link DedicatedWorkerServerBase} | {@link DedicatedWorkerClientDriver} - * SharedWorker | {@link SharedWorkerServer} | {@link SharedWorkerServerBase} | {@link SharedWorkerClientDriver} - * - * After the hooking to aggregated {@link IServerBase} object, overrides {@link addClient addClient()} method who - * accepts a newly connected client as an {@link IClientDriver} object. At last, call {@link open open()} method with - * specified port number. - * - * ```typescript - * class MyServer extends Something implements IServer - * { - * private server_base_: IServerBase = new WebServerBase(this); - * - * public addClient(driver: IClientDriver): void - * { - * // WHAT TO DO WHEN A CLIENT HAS CONNECTED - * } - * - * public open(port: number): void - * { - * this.server_base_.open(); - * } - * public close(): void - * { - * this.server_base_.close(); - * } - * } - * ``` - * - * - * - * - * - * @see {@link IServer}, {@link IClientDriver} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserverbase) - * @author Jeongho Nam - */ - interface IServerBase extends IServer { - } -} -declare namespace samchon.protocol { - /** - * A substitute {@link Server}. - * - * The {@link ServerBase} is a substitute class who subrogates {@link Server}'s responsibility. - * - * #### [Inherited] {@link IServerBase} - * {@link IServerBase} is an interface for substitue server classes who subrogate server's role. - * - * The easiest way to defining a server class is to extending one of them below, who implemented the {@link IServer}. - * However, it is impossible (that is, if the class is already extending another class), you can instead implement - * the {@link IServer} interface, create an {@link IServerBase} member, and write simple hooks to route calls into - * the aggregated {@link IServerBase}. - * - * Protocol | {@link IServer} | {@link IServerBase} | {@link IClientDriver} - * ------------------------|-------------------------------|-----------------------------------|------------------------------------- - * Samchon Framework's own | {@link Server} | {@link ServerBase} | {@link ClientDriver} - * Web-socket protocol | {@link WebServer} | {@link WebServerBase} | {@link WebClientDriver} - * DedicatedWorker | {@link DedicatedWorkerServer} | {@link DedicatedWorkerServerBase} | {@link DedicatedWorkerClientDriver} - * SharedWorker | {@link SharedWorkerServer} | {@link SharedWorkerServerBase} | {@link SharedWorkerClientDriver} - * - * After the hooking to aggregated {@link IServerBase} object, overrides {@link addClient addClient()} method who - * accepts a newly connected client as an {@link IClientDriver} object. At last, call {@link open open()} method with - * specified port number. - * - * ```typescript - * class MyServer extends Something implements IServer - * { - * private server_base_: IServerBase = new WebServerBase(this); - * - * public addClient(driver: IClientDriver): void - * { - * // WHAT TO DO WHEN A CLIENT HAS CONNECTED - * } - * - * public open(port: number): void - * { - * this.server_base_.open(); - * } - * public close(): void - * { - * this.server_base_.close(); - * } - * } - * ``` - * - * - * - * - * - * - * @see {@link Server}, {@link ClientDriver} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserverbase) - * @author Jeongho Nam - */ - class ServerBase extends Server implements IServerBase { - /** - * @hidden - */ - private hooker_; - /** - * Construct from a *hooker*. - * - * @param hooker A hooker throwing responsibility of server's role. - */ - constructor(hooker: IServer); - /** - * @inheritdoc - */ - addClient(driver: IClientDriver): void; - } -} -declare namespace samchon.protocol { - /** - * A substitute {@link WebServer}. - * - * The {@link WebServerBase} is a substitute class who subrogates {@link WebServer}'s responsibility. - * - * #### [Inherited] {@link IServerBase} - * {@link IServerBase} is an interface for substitue server classes who subrogate server's role. - * - * The easiest way to defining a server class is to extending one of them below, who implemented the {@link IServer}. - * However, it is impossible (that is, if the class is already extending another class), you can instead implement - * the {@link IServer} interface, create an {@link IServerBase} member, and write simple hooks to route calls into - * the aggregated {@link IServerBase}. - * - * Protocol | {@link IServer} | {@link IServerBase} | {@link IClientDriver} - * ------------------------|-------------------------------|-----------------------------------|------------------------------------- - * Samchon Framework's own | {@link Server} | {@link ServerBase} | {@link ClientDriver} - * Web-socket protocol | {@link WebServer} | {@link WebServerBase} | {@link WebClientDriver} - * DedicatedWorker | {@link DedicatedWorkerServer} | {@link DedicatedWorkerServerBase} | {@link DedicatedWorkerClientDriver} - * SharedWorker | {@link SharedWorkerServer} | {@link SharedWorkerServerBase} | {@link SharedWorkerClientDriver} - * - * After the hooking to aggregated {@link IServerBase} object, overrides {@link addClient addClient()} method who - * accepts a newly connected client as an {@link IClientDriver} object. At last, call {@link open open()} method with - * specified port number. - * - * ```typescript - * class MyServer extends Something implements IServer - * { - * private server_base_: IServerBase = new WebServerBase(this); - * - * public addClient(driver: IClientDriver): void - * { - * // WHAT TO DO WHEN A CLIENT HAS CONNECTED - * } - * - * public open(port: number): void - * { - * this.server_base_.open(); - * } - * public close(): void - * { - * this.server_base_.close(); - * } - * } - * ``` - * - * - * - * - * - * @see {@link WebServer}, {@link WebClientDriver} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserverbase) - * @author Jeongho Nam - */ - class WebServerBase extends WebServer implements IServerBase { - /** - * @hidden - */ - private hooker_; - /** - * Construct from a *hooker*. - * - * @param hooker A hooker throwing responsibility of server's role. - */ - constructor(hooker: IServer); - /** - * @inheritdoc - */ - addClient(driver: IClientDriver): void; - } -} -declare namespace samchon.protocol { - /** - * A substitute {@link DedicatedWorkerServer}. - * - * The {@link DedicatedWorkerServerBase} is a substitute class who subrogates {@link DedicatedWorkerServer}'s - * responsibility. - * - * #### [Inherited] {@link IServerBase} - * {@link IServerBase} is an interface for substitue server classes who subrogate server's role. - * - * The easiest way to defining a server class is to extending one of them below, who implemented the {@link IServer}. - * However, it is impossible (that is, if the class is already extending another class), you can instead implement - * the {@link IServer} interface, create an {@link IServerBase} member, and write simple hooks to route calls into - * the aggregated {@link IServerBase}. - * - * Protocol | {@link IServer} | {@link IServerBase} | {@link IClientDriver} - * ------------------------|-------------------------------|-----------------------------------|------------------------------------- - * Samchon Framework's own | {@link Server} | {@link ServerBase} | {@link ClientDriver} - * Web-socket protocol | {@link WebServer} | {@link WebServerBase} | {@link WebClientDriver} - * DedicatedWorker | {@link DedicatedWorkerServer} | {@link DedicatedWorkerServerBase} | {@link DedicatedWorkerClientDriver} - * SharedWorker | {@link SharedWorkerServer} | {@link SharedWorkerServerBase} | {@link SharedWorkerClientDriver} - * - * After the hooking to aggregated {@link IServerBase} object, overrides {@link addClient addClient()} method who - * accepts a newly connected client as an {@link IClientDriver} object. At last, call {@link open open()} method with - * specified port number. - * - * ```typescript - * class MyServer extends Something implements IServer - * { - * private server_base_: IServerBase = new WebServerBase(this); - * - * public addClient(driver: IClientDriver): void - * { - * // WHAT TO DO WHEN A CLIENT HAS CONNECTED - * } - * - * public open(port: number): void - * { - * this.server_base_.open(); - * } - * public close(): void - * { - * this.server_base_.close(); - * } - * } - * ``` - * - * - * - * - * - * @see {@link DedicatedWorkerServer}, {@link DedicatedWorkerClientDriver} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserverbase) - * @author Jeongho Nam - */ - class DedicatedWorkerServerBase extends DedicatedWorkerServer implements IServerBase { - /** - * @hidden - */ - private hooker_; - /** - * Construct from a *hooker*. - * - * @param hooker A hooker throwing responsibility of server's role. - */ - constructor(hooker: IServer); - /** - * @inheritdoc - */ - addClient(driver: IClientDriver): void; - } -} -declare namespace samchon.protocol { - /** - * A substitute {@link SharedWorkerServer}. - * - * The {@link SharedWorkerServerBase} is a substitute class who subrogates {@link SharedWorkerServer}'s - * responsibility. - * - * #### [Inherited] {@link IServerBase} - * {@link IServerBase} is an interface for substitue server classes who subrogate server's role. - * - * The easiest way to defining a server class is to extending one of them below, who implemented the {@link IServer}. - * However, it is impossible (that is, if the class is already extending another class), you can instead implement - * the {@link IServer} interface, create an {@link IServerBase} member, and write simple hooks to route calls into - * the aggregated {@link IServerBase}. - * - * Protocol | {@link IServer} | {@link IServerBase} | {@link IClientDriver} - * ------------------------|-------------------------------|-----------------------------------|------------------------------------- - * Samchon Framework's own | {@link Server} | {@link ServerBase} | {@link ClientDriver} - * Web-socket protocol | {@link WebServer} | {@link WebServerBase} | {@link WebClientDriver} - * DedicatedWorker | {@link DedicatedWorkerServer} | {@link DedicatedWorkerServerBase} | {@link DedicatedWorkerClientDriver} - * SharedWorker | {@link SharedWorkerServer} | {@link SharedWorkerServerBase} | {@link SharedWorkerClientDriver} - * - * After the hooking to aggregated {@link IServerBase} object, overrides {@link addClient addClient()} method who - * accepts a newly connected client as an {@link IClientDriver} object. At last, call {@link open open()} method with - * specified port number. - * - * ```typescript - * class MyServer extends Something implements IServer - * { - * private server_base_: IServerBase = new WebServerBase(this); - * - * public addClient(driver: IClientDriver): void - * { - * // WHAT TO DO WHEN A CLIENT HAS CONNECTED - * } - * - * public open(port: number): void - * { - * this.server_base_.open(); - * } - * public close(): void - * { - * this.server_base_.close(); - * } - * } - * ``` - * - * - * - * - * - * @see {@link SharedWorkerServer}, {@link SharedWorkerClientDriver} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserverbase) - * @author Jeongho Nam - */ - class SharedWorkerServerBase extends SharedWorkerServer implements IServerBase { - /** - * @hidden - */ - private hooker_; - /** - * Construct from a *hooker*. - * - * @param hooker A hooker throwing responsibility of server's role. - */ - constructor(hooker: IServer); - /** - * @inheritdoc - */ - addClient(driver: IClientDriver): void; - } -} -declare namespace samchon.protocol { - /** - * An interface for server connector. - * - * {@link IServerConnector} is a type of {@link ICommunicator}, specified for server connector classes who connect to - * the remote server as a client. {@link IServerConnector} provides {@link connect connection method} and takes full - * charge of network communication with the remote server. - * - * Declare specific type of {@link IServerConnector} from {@link IProtocol listener} and call the - * {@link connect connect()} method. Then whenever a replied message comes from the remote system, the message will - * be converted to an {@link Invoke} object and the {@link Invoke} object will be shifted to the - * {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} method. Below code is an example - * connecting to remote server and interacting with it. - * - * - https://github.com/samchon/framework/blob/master/ts/examples/calculator/calculator-application.ts - * - * Note that, protocol of this client and remote server must be matched. Thus, before determining specific type of - * this {@link IServerConnector}, you've to consider which protocol and type the remote server follows. - * - * Protocol | Derived Type | Connect to - * ------------------------|----------------------------------------|------------------------------- - * Samchon Framework's own | {@link ServerConnector} | {@link Server} - * Web-socket protocol | {@link WebServerConnector} | {@link WebServer} - * DedicatedWorker | {@link DedicatedWorkerServerConnector} | {@link DedicatedWorkerServer} - * SharedWorker | {@link SharedWorkerServerConnector} | {@link SharedWorkerServer} - * - * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_basic_components.png) - * - * @see {@link IServer}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserverconnector) - * @author Jeongho Nam - */ - interface IServerConnector extends ICommunicator { - /** - * Callback function for connection completed. - * - * When you call {@link connect connect()} and the connection has completed, then this call back function - * {@link onConnect} will be called. Note that, if the listener of this {@link onConnect} is a member method of - * some class, then you've use the ```bind```. - */ - onConnect: Function; - /** - * Connect to a server. - * - * Connects to a server with specified *host* address and *port* number. After the connection has - * succeeded, callback function {@link onConnect} is called. Listening data from the connected server also begins. - * Replied messages from the connected server will be converted to {@link Invoke} classes and will be shifted to - * the {@link WebCommunicator.listener listener}'s {@link IProtocol.replyData replyData()} method. - * - * If the connection fails immediately, either an event is dispatched or an exception is thrown: an error - * event is dispatched if a host was specified, and an exception is thrown if no host was specified. Otherwise, - * the status of the connection is reported by an event. If the socket is already connected, the existing - * connection is closed first. - * - * @param ip The name or IP address of the host to connect to. - * If no host is specified, the host that is contacted is the host where the calling file resides. - * If you do not specify a host, use an event listener to determine whether the connection was - * successful. - * @param port The port number to connect to. - */ - connect(ip: string, port: number): void; - } -} -declare namespace samchon.protocol { - /** - * Server connnector. - * - * {@link ServerConnector} is a class connecting to remote server who follows Samchon Framework's own protocol and - * taking full charge of network communication with the remote server. Create a {@link ServerConnector} instance from - * the {@IProtocol listener} and call the {@link connect connect()} method. - * - * #### [Inherited] {@link IServerConnector} - * {@link IServerConnector} is a type of {@link ICommunicator}, specified for server connector classes who connect to - * the remote server as a client. {@link IServerConnector} provides {@link connect connection method} and takes full - * charge of network communication with the remote server. - * - * Declare specific type of {@link IServerConnector} from {@link IProtocol listener} and call the - * {@link connect connect()} method. Then whenever a replied message comes from the remote system, the message will - * be converted to an {@link Invoke} object and the {@link Invoke} object will be shifted to the - * {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} method. - * - * Note that, protocol of this client and remote server must be matched. Thus, before determining specific type of - * this {@link IServerConnector}, you've to consider which protocol and type the remote server follows. - * - * Protocol | Derived Type | Connect to - * ------------------------|----------------------------------------|------------------------------- - * Samchon Framework's own | {@link ServerConnector} | {@link Server} - * Web-socket protocol | {@link WebServerConnector} | {@link WebServer} - * DedicatedWorker | {@link DedicatedWorkerServerConnector} | {@link DedicatedWorkerServer} - * SharedWorker | {@link SharedWorkerServerConnector} | {@link SharedWorkerServer} - * - * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_basic_components.png) - * - * @see {@link Server}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserverconnector) - * @author Jeongho Nam - */ - class ServerConnector extends Communicator implements IServerConnector { - /** - * @inheritdoc - */ - onConnect: Function; - /** - * Construct from *listener*. - * - * @param listener A listener object to listen replied message from newly connected client in - * {@link IProtocol.replyData replyData()} as an {@link Invoke} object. - */ - constructor(listener: IProtocol); - /** - * @inheritdoc - */ - connect(ip: string, port: number): void; - /** - * @hidden - */ - private handle_connect(...arg); - } -} -declare namespace samchon.protocol { - /** - * A server connector for web-socket protocol. - * - * {@link WebServerConnector} is a class connecting to remote server who follows Web-socket protocol and taking full - * charge of network communication with the remote server. Create an {@link WebServerConnector} instance from the - * {@IProtocol listener} and call the {@link connect connect()} method. - * - * #### [Inherited] {@link IServerConnector} - * {@link IServerConnector} is a type of {@link ICommunicator}, specified for server connector classes who connect to - * the remote server as a client. {@link IServerConnector} provides {@link connect connection method} and takes full - * charge of network communication with the remote server. - * - * Declare specific type of {@link IServerConnector} from {@link IProtocol listener} and call the - * {@link connect connect()} method. Then whenever a replied message comes from the remote system, the message will - * be converted to an {@link Invoke} class and the {@link Invoke} object will be shifted to the - * {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} method. - * - * Note that, protocol of this client and remote server must be matched. Thus, before determining specific type of - * this {@link IServerConnector}, you've to consider which protocol and type the remote server follows. - * - * Protocol | Derived Type | Connect to - * ------------------------|----------------------------------------|------------------------------- - * Samchon Framework's own | {@link ServerConnector} | {@link Server} - * Web-socket protocol | {@link WebServerConnector} | {@link WebServer} - * DedicatedWorker | {@link DedicatedWorkerServerConnector} | {@link DedicatedWorkerServer} - * SharedWorker | {@link SharedWorkerServerConnector} | {@link SharedWorkerServer} - * - * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_basic_components.png) - * - * @see {@link WebServer}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserverconnector) - * @author Jeongho Nam - */ - class WebServerConnector extends WebCommunicator implements IServerConnector { - /** - * @hidden - */ - private browser_socket_; - /** - * @hidden - */ - private node_client_; - /** - * @inheritdoc - */ - onConnect: Function; - /** - * Construct from *listener*. - * - * @param listener A listener object to listen replied message from newly connected client in - * {@link IProtocol.replyData replyData()} as an {@link Invoke} object. - */ - constructor(listener: IProtocol); - /** - * Connect to a web server. - * - * Connects to a server with specified *host* address, *port* number and *path*. After the connection has - * succeeded, callback function {@link onConnect} is called. Listening data from the connected server also begins. - * Replied messages from the connected server will be converted to {@link Invoke} classes and will be shifted to - * the {@link WebCommunicator.listener listener}'s {@link IProtocol.replyData replyData()} method. - * - * If the connection fails immediately, either an event is dispatched or an exception is thrown: an error - * event is dispatched if a host was specified, and an exception is thrown if no host was specified. Otherwise, - * the status of the connection is reported by an event. If the socket is already connected, the existing - * connection is closed first. - * - * @param ip The name or IP address of the host to connect to. - * If no host is specified, the host that is contacted is the host where the calling file resides. - * If you do not specify a host, use an event listener to determine whether the connection was - * successful. - * @param port The port number to connect to. - * @param path Path of service which you want. - */ - connect(ip: string, port: number, path?: string): void; - /** - * @inheritdoc - */ - close(): void; - /** - * @inheritdoc - */ - sendData(invoke: Invoke): void; - /** - * @hidden - */ - private handle_browser_connect(event); - /** - * @hidden - */ - private handle_browser_message(event); - /** - * @hidden - */ - private handle_node_connect(connection); - } -} -declare namespace samchon.protocol { - /** - * A server connector for DedicatedWorker. - * - * {@link DedicatedWorkerServerConnector} is a class connecting to SharedWorker and taking full charge of network - * communication with the SharedWorker. Create an {@link DedicatedWorkerServer} instance from the - * {@IProtocol listener} and call the {@link connect connect()} method. - * - * #### Why DedicatedWorker be a server? - * In JavaScript environment, there's no way to implement multi-threading function. Instead, JavaScript supports the - * **Worker**, creating a new process. However, the **Worker** does not shares memory addresses. To integrate the - * **Worker** with its master, only communication with string or binary data is allowed. Doesn't it seem like a network - * communication? Furthermore, there's not any difference between the worker communication and network communication. - * It's the reason why Samchon Framework considers the **Worker** as a network node. - * - * The class {@link DedicatedWorkerCommunicator} is designed make such relationship. From now on, DedicatedWorker is a - * {@link DedicatedWorkerServer server} and {@link DedicatedWorkerServerConnector browser} is a client. Integrate the - * server and clients with this {@link DedicatedWorkerCommunicator}. - * - * #### [Inherited] {@link IServerConnector} - * {@link IServerConnector} is a type of {@link ICommunicator}, specified for server connector classes who connect to - * the remote server as a client. {@link IServerConnector} provides {@link connect connection method} and takes full - * charge of network communication with the remote server. - * - * Declare specific type of {@link IServerConnector} from {@link IProtocol listener} and call the - * {@link connect connect()} method. Then whenever a replied message comes from the remote system, the message will - * be converted to an {@link Invoke} class and the {@link Invoke} object will be shifted to the - * {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} method. - * - * Note that, protocol of this client and remote server must be matched. Thus, before determining specific type of - * this {@link IServerConnector}, you've to consider which protocol and type the remote server follows. - * - * Protocol | Derived Type | Connect to - * ------------------------|----------------------------------------|------------------------------- - * Samchon Framework's own | {@link ServerConnector} | {@link Server} - * Web-socket protocol | {@link WebServerConnector} | {@link WebServer} - * DedicatedWorker | {@link DedicatedWorkerServerConnector} | {@link DedicatedWorkerServer} - * SharedWorker | {@link SharedWorkerServerConnector} | {@link SharedWorkerServer} - * - * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_basic_components.png) - * - * @see {@link DedicatedWorkerServer}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserverconnector) - * @author Jeongho Nam - */ - class DedicatedWorkerServerConnector extends DedicatedWorkerCommunicator implements IServerConnector { - /** - * @hidden - */ - private worker; - /** - * @inheritdoc - */ - onConnect: Function; - /** - * Construct from *listener*. - * - * @param listener A listener object to listen replied message from newly connected client in - * {@link IProtocol.replyData replyData()} as an {@link Invoke} object. - */ - constructor(listener: IProtocol); - /** - * @inheritdoc - */ - connect(jsFile: string): void; - /** - * @inheritdoc - */ - close(): void; - /** - * @inheritdoc - */ - sendData(invoke: Invoke): void; - } -} -declare namespace samchon.protocol { - /** - * A server connector for SharedWorker. - * - * {@link SharedWorkerServerConnector} is a class connecting to SharedWorker and taking full charge of network - * communication with the SharedWorker. Create an {@link SharedWorkerServerConnector} instance from the - * {@IProtocol listener} and call the {@link connect connect()} method. - * - * #### Why SharedWorker be a server? - * SharedWorker, it allows only an instance (process) to be created whether the SharedWorker is declared in a browser - * or multiple browsers. To integrate them, messages are being sent and received. Doesn't it seem like a relationship - * between a server and clients? Thus, Samchon Framework consider the SharedWorker as a server and browsers as - * clients. - * - * The class {@link SharedWorkerCommunicator} is designed make such relationship. From now on, SharedWorker is a - * {@link SharedWorkerServer server} and {@link SharedWorkerServerConnector browsers} are clients. Integrate the - * server and clients with this {@link SharedWorkerCommunicator}. - * - * #### [Inherited] {@link IServerConnector} - * {@link IServerConnector} is a type of {@link ICommunicator}, specified for server connector classes who connect to - * the remote server as a client. {@link IServerConnector} provides {@link connect connection method} and takes full - * charge of network communication with the remote server. - * - * Declare specific type of {@link IServerConnector} from {@link IProtocol listener} and call the - * {@link connect connect()} method. Then whenever a replied message comes from the remote system, the message will - * be converted to an {@link Invoke} class and the {@link Invoke} object will be shifted to the - * {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} method. - * - * Note that, protocol of this client and remote server must be matched. Thus, before determining specific type of - * this {@link IServerConnector}, you've to consider which protocol and type the remote server follows. - * - * Protocol | Derived Type | Connect to - * ------------------------|----------------------------------------|------------------------------- - * Samchon Framework's own | {@link ServerConnector} | {@link Server} - * Web-socket protocol | {@link WebServerConnector} | {@link WebServer} - * DedicatedWorker | {@link DedicatedWorkerServerConnector} | {@link DedicatedWorkerServer} - * SharedWorker | {@link SharedWorkerServerConnector} | {@link SharedWorkerServer} - * - * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_basic_components.png) - * - * @see {@link SharedWorkerServer}, {@link IProtocol} - * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserverconnector) - * @author Jeongho Nam - */ - class SharedWorkerServerConnector extends SharedWorkerCommunicator implements IServerConnector { - /** - * @inheritdoc - */ - onConnect: Function; - /** - * Construct from *listener*. - * - * @param listener A listener object to listen replied message from newly connected client in - * {@link IProtocol.replyData replyData()} as an {@link Invoke} object. - */ - constructor(listener: IProtocol); - /** - * Connect to a SharedWorker. - * - * Connects to a server with specified *jstFile* path. If a SharedWorker instance of the *jsFile* is not - * constructed yet, then the SharedWorker will be newly constructed. Otherwise the SharedWorker already exists, - * then connect to the SharedWorker. After those processes, callback function {@link onConnect} is called. - * Listening data from the connected server also begins. Replied messages from the connected server will be - * converted to {@link Invoke} classes and will be shifted to the {@link WebCommunicator.listener listener}'s - * {@link IProtocol.replyData replyData()} method. - * - * If the connection fails immediately, either an event is dispatched or an exception is thrown: an error - * event is dispatched if a host was specified, and an exception is thrown if no host was specified. Otherwise, - * the status of the connection is reported by an event. If the socket is already connected, the existing - * connection is closed first. - * - * @param jsFile Path of JavaScript file to execute who defines SharedWorker. - */ - connect(jsFile: string): void; - } -} -declare namespace samchon.protocol { - /** - * @hidden - */ - namespace socket { - type socket = any; - type server = any; - type http_server = any; - } - /** - * @hidden - */ - namespace websocket { - type connection = any; - type request = any; - type IMessage = any; - type ICookie = any; - type client = any; - } -} -declare namespace samchon.templates.distributed { - /** - * Master of Distributed Processing System, a server accepting slave clients. - * - * The {@link DistributedClientArray} is an abstract class, derived from the {@link DistributedSystemArray} class, - * opening a server accepting {@link DistributedSystem distributed clients}. - * - * Extends this {@link DistributedClientArray}, overrides {@link createServerBase createServerBase()} to determine - * which protocol to follow and {@link createExternalClient createExternalClient()} creating child - * {@link DistributedSystem} object. After the extending and overridings, open this server using the - * {@link open open()} method. - * - * #### [Inherited] {@link DistributedSystemArray} - * The {@link DistributedSystemArray} is an abstract class containing and managing remote distributed **slave** system - * drivers, {@link DistributedSystem} objects. Within framework of network, {@link DistributedSystemArray} represents - * your system, a **Master** of *Distributed Processing System* that requesting *distributed process* to **slave** - * systems and the children {@link DistributedSystem} objects represent the remote **slave** systems, who is being - * requested the *distributed processes*. - * - * The {@link DistributedSystemArray} contains {@link DistributedProcess} objects directly. You can request a - * **distributed process** through the {@link DistributedProcess} object. You can access the - * {@link DistributedProcess} object(s) with those methods: - * - * - {@link hasProcess} - * - {@link getProcess} - * - {@link insertProcess} - * - {@link eraseProcess} - * - {@link getProcessMap} - * - * When you need the **distributed process**, call the {@link DistributedProcess.sendData} method. Then the - * {@link DistributedProcess} will find the most idle {@link DistributedSystem} object who represents a distributed - * **slave **system. The {@link Invoke} message will be sent to the most idle {@link DistributedSystem} object. When - * the **distributed process** has completed, then {@link DistributedSystem.getPerformance performance index} and - * {@link DistributedProcess.getResource resource index} of related objects will be revaluated. - * - * - * - * - * - * #### Parallel Process - * This {@link DistributedSystemArray} class is derived from the {@link ParallelSystemArray} class, so you can request - * a **parallel process**, too. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices will - * be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * #### Proxy Pattern - * This class {@link DistributedSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link DistributedSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *Proxy Pattern*: - * - * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
    - *
  • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
  • - *
  • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
  • - *
  • Those strategy is called *Proxy Pattern*.
  • - *
- * - * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - abstract class DistributedClientArray extends DistributedSystemArray implements external.IExternalClientArray { - /** - * @hidden - */ - private server_base_; - /** - * Default Constructor. - */ - constructor(); - /** - * Factory method creating {@link IServerBase} object. - * - * This method {@link createServerBase createServerBase()} determines which protocol is used in this server, - * {@link ExternalClientArray}. If the protocol is determined, then {@link ExternalSystem external clients} who - * may connect to {@link ExternalClientArray this server} must follow the specified protocol. - * - * Overrides the {@link createServerBase createServerBase()} method to create and return one of them: - * - * - {@link ServerBase} - * - {@link WebServerBase} - * - {@link SharedWorkerServerBase} - * - * @return A new {@link IServerBase} object. - */ - protected abstract createServerBase(): protocol.IServerBase; - /** - * Add a newly connected remote client. - * - * When a {@link IClientDriver remote client} connects to this *master server of parallel processing system*, - * then this {@link ParallelClientArray} creates a child {@link ParallelSystem parallel client} object through - * the {@link createExternalClient createExternalClient()} method and {@link insert inserts} it. - * - * @param driver A communicator for external client. - */ - addClient(driver: protocol.IClientDriver): void; - /** - * (Deprecated) Factory method creating child object. - * - * The method {@link createChild createChild()} is deprecated. Don't use and override this. - * - * Note that, the {@link ParallelClientArray} is a server accepting {@link ParallelSystem parallel clients}. - * There's no way to creating the {@link ParallelSystem parallel clients} in advance before opening the server. - * - * @param xml An {@link XML} object represents the child {@link ParallelSystem} object. - * @return ```null``` - */ - createChild(xml: library.XML): System; - /** - * Factory method creating {@link DistributedSystem} object. - * - * The method {@link createExternalClient createExternalClient()} is a factory method creating a child - * {@link ParallelSystem} object, that is called whenever a parallel client has connected, by - * {@link addClient addClient()}. - * - * Overrides this {@link createExternalClient} method and creates a type of {@link DistributedSystem} object with - * the *driver* that communicates with the parallel client. After the creation, returns the object. Then whenever - * a parallel client has connected, matched {@link DistributedSystem} object will be constructed and - * {@link insert inserted} into this {@link DistributedSystemArray} object. - * - * @param driver A communicator with the parallel client. - * @return A newly created {@link ParallelSystem} object. - */ - protected abstract createExternalClient(driver: protocol.IClientDriver): System; - /** - * @inheritdoc - */ - open(port: number): void; - /** - * @inheritdoc - */ - close(): void; - } -} -declare namespace samchon.templates.distributed { - /** - * Mediator of Distributed Processing System, a server accepting slave clients. - * - * The {@link DistributedClientArrayMediator} is an abstract class, derived from {@link DistributedSystemArrayMediator} - * class, opening a server accepting {@link DistributedSystem distributed clients} as a **master**. - * - * Extends this {@link DistributedClientArrayMediator}, overrides {@link createServerBase createServerBase()} to - * determine which protocol to follow and {@link createExternalClient createExternalClient()} creating child - * {@link DistributedSystem} object. After the extending and overridings, open this server using the - * {@link open open()} method. - * - * #### [Inherited] {@link DistributedSystemArrayMediator} - * The {@link DistributedSystemArrayMediator} class be a master for its slave systems, and be a slave to its master - * system at the same time. This {@link DistributedSystemArrayMediator} be a master system, containing and managing - * {@link DistributedSystem} objects, which represent distributed slave systems, by extending - * {@link DistributedSystemArray} class. Also, be a slave system through {@link getMediator mediator} object, which is - * derived from the {@link SlaveSystem} class. - * - * As a slave, you can specify this {@link DistributedSystemArrayMediator} to be a client slave connecting to master - * server or a server slave accepting master client by overriding the {@link createMediator} method. - * Overrides the {@link createMediator createMediator()} method and return one of them: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * #### [Inherited] {@link DistributedSystemArray} - * The {@link DistributedSystemArray} is an abstract class containing and managing remote distributed **slave** system - * drivers, {@link DistributedSystem} objects. Within framework of network, {@link DistributedSystemArray} represents - * your system, a **Master** of *Distributed Processing System* that requesting *distributed process* to **slave** - * systems and the children {@link DistributedSystem} objects represent the remote **slave** systems, who is being - * requested the *distributed processes*. - * - * The {@link DistributedSystemArray} contains {@link DistributedProcess} objects directly. You can request a - * **distributed process** through the {@link DistributedProcess} object. You can access the - * {@link DistributedProcess} object(s) with those methods: - * - * - {@link hasProcess} - * - {@link getProcess} - * - {@link insertProcess} - * - {@link eraseProcess} - * - {@link getProcessMap} - * - * When you need the **distributed process**, call the {@link DistributedProcess.sendData} method. Then the - * {@link DistributedProcess} will find the most idle {@link DistributedSystem} object who represents a distributed - * **slave **system. The {@link Invoke} message will be sent to the most idle {@link DistributedSystem} object. When - * the **distributed process** has completed, then {@link DistributedSystem.getPerformance performance index} and - * {@link DistributedProcess.getResource resource index} of related objects will be revaluated. - * - * - * - * - * - * #### Parallel Process - * This {@link DistributedSystemArray} class is derived from the {@link ParallelSystemArray} class, so you can request - * a **parallel process**, too. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices will - * be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * #### Proxy Pattern - * This class {@link DistributedSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link DistributedSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *Proxy Pattern*: - * - * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
    - *
  • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
  • - *
  • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
  • - *
  • Those strategy is called *Proxy Pattern*.
  • - *
- * - * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - abstract class DistributedClientArrayMediator extends DistributedSystemArrayMediator implements external.IExternalClientArray { - /** - * A subrogator of {@link IServer server}'s role instead of this {@link ExternalClientArray}. - */ - private server_base_; - /** - * Default Constructor. - */ - constructor(); - /** - * Factory method creating {@link IServerBase} object. - * - * This method {@link createServerBase createServerBase()} determines which protocol is used in this - * {@link DistributedClientArrayMediator} object as a **master**. If the protocol is determined, then - * {@link DistributedSystem distributed clients} who may connect to {@link DistributedClientArrayMediator this - * server} must follow the specified protocol. - * - * Overrides the {@link createServerBase createServerBase()} method to create and return one of them: - * - * - {@link ServerBase} - * - {@link WebServerBase} - * - {@link SharedWorkerServerBase} - * - * @return A new {@link IServerBase} object. - */ - protected abstract createServerBase(): protocol.IServerBase; - /** - * Add a newly connected remote client. - * - * When a {@link IClientDriver remote client} connects to this *master server of distributed processing system*, - * then this {@link DistributedClientArrayMediator} creates a child {@link Distributed distributed client} object - * through the {@link createExternalClient createExternalClient()} method. - * - * @param driver A communicator for external client. - */ - addClient(driver: protocol.IClientDriver): void; - /** - * (Deprecated) Factory method creating child object. - * - * The method {@link createChild createChild()} is deprecated. Don't use and override this. - * - * Note that, the {@link DistributedClientArrayMediator} is a server accepting {@link DistributedSystem distributed - * clients} as a master. There's no way to creating the {@link DistributedSystem distributed clients} in advance - * before opening the server. - * - * @param xml An {@link XML} object represents the child {@link DistributedSystem} object. - * @return null - */ - createChild(xml: library.XML): System; - /** - * Factory method creating {@link DistributedSystem} object. - * - * The method {@link createExternalClient createExternalClient()} is a factory method creating a child - * {@link DistributedSystem} object, that is called whenever a distributed client has connected, by - * {@link addClient addClient()}. - * - * Overrides this {@link createExternalClient} method and creates a type of {@link DistributedSystem} object with - * the *driver* that communicates with the distributed client. After the creation, returns the object. Then whenever - * a distributed client has connected, matched {@link DistributedSystem} object will be constructed and - * {@link insert inserted} into this {@link DistributedClientArrayMediator} object. - * - * @param driver A communicator with the distributed client. - * @return A newly created {@link DistributedSystem} object. - */ - protected abstract createExternalClient(driver: protocol.IClientDriver): System; - /** - * @inheritdoc - */ - open(port: number): void; - /** - * @inheritdoc - */ - close(): void; - } -} -declare namespace samchon.templates.distributed { - /** - * A process of Distributed Processing System. - * - * The {@link DistributedProcess} is an abstract class who represents a **process**, *SOMETHING TO DISTRIBUTE* in a Distributed - * Processing System. Overrides the {@link DistributedProcess} and defines the *SOMETHING TO DISTRIBUTE*. - * - * Relationship between {@link DistributedSystem} and {@link DistributedProcess} objects are **M: N Associative**. - * Unlike {@link ExternalSystemRole}, the {@link DistributedProcess} objects are not belonged to a specific - * {@link DistributedSystem} object. The {@link DistributedProcess} objects are belonged to the - * {@link DistributedSystemArrayMediator} directly. - * - * When you need the **distributed process**, then call {@link sendData sendData()}. The {@link sendData} will find - * the most idle {@link DistributedSystem slave system} considering not only number of processes on progress, but also - * {@link DistributedSystem.getPerformance performance index} of each {@link DistributedSystem} object and - * {@link getResource resource index} of this {@link DistributedProcess} object. The {@link Invoke} message - * requesting the **distributed process** will be sent to the most idle {@link DistributedSystem slave system}. - * - * Those {@link DistributedSystem.getPerformance performance index} and {@link getResource resource index} are - * revaluated whenever the **distributed process** has completed basis on the execution time. - * - * - * - * - * - * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - abstract class DistributedProcess extends protocol.Entity implements protocol.IProtocol { - /** - * @hidden - */ - private system_array_; - /** - * A name, represents and identifies this {@link DistributedProcess process}. - * - * This {@link name} is an identifier represents this {@link DistributedProcess process}. This {@link name} is - * used in {@link DistributedSystemArray.getProcess} and {@link DistributedSystemArray.getProcess}, as a key elements. - * Thus, this {@link name} should be unique in its parent {@link DistributedSystemArray} object. - */ - protected name: string; - /** - * @hidden - */ - private progress_list_; - /** - * @hidden - */ - private history_list_; - /** - * @hidden - */ - private resource; - /** - * @hidden - */ - private enforced_; - /** - * Constrct from parent {@link DistributedSystemArray} object. - * - * @param systemArray The parent {@link DistributedSystemArray} object. - */ - constructor(systemArray: DistributedSystemArray); - /** - * Identifier of {@link ParallelProcess} is its {@link name}. - */ - key(): string; - /** - * Get parent {@link DistributedSystemArray} object. - * - * @return The parent {@link DistributedSystemArray} object. - */ - getSystemArray(): DistributedSystemArray; - /** - * Get parent {@link DistributedSystemArray} object. - * - * @return The parent {@link DistributedSystemArray} object. - */ - getSystemArray>(): SystemArray; - /** - * Get name, who represents and identifies this process. - */ - getName(): string; - /** - * Get resource index. - * - * Get *resource index* that indicates how much this {@link DistributedProcess process} is heavy. - * - * If this {@link DistributedProcess process} does not have any {@link Invoke} message had handled, then the - * *resource index* will be ```1.0```, which means default and average value between all - * {@link DistributedProcess} instances (that are belonged to a same {@link DistributedSystemArray} object). - * - * You can specify the *resource index* by yourself, but notice that, if the *resource index* is higher than - * other {@link DistributedProcess} objects, then this {@link DistributedProcess process} will be ordered to - * handle less processes than other {@link DistributedProcess} objects. Otherwise, the *resource index* is - * lower than others, of course, much processes will be requested. - * - * - {@link setResource setResource()} - * - {@link enforceResource enforceResource()} - * - * Unless {@link enforceResource enforceResource()} is called, This *resource index* is **revaluated** whenever - * {@link sendData sendData()} is called. - * - * @return Resource index. - */ - getResource(): number; - /** - * Set resource index. - * - * Set *resource index* that indicates how much this {@link DistributedProcess process} is heavy. This - * *resource index* can be **revaulated**. - * - * Note that, initial and average *resource index* of {@link DistributedProcess} objects are ```1.0```. If the - * *resource index* is higher than other {@link DistributedProcess} objects, then this - * {@link DistributedProcess} will be ordered to handle more processes than other {@link DistributedProcess} - * objects. Otherwise, the *resource index* is lower than others, of course, less processes will be requested. - * - * Unlike {@link enforceResource}, configuring *resource index* by this {@link setResource} allows the - * **revaluation**. This **revaluation** prevents wrong valuation from user. For example, you *mis-valuated* the - * *resource index*. The {@link DistributedProcess process} is much heavier than any other, but you estimated it - * to the lightest one. It looks like a terrible case that causes - * {@link DistributedSystemArray entire distributed processing system} to be slower, however, don't mind. The - * {@link DistributedProcess process} will the direct to the *propriate resource index* eventually with the - * **revaluation**. - * - * - The **revaluation** is caused by the {@link sendData sendData()} method. - * - * @param val New resource index, but can be revaluated. - */ - setResource(val: number): void; - /** - * Enforce resource index. - * - * Enforce *resource index* that indicates how much heavy the {@link DistributedProcess process is}. The - * *resource index* will be fixed, never be **revaluated**. - * - * Note that, initial and average *resource index* of {@link DistributedProcess} objects are ```1.0```. If the - * *resource index* is higher than other {@link DistributedProcess} objects, then this - * {@link DistributedProcess} will be ordered to handle more processes than other {@link DistributedProcess} - * objects. Otherwise, the *resource index* is lower than others, of course, less processes will be requested. - * - * The difference between {@link setResource} and this {@link enforceResource} is allowing **revaluation** or not. - * This {@link enforceResource} does not allow the **revaluation**. The *resource index* is clearly fixed and - * never be changed by the **revaluation**. But you've to keep in mind that, you can't avoid the **mis-valuation** - * with this {@link enforceResource}. - * - * For example, there's a {@link DistributedProcess process} much heavier than any other, but you - * **mis-estimated** it to the lightest. In that case, there's no way. The - * {@link DistributedSystemArray entire distributed processing system} will be slower by the **mis-valuation**. - * By the reason, using {@link enforceResource}, it's recommended only when you can clearly certain the - * *resource index*. If you can't certain the *resource index* but want to recommend, then use {@link setResource} - * instead. - * - * @param val New resource index to be fixed. - */ - enforceResource(val: number): void; - /** - * @hidden - */ - private compute_average_elapsed_time(); - /** - * @inheritdoc - */ - abstract replyData(invoke: protocol.Invoke): void; - /** - * Send an {@link Invoke} message. - * - * Sends an {@link Invoke} message requesting a **distributed process**. The {@link Invoke} message will be sent - * to the most idle {@link DistributedSystem} object, which represents a slave system, and the most idle - * {@link DistributedSystem} object will be returned. - * - * When the **distributed process** has completed, then the {@link DistributedSystemArray} object will revaluate - * {@link getResource resource index} and {@link DistributedSystem.getPerformance performance index} of this - * {@link DistributedSystem} and the most idle {@link DistributedSystem} objects basis on the execution time. - * - * @param invoke An {@link Invoke} message requesting distributed process. - * @return The most idle {@link DistributedSystem} object who may send the {@link Invoke} message. - */ - sendData(invoke: protocol.Invoke): DistributedSystem; - /** - * Send an {@link Invoke} message. - * - * Sends an {@link Invoke} message requesting a **distributed process**. The {@link Invoke} message will be sent - * to the most idle {@link DistributedSystem} object, which represents a slave system, and the most idle - * {@link DistributedSystem} object will be returned. - * - * When the **distributed process** has completed, then the {@link DistributedSystemArray} object will revaluate - * {@link getResource resource index} and {@link DistributedSystem.getPerformance performance index} of this - * {@link DistributedSystem} and the most idle {@link DistributedSystem} objects basis on the execution time. - * - * @param invoke An {@link Invoke} message requesting distributed process. - * @param weight Weight of resource which indicates how heavy this {@link Invoke} message is. Default is 1. - * - * @return The most idle {@link DistributedSystem} object who may send the {@link Invoke} message. - */ - sendData(invoke: protocol.Invoke, weight: number): DistributedSystem; - /** - * @hidden - */ - private complete_history(history); - /** - * @inheritdoc - */ - TAG(): string; - } -} -declare namespace samchon.templates.external { - /** - * An external system driver. - * - * The {@link ExternalSystem} class represents an external system, connected and interact with this system. - * {@link ExternalSystem} takes full charge of network communication with the remote, external system have connected. - * Replied {@link Invoke} messages from the external system is shifted to and processed in, children elements of this - * class, {@link ExternalSystemRole} objects. - * - * - * - * - * - * #### Bridge & Proxy Pattern - * The {@link ExternalSystem} class can be a *bridge* for *logical proxy*. In framework within user, - * which {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
    - *
  • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
  • - *
  • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
  • - *
  • Those strategy is called *Bridge Pattern* and *Proxy Pattern*.
  • - *
- * - * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) - * @author Jeongho Nam - */ - abstract class ExternalSystem extends protocol.EntityDequeCollection implements protocol.IProtocol { - /** - * The name represents external system have connected. - */ - protected name: string; - /** - * @hidden - */ - private system_array_; - /** - * @hidden - */ - private communicator_; - /** - * Construct from parent {@link ExternalSystemArray}. - * - * @param systemArray The parent {@link ExternalSystemArray} object. - */ - constructor(systemArray: ExternalSystemArray); - /** - * Constrct from parent {@link ExternalSystemArray} and communicator. - * - * @param systemArray The parent {@link ExternalSystemArray} object. - * @param communicator Communicator with the remote, external system. - */ - constructor(systemArray: ExternalSystemArray, communicator: protocol.IClientDriver); - /** - * Default Destructor. - * - * This {@link destructor destructor()} method is called when the {@link ExternalSystem} object is destructed and - * the {@link ExternalSystem} object is destructed when connection with the remote system is closed or this - * {@link ExternalSystem} object is {@link ExternalSystemArray.erase erased} from its parent - * {@link ExternalSystemArray} object. - * - * Note that, don't call this {@link destructor destructor()} method by yourself. It must be called automatically - * by those *destruction* cases. Also, if your derived {@link ExternalSystem} class has something to do on the - * *destruction*, then overrides this {@link destructor destructor()} method and defines the something to do. - * Overriding this {@link destructor destructor()}, don't forget to calling ```super.destructor();``` on tail. - * - * ```typescript - * class SomeSystem extends templates.external.ExternalSystem - * { - * protected destructor(): void - * { - * // DO SOMETHING - * this.do_something(); - * - * // CALL SUPER.DESTRUCTOR() ON TAIL. DON'T FORGET THIS - * super.destructor(); - * } - * } - * ``` - */ - protected destructor(): void; - /** - * @hidden - */ - private handle_close(); - /** - * Get parent {@link ExternalSystemArray} object. - */ - getSystemArray(): ExternalSystemArray; - /** - * Get parent {@link ExternalSystemArray} object. - */ - getSystemArray>(): SystemArray; - /** - * Identifier of {@link ExternalSystem} is its {@link name}. - * - * @return name. - */ - key(): string; - /** - * Get {@link name}. - */ - getName(): string; - /** - * @hidden - */ - /** - * @hidden - */ - protected communicator: protocol.ICommunicator; - /** - * Close connection. - */ - close(): void; - /** - * Send {@link Invoke} message to external system. - * - * @param invoke An {@link Invoke} message to send. - */ - sendData(invoke: protocol.Invoke): void; - /** - * Handle an {@Invoke} message has received. - * - * @param invoke An {@link Invoke} message have received. - */ - replyData(invoke: protocol.Invoke): void; - /** - * Tag name of the {@link ExternalSystem} in {@link XML}. - * - * @return *system*. - */ - TAG(): string; - /** - * Tag name of {@link ExternalSystemRole children elements} belonged to the {@link ExternalSystem} in {@link XML}. - * - * @return *role*. - */ - CHILD_TAG(): string; - } -} -declare namespace samchon.templates.parallel { - /** - * A driver for a parallel slave system. - * - * The {@link ParallelSystem} is an abstract class represents a **slave** system in *Parallel Processing System*, - * connected with this **master** system. This {@link ParallelSystem} takes full charge of network communication with - * the remote, parallel **slave** system has connected. - * - * When a *parallel process* is requested (by {@link ParallelSystemArray.sendSegmentData} or - * {@link ParallelSystemArray.sendPieceData}), the number of pieces to be allocated to a {@link ParallelSystem} is - * turn on its {@link getPerformance performance index}. Higher {@link getPerformance performance index}, then - * more pieces are requested. The {@link getPerformance performance index} is revaluated whenever a *parallel process* - * has completed, basic on the execution time and number of pieces. You can sugguest or enforce the - * {@link getPerformance performance index} with {@link setPerformance} or {@link enforcePerformance}. - * - * - * - * - * - * #### Bridge & Proxy Pattern - * This class {@link ParallelSystem} is derived from the {@link ExternalSystem} class. Thus, you can take advantage - * of the *Bridge & Proxy Pattern* in this {@link ParallelSystem} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *Bridge & Proxy Pattern*: - * - * The {@link ExternalSystem} class can be a *bridge* for *logical proxy*. In framework within user, - * which {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
    - *
  • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
  • - *
  • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
  • - *
  • Those strategy is called *Bridge Pattern* and *Proxy Pattern*.
  • - *
- * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ - abstract class ParallelSystem extends external.ExternalSystem { - /** - * @hidden - */ - private progress_list_; - /** - * @hidden - */ - private history_list_; - /** - * @hidden - */ - private exclude_; - /** - * @hidden - */ - private performance; - /** - * @hidden - */ - private enforced_; - /** - * Construct from parent {@link ParallelSystemArray}. - * - * @param systemArray The parent {@link ParallelSystemArray} object. - */ - constructor(systemArray: ParallelSystemArray); - /** - * Construct from parent {@link ParallelSystemArray} and communicator. - * - * @param systemArray The parent {@link ParallelSystemArray} object. - * @param communicator A communicator communicates with remote, the external system. - */ - constructor(systemArray: ParallelSystemArray, communicator: protocol.IClientDriver); - /** - * Default Destructor. - * - * This {@link destructor destructor()} method is called when the {@link ParallelSystem} object is destructed and - * the {@link ParallelSystem} object is destructed when connection with the remote system is closed or this - * {@link ParallelSystem} object is {@link ParallelSystemArray.erase erased} from its parent - * {@link ParallelSystemArray} object. - * - * You may think if there're some *parallel processes* have requested but not completed yet, then it would be a - * critical problem because the *parallel processes* will not complete forever. Do not worry. The critical problem - * does not happen. After the destruction, the remained *parallel processes* will be shifted to and proceeded in - * other {@link ParallelSystem} objects. - * - * Note that, don't call this {@link destructor destructor()} method by yourself. It must be called automatically - * by those *destruction* cases. Also, if your derived {@link ParallelSystem} class has something to do on the - * *destruction*, then overrides this {@link destructor destructor()} method and defines the something to do. - * Overriding this {@link destructor destructor()}, don't forget to calling ```super.destructor();``` on tail. - * - * ```typescript - * class SomeSystem extends protocol.external.ExternalSystem - * { - * protected destructor(): void - * { - * // DO SOMETHING - * this.do_something(); - * - * // CALL SUPER.DESTRUCTOR() ON TAIL. DON'T FORGET THIS - * super.destructor(); - * } - * } - * ``` - */ - protected destructor(): void; - /** - * Get manager of this object. - * - * @return The parent {@link ParallelSystemArray} object. - */ - getSystemArray(): ParallelSystemArray; - /** - * Get manager of this object. - * - * @return The parent {@link ParallelSystemArray} object. - */ - getSystemArray>(): SystemArray; - /** - * Get performance index. - * - * Get *performance index* that indicates how much fast the remote system is. - * - * If this {@link ParallelSystem parallel system} does not have any {@link Invoke} message had handled, then the - * *performance index* will be ```1.0```, which means default and average value between all {@link ParallelSystem} - * instances (that are belonged to a same {@link ParallelSystemArray} object). - * - * You can specify this *performance index* by yourself but notice that, if the *performance index* is higher - * than other {@link ParallelSystem} objects, then this {@link ParallelSystem parallel system} will be ordered to - * handle more processes than other {@link ParallelSystem} objects. Otherwise, the *performance index* is lower - * than others, of course, less processes will be delivered. - * - * - {@link setPerformance setPerformance()} - * - {@link enforcePerformance enforcePerformance()} - * - * Unless {@link enforcePerformance enforcePerformance()} is called, This *performance index* is **revaluated** - * whenever user calls one of them below. - * - * - {@link ParallelSystemArray.sendSegmentData ParallelSystemArray.sendSegmentData()} - * - {@link ParallelSystemArray.sendPieceData ParallelSystemArray.sendPieceData()} - * - {@link DistributedProcess.sendData DistributedProcess.sendData()}. - * - * @return Performance index. - */ - getPerformance(): number; - /** - * Set performance index. - * - * Set *performance index* that indicates how much fast the remote system is. This *performance index* can be - * **revaulated**. - * - * Note that, initial and average *performance index* of {@link ParallelSystem} objects are ```1.0```. If the - * *performance index* is higher than other {@link ParallelSystem} objects, then this {@link ParallelSystem} will - * be ordered to handle more processes than other {@link ParallelSystem} objects. Otherwise, the - * *performance index* is lower than others, of course, less processes will be delivered. - * - * Unlike {@link enforcePerformance}, configuring *performance index* by this {@link setPerformance} allows - * **revaluation**. This **revaluation** prevents wrong valuation from user. For example, you *mis-valuated* the - * *performance index*. The remote system is much faster than any other, but you estimated it to the slowest one. - * It looks like a terrible case that causes {@link ParallelSystemArray entire parallel systems} to be slower, - * however, don't mind. The system will direct to the *propriate performance index* eventually with the - * **revaluation** by following methods. - * - * - {@link ParallelSystemArray.sendSegmentData ParallelSystemArray.sendSegmentData()} - * - {@link ParallelSystemArray.sendPieceData ParallelSystemArray.sendPieceData()} - * - {@link DistributedProcess.sendData DistributedProcess.sendData()}. - * - * @param val New performance index, but can be revaluated. - */ - setPerformance(val: number): void; - /** - * Enforce performance index. - * - * Enforce *performance index* that indicates how much fast the remote system is. The *performance index* will be - * fixed, never be **revaluated**. - * - * Note that, initial and average *performance index* of {@link ParallelSystem} objects are ```1.0```. If the - * *performance index* is higher than other {@link ParallelSystem} objects, then this {@link ParallelSystem} will - * be ordered to handle more processes than other {@link ParallelSystem} objects. Otherwise, the - * *performance index* is lower than others, of course, less processes will be delivered. - * - * The difference between {@link setPerformance} and this {@link enforcePerformance} is allowing **revaluation** - * or not. This {@link enforcePerformance} does not allow the **revaluation**. The *performance index* is clearly - * fixed and never be changed by the **revaluation**. But you've to keep in mind that, you can't avoid the - * **mis-valuation** with this {@link enforcePerformance}. - * - * For example, there's a remote system much faster than any other, but you **mis-estimated** it to the slowest. - * In that case, there's no way. The {@link ParallelSystemArray entire parallel systems} will be slower by the - * **mis-valuation**. By the reason, using {@link enforcePerformance}, it's recommended only when you can clearly - * certain the *performance index*. If you can't certain the *performance index* but want to recommend, then use - * {@link setPerformance} instead. - * - * @param val New performance index to be fixed. - */ - enforcePerformance(val: number): void; - /** - * @hidden - */ - private send_piece_data(invoke, first, last); - /** - * @hidden - */ - private _replyData(invoke); - /** - * @hidden - */ - protected _Report_history(xml: library.XML): void; - /** - * @hidden - */ - protected _Send_back_history(invoke: protocol.Invoke, history: protocol.InvokeHistory): void; - } -} -declare namespace samchon.templates.distributed { - /** - * A driver for a distributed slave system. - * - * The {@link DistributedSystem} is an abstract class represents a **slave** system in *Distributed Processing System*, - * connected with this **master** system. This {@link DistributedSystem} takes full charge of network communication - * with the remote, distributed **slave** system has connected. - * - * This {@link DistributedSystem} has a {@link getPerformance performance index} that indicates how much the **slave** - * system is fast. The {@link getPerformance performance index} is referenced and revaluated whenever those methods - * are called: - * - * - Requesting a *parallel process* - * - {@link DistributedSystemArray.sendSegmentData} - * - {@link DistributedSystemArray.sendPieceData} - * - Requesting a *distributed process*: {@link DistributedProcess.sendData} - * - * Note that, this {@link DistributedSystem} class derived from the {@link ExternalSystem} class. Thus, this - * {@link DistributedSystem} can also have children {@link ExternalSystemRole} objects exclusively. However, the - * children {@link ExternalSystemRole roles} objects are different with the {@link DistributedProcess}. The - * domestic {@link ExternalSystemRole roles} are belonged to only a specific {@link DistributedSystem} object. - * Otherwise, the {@link DistributedProcess} objects are belonged to a {@link DistributedSystemArray} object. - * Furthermore, the relationship between this {@link DistributedSystem} and {@link DistributedProcess} classes are - * **M: N Associative**. - * - * Articles | {@link DistributedProcess} | {@link ExternalSystemRole} - * -------------|--------------------------------|---------------------------- - * Belonged to | {@link DistributedSystemArray} | {@link DistributedSystem} - * Relationship | M: N Associative | 1: N Composite - * Ownership | References | Exclusive possession - * - * - * - * - * - * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - abstract class DistributedSystem extends parallel.ParallelSystem { - /** - * Construct from parent {@link DistributedSystemArray}. - * - * @param systemArray The parent {@link DistributedSystemArray} object. - */ - constructor(systemArray: DistributedSystemArray); - /** - * Constrct from parent {@link DistributedSystemArray} and communicator. - * - * @param systemArray The parent {@link DistributedSystemArray} object. - * @param communicator A communicator communicates with remote, the external system. - */ - constructor(systemArray: DistributedSystemArray, communicator: protocol.IClientDriver); - /** - * Factory method creating a {@link ExternalSystemRole child} object. - * - * In {@link distributed} module, the process class {@link DistributedProcess} is not belonged to a specific - * {@link DistributedSystem} object. It only belongs to a {@link DistributedSystemArray} object and has a - * **M: N Associative Relationship** between this {@link DistributedSystem} class. - * - * By that reason, it's the normal case that the {@link DistributedSystem} object does not have any children - * {@link ExternalSystemRole} object. Thus, default {@link createChild} returns ```null```. - * - * However, if you want a {@link DistributedSystem} to have its own domestic {@link ExternalSystemRole} objects - * without reference to the {@link DistributedProcess} objects, it is possible. Creates and returns the - * domestic {@link ExternalSystemRole} object. - * - * @param xml {@link XML} represents the {@link ExternalSystemRole child} object. - * @return A newly created {@link ExternalSystemRole} object or ```null```. - */ - createChild(xml: library.XML): external.ExternalSystemRole; - /** - * Get manager of this object. - * - * @return The parent {@link DistributedSystemArray} object. - */ - getSystemArray(): DistributedSystemArray; - /** - * Get manager of this object. - * - * @return The parent {@link DistributedSystemArray} object. - */ - getSystemArray>(): SystemArray; - /** - * @hidden - */ - private compute_average_elapsed_time(); - /** - * @inheritdoc - */ - replyData(invoke: protocol.Invoke): void; - /** - * @hidden - */ - protected _Report_history(xml: library.XML): void; - /** - * @hidden - */ - protected _Send_back_history(invoke: protocol.Invoke, history: protocol.InvokeHistory): void; - } -} -declare namespace samchon.templates.distributed { - /** - * An interface for a distributed slave server driver. - * - * The easiest way to defining a driver for distributed **slave** server is extending {@link DistributedServer} class. - * However, if you've to interact with a prallel **slave** system who can be both server and client, them make a class - * (let's name it **BaseSystem**) extending the {@link DistributedServer} class. At next, make a new class (now, I name - * it **BaseServer**) extending the **BaseSystem** and implements this interface {@link IParallelServer}. Define the - * **BaseServer** following those codes on below: - * - * - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ - interface IDistributedServer extends DistributedSystem { - /** - * Connect to external server. - */ - connect(): void; - } - /** - * A driver for distributed slave server. - * - * The {@link DistributedServer} is an abstract class, derived from the {@link DistributedSystem} class, connecting to - * remote, distributed **slave** server. Extends this {@link DistributedServer} class and overrides the - * {@link createServerConnector createServerConnector()} method following which protocol the **slave** server uses. - * - * #### [Inheritdoc] {@link DistributedSystem} - * The {@link DistributedSystem} is an abstract class represents a **slave** system in *Distributed Processing System*, - * connected with this **master** system. This {@link DistributedSystem} takes full charge of network communication - * with the remote, distributed **slave** system has connected. - * - * This {@link DistributedSystem} has a {@link getPerformance performance index} that indicates how much the **slave** - * system is fast. The {@link getPerformance performance index} is referenced and revaluated whenever those methods - * are called: - * - * - Requesting a *parallel process* - * - {@link DistributedSystemArray.sendSegmentData} - * - {@link DistributedSystemArray.sendPieceData} - * - Requesting a *distributed process*: {@link DistributedProcess.sendData} - * - * Note that, this {@link DistributedSystem} class derived from the {@link ExternalSystem} class. Thus, this - * {@link DistributedSystem} can also have children {@link ExternalSystemRole} objects exclusively. However, the - * children {@link ExternalSystemRole roles} objects are different with the {@link DistributedProcess}. The - * domestic {@link ExternalSystemRole roles} are belonged to only a specific {@link DistributedSystem} object. - * Otherwise, the {@link DistributedProcess} objects are belonged to a {@link DistributedSystemArray} object. - * Furthermore, the relationship between this {@link DistributedSystem} and {@link DistributedProcess} classes are - * **M: N Associative**. - * - * Articles | {@link DistributedProcess} | {@link ExternalSystemRole} - * -------------|--------------------------------|---------------------------- - * Belonged to | {@link DistributedSystemArray} | {@link DistributedSystem} - * Relationship | M: N Associative | 1: N Composite - * Ownership | References | Exclusive possession - * - * - * - * - * - * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - abstract class DistributedServer extends DistributedSystem implements external.IExternalServer { - /** - * IP address of target external system to connect. - */ - protected ip: string; - /** - * Port number of target external system to connect. - */ - protected port: number; - /** - * Construct from parent {@link DistributedSystemArray}. - * - * @param systemArray The parent {@link DistributedSystemArray} object. - */ - constructor(systemArray: DistributedSystemArray); - /** - * Factory method creating {@link IServerConnector} object. - * - * The {@link createServerConnector createServerConnector()} is an abstract method creating - * {@link IServerConnector} object. Overrides and returns one of them, considering which protocol the slave server - * follows: - * - * - {@link ServerConnector} - * - {@link WebServerConnector} - * - {@link DedicatedWorkerServerConnector} - * - {@link SharedWorkerServerConnector} - * - * @return A newly created {@link IServerConnector} object. - */ - protected abstract createServerConnector(): protocol.IServerConnector; - /** - * @inheritdoc - */ - connect(): void; - } -} -declare namespace samchon.templates.distributed { - /** - * Master of Distributed Processing System, a client connecting to slave servers. - * - * The {@link DistributedServerArray} is an abstract class, derived from the {@link DistributedSystemArray} class, - * connecting to {@link IDistributedServer distributed servers}. - * - * Extends this {@link DistributedServerArray} and overrides {@link createChild createChild()} method creating child - * {@link IDistributedServer} object. After the extending and overriding, construct children {@link IDistributedServer} - * objects and call the {@link connect connect()} method. - * - * #### [Inherited] {@link DistributedSystemArray} - * The {@link DistributedSystemArray} is an abstract class containing and managing remote distributed **slave** system - * drivers, {@link DistributedSystem} objects. Within framework of network, {@link DistributedSystemArray} represents - * your system, a **Master** of *Distributed Processing System* that requesting *distributed process* to **slave** - * systems and the children {@link DistributedSystem} objects represent the remote **slave** systems, who is being - * requested the *distributed processes*. - * - * The {@link DistributedSystemArray} contains {@link DistributedProcess} objects directly. You can request a - * **distributed process** through the {@link DistributedProcess} object. You can access the - * {@link DistributedProcess} object(s) with those methods: - * - * - {@link hasProcess} - * - {@link getProcess} - * - {@link insertProcess} - * - {@link eraseProcess} - * - {@link getProcessMap} - * - * When you need the **distributed process**, call the {@link DistributedProcess.sendData} method. Then the - * {@link DistributedProcess} will find the most idle {@link DistributedSystem} object who represents a distributed - * **slave **system. The {@link Invoke} message will be sent to the most idle {@link DistributedSystem} object. When - * the **distributed process** has completed, then {@link DistributedSystem.getPerformance performance index} and - * {@link DistributedProcess.getResource resource index} of related objects will be revaluated. - * - * - * - * - * - * #### Parallel Process - * This {@link DistributedSystemArray} class is derived from the {@link ParallelSystemArray} class, so you can request - * a **parallel process**, too. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices will - * be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * #### Proxy Pattern - * This class {@link DistributedSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link DistributedSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *Proxy Pattern*: - * - * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
    - *
  • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
  • - *
  • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
  • - *
  • Those strategy is called *Proxy Pattern*.
  • - *
- * - * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - abstract class DistributedServerArray extends DistributedSystemArray implements external.IExternalServerArray { - /** - * Default Constructor. - */ - constructor(); - /** - * @inheritdoc - */ - connect(): void; - } -} -declare namespace samchon.templates.distributed { - /** - * Mediator of Distributed Processing System, a client connecting to slave servers. - * - * The {@link DistributedServerArrayMediator} is an abstract class, derived from {@link DistributedSystemArrayMediator} - * class, connecting to {@link IDistributedServer distributed servers}. - * - * Extends this {@link DistributedServerArrayMediator} and overrides {@link createChild createChild()} method creating - * child {@link IDistributedServer} object. After the extending and overriding, construct children - * {@link IDistributedServer} objects and call the {@link connect connect()} method. - * - * #### [Inherited] {@link DistributedSystemArrayMediator} - * The {@link DistributedSystemArrayMediator} class be a master for its slave systems, and be a slave to its master - * system at the same time. This {@link DistributedSystemArrayMediator} be a master system, containing and managing - * {@link DistributedSystem} objects, which represent distributed slave systems, by extending - * {@link DistributedSystemArray} class. Also, be a slave system through {@link getMediator mediator} object, which is - * derived from the {@link SlaveSystem} class. - * - * As a slave, you can specify this {@link DistributedSystemArrayMediator} to be a client slave connecting to master - * server or a server slave accepting master client by overriding the {@link createMediator} method. - * Overrides the {@link createMediator createMediator()} method and return one of them: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * #### [Inherited] {@link DistributedSystemArray} - * The {@link DistributedSystemArray} is an abstract class containing and managing remote distributed **slave** system - * drivers, {@link DistributedSystem} objects. Within framework of network, {@link DistributedSystemArray} represents - * your system, a **Master** of *Distributed Processing System* that requesting *distributed process* to **slave** - * systems and the children {@link DistributedSystem} objects represent the remote **slave** systems, who is being - * requested the *distributed processes*. - * - * The {@link DistributedSystemArray} contains {@link DistributedProcess} objects directly. You can request a - * **distributed process** through the {@link DistributedProcess} object. You can access the - * {@link DistributedProcess} object(s) with those methods: - * - * - {@link hasProcess} - * - {@link getProcess} - * - {@link insertProcess} - * - {@link eraseProcess} - * - {@link getProcessMap} - * - * When you need the **distributed process**, call the {@link DistributedProcess.sendData} method. Then the - * {@link DistributedProcess} will find the most idle {@link DistributedSystem} object who represents a distributed - * **slave **system. The {@link Invoke} message will be sent to the most idle {@link DistributedSystem} object. When - * the **distributed process** has completed, then {@link DistributedSystem.getPerformance performance index} and - * {@link DistributedProcess.getResource resource index} of related objects will be revaluated. - * - * - * - * - * - * #### Parallel Process - * This {@link DistributedSystemArray} class is derived from the {@link ParallelSystemArray} class, so you can request - * a **parallel process**, too. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices will - * be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * #### Proxy Pattern - * This class {@link DistributedSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link DistributedSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *Proxy Pattern*: - * - * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
    - *
  • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
  • - *
  • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
  • - *
  • Those strategy is called *Proxy Pattern*.
  • - *
- * - * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - abstract class DistributedServerArrayMediator extends DistributedSystemArrayMediator implements external.IExternalServerArray { - /** - * Default Constructor. - */ - constructor(); - /** - * @inheritdoc - */ - connect(): void; - } -} -declare namespace samchon.templates.distributed { - /** - * Master of Distributed Processing System, be a server and client at the same time. - * - * The {@link DistributedServerClientArray} is an abstract class, derived from the {@link DistributedSystemArray} - * class, opening a server accepting {@link Distributed distributed clients} and being a client connecting to - * {@link IDistributedServer distributed servers} at the same time. - * - * Extends this {@link DistributedServerClientArray} and overrides below methods. After the overridings, open server - * with {@link open open()} method and connect to {@link IDistributedServer distributed servers} through the - * {@link connect connect()} method. - * - * - {@link createServerBase createServerBase()} - * - {@link createExternalClient createExternalClient()} - * - {@link createExternalServer createExternalServer()} - * - * #### [Inherited] {@link DistributedSystemArray} - * The {@link DistributedSystemArray} is an abstract class containing and managing remote distributed **slave** system - * drivers, {@link DistributedSystem} objects. Within framework of network, {@link DistributedSystemArray} represents - * your system, a **Master** of *Distributed Processing System* that requesting *distributed process* to **slave** - * systems and the children {@link DistributedSystem} objects represent the remote **slave** systems, who is being - * requested the *distributed processes*. - * - * The {@link DistributedSystemArray} contains {@link DistributedProcess} objects directly. You can request a - * **distributed process** through the {@link DistributedProcess} object. You can access the - * {@link DistributedProcess} object(s) with those methods: - * - * - {@link hasProcess} - * - {@link getProcess} - * - {@link insertProcess} - * - {@link eraseProcess} - * - {@link getProcessMap} - * - * When you need the **distributed process**, call the {@link DistributedProcess.sendData} method. Then the - * {@link DistributedProcess} will find the most idle {@link DistributedSystem} object who represents a distributed - * **slave **system. The {@link Invoke} message will be sent to the most idle {@link DistributedSystem} object. When - * the **distributed process** has completed, then {@link DistributedSystem.getPerformance performance index} and - * {@link DistributedProcess.getResource resource index} of related objects will be revaluated. - * - * - * - * - * - * #### Parallel Process - * This {@link DistributedSystemArray} class is derived from the {@link ParallelSystemArray} class, so you can request - * a **parallel process**, too. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices will - * be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * #### Proxy Pattern - * This class {@link DistributedSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link DistributedSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *Proxy Pattern*: - * - * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
    - *
  • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
  • - *
  • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
  • - *
  • Those strategy is called *Proxy Pattern*.
  • - *
- * - * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - abstract class DistributedServerClientArray extends DistributedClientArray implements external.IExternalServerClientArray { - /** - * Default Constructor. - */ - constructor(); - /** - * Factory method of a child Entity. - * - * This method is migrated to {@link createExternalServer}. Override the {@link createExternalServer} method. - * - * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. - * @return A new child Entity via {@link createExternalServer createExternalServer()}. - */ - createChild(xml: library.XML): System; - /** - * Factory method creating an {@link IDistributedServer} object. - * - * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. - * @return A newly created {@link IDistributedServer} object. - */ - protected abstract createExternalServer(xml: library.XML): System; - /** - * @inheritdoc - */ - connect(): void; - } -} -declare namespace samchon.templates.distributed { - /** - * Mediator of Distributed Processing System, be a server and client at the same time as a **master**. - * - * The {@link DistributedServerClientArrayMediator} is an abstract class, derived from the - * {@link DistributedSystemArrayMediator} class, opening a server accepting {@link DistributedSystem distributed - * clients} and being a client connecting to {@link IDistributedServer distributed servers} at the same time. - * - * Extends this {@link DistributedServerClientArrayMediator} and overrides below methods. After the overridings, open - * server with {@link open open()} method and connect to {@link IDistributedServer distributed servers} through the - * {@link connect connect()} method. - * - * - {@link createServerBase createServerBase()} - * - {@link createExternalClient createExternalClient()} - * - {@link createExternalServer createExternalServer()} - * - * #### [Inherited] {@link DistributedSystemArrayMediator} - * The {@link DistributedSystemArrayMediator} class be a master for its slave systems, and be a slave to its master - * system at the same time. This {@link DistributedSystemArrayMediator} be a master system, containing and managing - * {@link DistributedSystem} objects, which represent distributed slave systems, by extending - * {@link DistributedSystemArray} class. Also, be a slave system through {@link getMediator mediator} object, which is - * derived from the {@link SlaveSystem} class. - * - * As a slave, you can specify this {@link DistributedSystemArrayMediator} to be a client slave connecting to master - * server or a server slave accepting master client by overriding the {@link createMediator} method. - * Overrides the {@link createMediator createMediator()} method and return one of them: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * #### [Inherited] {@link DistributedSystemArray} - * The {@link DistributedSystemArray} is an abstract class containing and managing remote distributed **slave** system - * drivers, {@link DistributedSystem} objects. Within framework of network, {@link DistributedSystemArray} represents - * your system, a **Master** of *Distributed Processing System* that requesting *distributed process* to **slave** - * systems and the children {@link DistributedSystem} objects represent the remote **slave** systems, who is being - * requested the *distributed processes*. - * - * The {@link DistributedSystemArray} contains {@link DistributedProcess} objects directly. You can request a - * **distributed process** through the {@link DistributedProcess} object. You can access the - * {@link DistributedProcess} object(s) with those methods: - * - * - {@link hasProcess} - * - {@link getProcess} - * - {@link insertProcess} - * - {@link eraseProcess} - * - {@link getProcessMap} - * - * When you need the **distributed process**, call the {@link DistributedProcess.sendData} method. Then the - * {@link DistributedProcess} will find the most idle {@link DistributedSystem} object who represents a distributed - * **slave **system. The {@link Invoke} message will be sent to the most idle {@link DistributedSystem} object. When - * the **distributed process** has completed, then {@link DistributedSystem.getPerformance performance index} and - * {@link DistributedProcess.getResource resource index} of related objects will be revaluated. - * - * - * - * - * - * #### Parallel Process - * This {@link DistributedSystemArray} class is derived from the {@link ParallelSystemArray} class, so you can request - * a **parallel process**, too. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices will - * be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * #### Proxy Pattern - * This class {@link DistributedSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link DistributedSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *Proxy Pattern*: - * - * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
    - *
  • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
  • - *
  • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
  • - *
  • Those strategy is called *Proxy Pattern*.
  • - *
- * - * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - abstract class DistributedServerClientArrayMediator extends DistributedClientArrayMediator implements external.IExternalServerClientArray { - /** - * Default Constructor. - */ - constructor(); - /** - * Factory method of a child Entity. - * - * This method is migrated to {@link createExternalServer}. Override the {@link createExternalServer} method. - * - * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. - * @return A new child Entity via {@link createExternalServer createExternalServer()}. - */ - createChild(xml: library.XML): System; - /** - * Factory method creating an {@link IDistributedServer} object. - * - * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. - * @return A newly created {@link IDistributedServer} object. - */ - protected abstract createExternalServer(xml: library.XML): System; - /** - * @inheritdoc - */ - connect(): void; - } -} -declare namespace samchon.templates.distributed { - /** - * History of an {@link Invoke} message. - * - * The {@link PRInvokeHistory} is a class archiving history log of an {@link Invoke} message which requests the - * *distributed process*, created whenever {@link DistributedProcess.sendData} is called. - * - * When the *distributed process* has completed, then {@link complete complete()} is called and the *elapsed time* is - * determined. The elapsed time is utilized for computation of {@link DistributedSystem.getPerformance performance index} - * and {@link DistributedProcess.getResource resource index} of related objects. - * - * - * - * - * - * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - class DSInvokeHistory extends protocol.InvokeHistory { - /** - * @hidden - */ - private system_; - /** - * @hidden - */ - private process_; - /** - * @hidden - */ - private weight_; - /** - * Construct from a DistributedSystem. - * - * @param system The {@link DistributedSystem} object who sent the {@link Invoke} message. - */ - constructor(system: DistributedSystem); - /** - * Initilizer Constructor. - * - * @param system The {@link DistributedSystem} object who sent the {@link Invoke} message. - * @param process The {@link DistributedProcess} object who sent the {@link Invoke} message. - * @param invoke An {@link Invoke} message requesting the *distributed process*. - * @param weight Weight of resource which indicates how heavy this {@link Invoke} message is. - */ - constructor(system: DistributedSystem, process: DistributedProcess, invoke: protocol.Invoke, weight: number); - /** - * @inheritdoc - */ - construct(xml: library.XML): void; - /** - * Get the related {@link DistributedSystem} object. - */ - getSystem(): DistributedSystem; - /** - * Get the related {@link DistributedProcess} object. - */ - getProcess(): DistributedProcess; - /** - * Get weight. - * - * Gets weight of resource which indicates how heavy this {@link Invoke} message is. Default is 1. - */ - getWeight(): number; - /** - * @inheritdoc - */ - toXML(): library.XML; - } -} -declare namespace samchon.templates.external { - /** - * An interface for an {@link ExternalSystemArray} accepts {@link ExternalSystem external clients} as a - * {@link IServer server}. - * - * The easiest way to defining an {@link ExternalSystemArray} who opens server and accepts - * {@link ExternalSystem external clients} is to extending one of below, who are derived from this interface - * {@link IExternalClientArray}. However, if you can't specify an {@link ExternalSystemArray} to be whether server or - * client, then make a class (let's name it as **BaseSystemArray**) extending {@link ExternalSystemArray} and make - * a new class (now, I name it **BaseClientArray**) extending **BaseSystemArray** and implementing this - * interface {@link IExternalClientArray}. Define the **BaseClientArray** following those codes on below: - * - * - * - * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) - * @author Jeongho Nam - */ - interface IExternalClientArray extends ExternalSystemArray, protocol.IServer { - } - /** - * An array and manager of {@link ExternalSystem external clients} as a server. - * - * The {@link ExternalClientArray} is an abstract class, derived from the {@link ExternalSystemArray} class, opening - * a server accepting {@link ExternalSystem external clients}. - * - * Extends this {@link ExternalClientArray}, overrides {@link createServerBase createServerBase()} to determine which - * protocol to follow and {@link createExternalClient createExternalClient()} creating child {@link ExternalSystem} - * object. After the extending and overridings, open this server using the {@link open open()} method. - * - * #### [Inherited] {@link ExternalSystemArray} - * The {@link ExternalSystemArray} is an abstract class containing and managing external system drivers, - * {@link ExternalSystem} objects. Within framewokr of network, {@link ExternalSystemArray} represents your system - * and children {@link ExternalSystem} objects represent remote, external systems connected with your system. - * With this {@link ExternalSystemArray}, you can manage multiple external systems as a group. - * - * - * - * - * - * #### Proxy Pattern - * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
    - *
  • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
  • - *
  • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
  • - *
  • Those strategy is called *Proxy Pattern*.
  • - *
- * - * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) - * @author Jeongho Nam - */ - abstract class ExternalClientArray extends ExternalSystemArray implements IExternalClientArray { - /** - * @hidden - */ - private server_base_; - /** - * Default Constructor. - */ - constructor(); - /** - * Factory method creating {@link IServerBase} object. - * - * This method {@link createServerBase createServerBase()} determines which templates is used in this server, - * {@link ExternalClientArray}. If the templates is determined, then {@link ExternalSystem external clients} who - * may connect to {@link ExternalClientArray this server} must follow the specified templates. - * - * Creates and returns one of them: - * - * - {@link ServerBase} - * - {@link WebServerBase} - * - {@link SharedWorkerServerBase} - * - * @return A new {@link IServerBase} object. - */ - protected abstract createServerBase(): protocol.IServerBase; - /** - * Add a newly connected remote client. - * - * When a {@link IClientDriver remote client} connects to this *server* {@link ExternalClientArray} object, - * then this {@link ExternalClientArray} creates a child {@link ExternalSystem external client} object through - * the {@link createExternalClient createExternalClient()} method and {@link insert inserts} it. - * - * @param driver A communicator for external client. - */ - addClient(driver: protocol.IClientDriver): void; - /** - * (Deprecated) Factory method creating child object. - * - * The method {@link createChild createChild()} is deprecated. Don't use and override this. - * - * Note that, the {@link ExternalClientArray} is a server accepting {@link ExternalSystem external clients}. - * There's no way to creating the {@link ExternalSystem external clients} in advance before opening the server. - * - * @param xml An {@link XML} object represents the child {@link ExternalSystem} object. - * @return null - */ - createChild(xml: library.XML): T; - /** - * Factory method creating a child {@link ExternalSystem} object. - * - * @param driver A communicator with connected client. - * @return A newly created {@link ExternalSystem} object. - */ - protected abstract createExternalClient(driver: protocol.IClientDriver): T; - /** - * @inheritdoc - */ - open(port: number): void; - /** - * @inheritdoc - */ - close(): void; - } -} -declare namespace samchon.templates.external { - /** - * An interface for an external server driver. - * - * The easiest way to defining an external server driver is to extending one of below, who are derived from this - * interface {@link IExternalServer}. However, if you've to interact with an external system who can be both server - * and client, then make a class (let's name it as **BaseSystem**) extending {@link ExternalSystem} and make a - * new class (now, I name it **BaseServer**) extending **BaseSystem** and implementing this interface - * {@link IExternalServer}. Define the **BaseServer** following those codes on below: - * - * - * - * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) - * @author Jeongho Nam - */ - interface IExternalServer extends ExternalSystem { - /** - * Connect to external server. - */ - connect(): void; - } - /** - * An external server driver. - * - * The {@link ExternalServer} is an abstract class, derived from the {@link ExternalSystem} class, connecting to - * remote, external server. Extends this {@link ExternalServer} class and overrides the - * {@link createServerConnector createServerConnector()} method following which protocol the external server uses. - * - * #### [Inherited] {@link ExternalSystem} - * The {@link ExternalSystem} class represents an external system, connected and interact with this system. - * {@link ExternalSystem} takes full charge of network communication with the remote, external system have connected. - * Replied {@link Invoke} messages from the external system is shifted to and processed in, children elements of this - * class, {@link ExternalSystemRole} objects. - * - * - * - * - * - * #### Bridge & Proxy Pattern - * The {@link ExternalSystem} class can be a *bridge* for *logical proxy*. In framework within user, - * which {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
    - *
  • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
  • - *
  • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
  • - *
  • Those strategy is called *Bridge Pattern* and *Proxy Pattern*.
  • - *
- * - * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) - * @author Jeongho Nam - */ - abstract class ExternalServer extends ExternalSystem implements IExternalServer { - /** - * IP address of target external system to connect. - */ - protected ip: string; - /** - * Port number of target external system to connect. - */ - protected port: number; - /** - * Construct from parent {@link ExternalSystemArray}. - * - * @param systemArray The parent {@link ExternalSystemArray} object. - */ - constructor(systemArray: ExternalSystemArray); - /** - * Factory method creating {@link IServerConnector} object. - * - * The {@link createServerConnector createServerConnector()} is an abstract method creating - * {@link IServerConnector} object. Overrides and returns one of them, considering which templates the external - * system follows: - * - * - {@link ServerConnector} - * - {@link WebServerConnector} - * - {@link DedicatedWorkerServerConnector} - * - {@link SharedWorkerServerConnector} - * - * @return A newly created {@link IServerConnector} object. - */ - protected abstract createServerConnector(): protocol.IServerConnector; - /** - * @inheritdoc - */ - connect(): void; - } -} -declare namespace samchon.templates.external { - /** - * An interface for an {@link ExternalSystemArray} connects to {@link IExternalServer external servers} as a - * **client**. - * - * The easiest way to defining an {@link ExternalSystemArray} who connects to - * {@link IExternalServer external servers} is to extending one of below, who are derived from this interface - * {@link IExternalServerArray}. However, if you can't specify an {@link ExternalSystemArray} to be whether server or - * client, then make a class (let's name it as **BaseSystemArray**) extending {@link ExternalSystemArray} and make - * a new class (now, I name it **BaseServerArray**) extending **BaseSystemArray** and implementing this - * interface {@link IExternalServerArray}. Define the **BaseServerArray** following those codes on below: - * - * - * - * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) - * @author Jeongho Nam - */ - interface IExternalServerArray extends ExternalSystemArray { - /** - * Connect to {@link IExternalServer external servers}. - * - * This method calls children elements' method {@link IExternalServer.connect} gradually. - */ - connect(): void; - } - /** - * An array and manager of {@link IExternalServer external servers}. - * - * The {@link ExternalServerArray} is an abstract class, derived from the {@link ExternalSystemArray} class, - * connecting to {@link IExternalServer external servers}. - * - * Extends this {@link ExternalServerArray} and overrides {@link createChild createChild()} method creating child - * {@link IExternalServer} object. After the extending and overriding, construct children {@link IExternalServer} - * objects and call the {@link connect connect()} method. - * - * #### [Inherited] {@link ExternalSystemArray} - * The {@link ExternalSystemArray} is an abstract class containing and managing external system drivers, - * {@link ExternalSystem} objects. Within framewokr of network, {@link ExternalSystemArray} represents your system - * and children {@link ExternalSystem} objects represent remote, external systems connected with your system. - * With this {@link ExternalSystemArray}, you can manage multiple external systems as a group. - * - * - * - * - * - * #### Proxy Pattern - * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
    - *
  • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
  • - *
  • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
  • - *
  • Those strategy is called *Proxy Pattern*.
  • - *
- * - * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) - * @author Jeongho Nam - */ - abstract class ExternalServerArray extends ExternalSystemArray implements IExternalServerArray { - /** - * Default Constructor. - */ - constructor(); - /** - * @inheritdoc - */ - connect(): void; - } -} -declare namespace samchon.templates.external { - /** - * An interface for an {@link ExternalSystemArray} accepts {@link ExternalSystem external clients} as a - * {@link IServer server} and connects to {@link IExternalServer} as **client**, at the same time. - * - * The easiest way to defining an {@link IExternalServerClientArray} who opens server, accepts - * {@link ExternalSystem external clients} and connects to {@link IExternalServer external servers} is to extending - * one of below, who are derived from this interface {@link IExternalServerClientArray}. However, if you can't - * specify an {@link ExternalSystemArray} to be whether server or client or even can both them, then make a class - * (let's name it as **BaseSystemArray**) extending {@link ExternalSystemArray} and make a new class (now, I name - * it **BaseServerClientArray**) extending **BaseSystemArray** and implementing this interface - * {@link IExternalServerClientArray}. Define the **BaseServerClientArray** following those codes on below: - * - * - * - * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) - * @author Jeongho Nam - */ - interface IExternalServerClientArray extends IExternalClientArray { - /** - * Connect to {@link IExternalServer external servers}. - * - * This method calls children elements' method {@link IExternalServer.connect} gradually. - */ - connect(): void; - } - /** - * An array and manager of {@link IExternalServer external servers} and {@link ExternalSystem external clients}. - * - * The {@link ExternalServerClientArray} is an abstract class, derived from the {@link ExternalSystemArray} class, - * opening a server accepting {@link ExternalSystem external clients} and being a client connecting to - * {@link IExternalServer external servers} at the same time. - * - * Extends this {@link ExternalServerClientArray} and overrides below methods. After the overridings, open server - * with {@link open open()} method and connect to {@link IExternalServer external servers} through the - * {@link connect connect()} method. - * - * - {@link createServerBase createServerBase()} - * - {@link createExternalClient createExternalClient()} - * - {@link createExternalServer createExternalServer()} - * - * #### [Inherited] {@link ExternalSystemArray} - * The {@link ExternalSystemArray} is an abstract class containing and managing external system drivers, - * {@link ExternalSystem} objects. Within framewokr of network, {@link ExternalSystemArray} represents your system - * and children {@link ExternalSystem} objects represent remote, external systems connected with your system. - * With this {@link ExternalSystemArray}, you can manage multiple external systems as a group. - * - * - * - * - * - * #### Proxy Pattern - * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
    - *
  • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
  • - *
  • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
  • - *
  • Those strategy is called *Proxy Pattern*.
  • - *
- * - * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) - * @author Jeongho Nam - */ - abstract class ExternalServerClientArray extends ExternalClientArray implements IExternalServerClientArray { - /** - * Default Constructor. - */ - constructor(); - /** - * Factory method of a child Entity. - * - * This method is migrated to {@link createExternalServer}. Override the {@link createExternalServer} method. - * - * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. - * @return A new child Entity via {@link createExternalServer createExternalServer()}. - */ - createChild(xml: library.XML): T; - /** - * Factory method creating an {@link IExternalServer} object. - * - * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. - * @return A newly created {@link IExternalServer} object. - */ - protected abstract createExternalServer(xml: library.XML): T; - /** - * @inheritdoc - */ - connect(): void; - } -} -declare namespace samchon.templates.external { - /** - * A role of an external system. - * - * The {@link ExternalSystemRole} class represents a role, *WHAT TO DO*. Extends the {@link ExternalSystemRole} class - * and overrides {@link replyData replyData()} to define the *WHAT TO DO*. And assign this {@link ExternalSystemRole} - * object to related {@link ExternalSystem} object. - * - * - * - * - * - * #### Proxy Pattern - * The {@link ExternalSystemRole} class can be an *logical proxy*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
    - *
  • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem} object, via {@link ExternalSystemArray.getRole ExternalSystemArray.getRole()}. - *
  • - *
  • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
  • - *
  • Those strategy is called *Proxy Pattern*.
  • - *
- * - * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) - * @author Jeongho Nam - */ - abstract class ExternalSystemRole extends protocol.Entity implements protocol.IProtocol { - /** - * @hidden - */ - private system; - /** - * A name, represents and identifies this {@link ExternalSystemRole role}. - * - * This {@link name} is an identifier represents this {@link ExternalSystemRole role}. This {@link name} is - * used in {@link ExternalSystemArray.getRole} and {@link ExternalSystem.get}, as a key elements. Thus, this - * {@link name} should be unique in an {@link ExternalSystemArray}. - */ - protected name: string; - /** - * Constructor from a system. - * - * @param system An external system containing this role. - */ - constructor(system: ExternalSystem); - /** - * Identifier of {@link ExternalSystemRole} is its {@link name}. - */ - key(): string; - /** - * Get grandparent {@link ExternalSystemArray}. - * - * Get the grandparent {@link ExternalSystemArray} object through this parent {@link ExternalSystem}, - * {@link ExternalSystem.getSystemArray ExternalSystem.getSystemArray()}. - * - * @return The grandparent {@link ExternalSystemArray} object. - */ - getSystemArray(): ExternalSystemArray; - /** - * Get parent {@link ExternalSystemRole} object. - */ - getSystem(): ExternalSystem; - /** - * Get name, who represents and identifies this role. - */ - getName(): string; - /** - * Send an {@link Invoke} message. - * - * Sends an {@link Invoke} message to remote system through the parent {@link ExternalSystem} object. - * - * @param invoke An {@link Invoke} message to send to the external system. - */ - sendData(invoke: protocol.Invoke): void; - /** - * Handle replied {@link Invoke} message. - * - * {@link ExternalSystemRole.replyData ExternalSystemRole.replyData()} is an abstract method handling a replied - * {@link Invoke message} gotten from remote system via parent {@link ExternalSystem} object. Overrides this - * method and defines the *WHAT TO DO* with the {@link Invoke message}. - * - * @param invoke An {@link Invoke} message received from the {@link ExternalSystem external system}. - */ - abstract replyData(invoke: protocol.Invoke): void; - /** - * Tag name of the {@link ExternalSytemRole} in {@link XML}. - * - * @return *role*. - */ - TAG(): string; - } -} -declare namespace samchon.templates.slave { - abstract class SlaveSystem implements protocol.IProtocol { - /** - * @hidden - */ - protected communicator_: protocol.ICommunicator; - /** - * Default Constructor. - */ - constructor(); - sendData(invoke: protocol.Invoke): void; - /** - * @hidden - */ - protected _replyData(invoke: protocol.Invoke): void; - replyData(invoke: protocol.Invoke): void; - } -} -declare namespace samchon.templates.parallel { - /** - * A mediator, the master driver. - * - * The {@link MediatorSystem} is an abstract class helping {@link ParallelSystemArrayMediator} can be a **slave** - * system. The {@link MediatorSystem} interacts and communicates with the **master** system as a role of **slave**. - * - * This {@link MediatorSystem} object is created in {@link ParallelSystemArrayMediator.createMediator}. Override the - * method and return one of them, which are derived from this {@link MediatorSystem} class, considering which - * type and protocol the **master** system follows: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * When the **master** orders a *parallel process* to this **slave**, then the {@link MediatorSystem} delivers the - * *parallel process* to its parent {@link ParallelSystemArrayMediator} object. The - * {@link ParallelSystemArrayMediator} object distributes the *parallel process* to its slaves system, - * {@link ParallelSystem} objects. When the *parallel process* has completed, then {@link MediatorSystem} reports the - * result to its **master**. - * - * - * - * - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System), - * [Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - abstract class MediatorSystem extends slave.SlaveSystem { - /** - * @hidden - */ - private system_array_; - /** - * @hidden - */ - private progress_list_; - /** - * Construct from parent {@link ParallelSystemArrayMediator} object. - * - * @param systemArray The parent {@link ParallelSystemArrayMediator} object. - */ - constructor(systemArray: ParallelSystemArrayMediator); - /** - * Construct from parent {@link DistributedSystemArrayMediator} object. - * - * @param systemArray The parent {@link DistributedSystemArrayMediator} object. - */ - constructor(systemArray: distributed.DistributedSystemArrayMediator); - /** - * Start interaction. - * - * The {@link start start()} is an abstract method starting interaction with the **master** system. If the - * **master** is a server, then connects to the **master**. Otherwise, the **master** is client, then this - * {@link MediatorSystem} object wil open a server accepting the **master**. - */ - abstract start(): void; - /** - * Get parent {@link ParallelSystemArrayMediator} or {@link DistributedSystemArrayMediator} object. - */ - getSystemArray(): ParallelSystemArrayMediator | distributed.DistributedSystemArrayMediator; - /** - * Get parent {@link ParallelSystemArrayMediator} object. - */ - getSystemArray>(): SystemArray; - /** - * Get parent {@link DistributedSystemArrayMediator} object. - */ - getSystemArray>(): SystemArray; - /** - * @hidden - */ - private complete_history(uid); - /** - * @hidden - */ - protected _replyData(invoke: protocol.Invoke): void; - /** - * @inheritdoc - */ - replyData(invoke: protocol.Invoke): void; - } -} -declare namespace samchon.templates.parallel { - /** - * A mediator server, driver for the master client. - * - * The {@link MediatorServer} is a class opening a server accepting the **master** client, following the protocol of - * Samchon Framework's own. - * - * #### [Inherited] {@link MediatorSystem} - * The {@link MediatorSystem} is an abstract class helping {@link ParallelSystemArrayMediator} can be a **slave** - * system. The {@link MediatorSystem} interacts and communicates with the **master** system as a role of **slave**. - * - * This {@link MediatorSystem} object is created in {@link ParallelSystemArrayMediator.createMediator}. Override the - * method and return one of them, which are derived from this {@link MediatorSystem} class, considering which - * type and protocol the **master** system follows: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * When the **master** orders a *parallel process* to this **slave**, then the {@link MediatorSystem} delivers the - * *parallel process* to its parent {@link ParallelSystemArrayMediator} object. The - * {@link ParallelSystemArrayMediator} object distributes the *parallel process* to its slaves system, - * {@link ParallelSystem} objects. When the *parallel process* has completed, then {@link MediatorSystem} reports the - * result to its **master**. - * - * - * - * - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System), - * [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - class MediatorServer extends MediatorSystem implements slave.ISlaveServer { - /** - * @hidden - */ - private server_base_; - /** - * @hidden - */ - private port; - /** - * Initializer Constructor. - * - * @param systemArray The parent {@link ParallelSystemArrayMediator} object. - * @param port Port number of server to open. - */ - constructor(systemArray: ParallelSystemArrayMediator, port: number); - /** - * Initializer Constructor. - * - * @param systemArray The parent {@link DistributedSystemArrayMediator} object. - * @param port Port number of server to open. - */ - constructor(systemArray: distributed.DistributedSystemArrayMediator, port: number); - /** - * Factory method creating {@link IServerBase} object. - * - * This method {@link createServerBase createServerBase()} determines which protocol is used in this server, - * {@link MediatorServer}. Note that, **slave** (this {@link MediatorServer} object) must follow the **master**'s - * protocol. - * - * Overrides and return one of them considering the which protocol to follow: - * - * - {@link ServerBase} - * - {@link WebServerBase} - * - {@link SharedWorkerServerBase} - */ - protected createServerBase(): protocol.IServerBase; - /** - * Add a newly connected remote client. - * - * {@link MediatorServer} represents a **slave** dedicating to its **master**. In that reason, the - * {@link MediatorServer} does not accept multiple **master** clients. It accepts only one. Thus, *listener* of - * the *communicator* is {@link MediatorSystem} object, itself. - * - * @param driver A communicator with remote client. - */ - addClient(driver: protocol.IClientDriver): void; - /** - * @inheritdoc - */ - start(): void; - /** - * @inheritdoc - */ - open(port: number): void; - /** - * @inheritdoc - */ - close(): void; - } - /** - * A mediator server, driver for the master client. - * - * The {@link MediatorWebServer} is a class opening a server accepting the **master** client, following the - * web-socket protocol. - * - * #### [Inherited] {@link MediatorSystem} - * The {@link MediatorSystem} is an abstract class helping {@link ParallelSystemArrayMediator} can be a **slave** - * system. The {@link MediatorSystem} interacts and communicates with the **master** system as a role of **slave**. - * - * This {@link MediatorSystem} object is created in {@link ParallelSystemArrayMediator.createMediator}. Override the - * method and return one of them, which are derived from this {@link MediatorSystem} class, considering which - * type and protocol the **master** system follows: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * When the **master** orders a *parallel process* to this **slave**, then the {@link MediatorSystem} delivers the - * *parallel process* to its parent {@link ParallelSystemArrayMediator} object. The - * {@link ParallelSystemArrayMediator} object distributes the *parallel process* to its slaves system, - * {@link ParallelSystem} objects. When the *parallel process* has completed, then {@link MediatorSystem} reports the - * result to its **master**. - * - * - * - * - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System), - * [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - class MediatorWebServer extends MediatorServer { - /** - * @inheritdoc - */ - protected createServerBase(): protocol.IServerBase; - } - /** - * A mediator server, driver for the master client. - * - * The {@link MediatorDedicatedWorkerServer} is a class opening a server accepting the **master** client, following - * the DedicatedWorker's protocol. - * - * #### [Inherited] {@link MediatorSystem} - * The {@link MediatorSystem} is an abstract class helping {@link ParallelSystemArrayMediator} can be a **slave** - * system. The {@link MediatorSystem} interacts and communicates with the **master** system as a role of **slave**. - * - * This {@link MediatorSystem} object is created in {@link ParallelSystemArrayMediator.createMediator}. Override the - * method and return one of them, which are derived from this {@link MediatorSystem} class, considering which - * type and protocol the **master** system follows: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * When the **master** orders a *parallel process* to this **slave**, then the {@link MediatorSystem} delivers the - * *parallel process* to its parent {@link ParallelSystemArrayMediator} object. The - * {@link ParallelSystemArrayMediator} object distributes the *parallel process* to its slaves system, - * {@link ParallelSystem} objects. When the *parallel process* has completed, then {@link MediatorSystem} reports the - * result to its **master**. - * - * - * - * - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System), - * [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - class MediatorDedicatedWorkerServer extends MediatorServer { - /** - * @inheritdoc - */ - protected createServerBase(): protocol.IServerBase; - } - /** - * A mediator server, driver for the master client. - * - * The {@link MediatorSharedWorkerServer} is a class opening a server accepting the **master** client, following the - * SharedWorker's protocol. - * - * #### [Inherited] {@link MediatorSystem} - * The {@link MediatorSystem} is an abstract class helping {@link ParallelSystemArrayMediator} can be a **slave** - * system. The {@link MediatorSystem} interacts and communicates with the **master** system as a role of **slave**. - * - * This {@link MediatorSystem} object is created in {@link ParallelSystemArrayMediator.createMediator}. Override the - * method and return one of them, which are derived from this {@link MediatorSystem} class, considering which - * type and protocol the **master** system follows: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * When the **master** orders a *parallel process* to this **slave**, then the {@link MediatorSystem} delivers the - * *parallel process* to its parent {@link ParallelSystemArrayMediator} object. The - * {@link ParallelSystemArrayMediator} object distributes the *parallel process* to its slaves system, - * {@link ParallelSystem} objects. When the *parallel process* has completed, then {@link MediatorSystem} reports the - * result to its **master**. - * - * - * - * - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System), - * [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - class MediatorSharedWorkerServer extends MediatorServer { - /** - * @inheritdoc - */ - protected createServerBase(): protocol.IServerBase; - } -} -declare namespace samchon.templates.parallel { - /** - * A mediator client, driver for the master server. - * - * The {@link MediatorServer} is a class being a client connecting to the **master** server, following the protocol - * of Samchon Framework's own. - * - * #### [Inherited] {@link MediatorSystem} - * The {@link MediatorSystem} is an abstract class helping {@link ParallelSystemArrayMediator} can be a **slave** - * system. The {@link MediatorSystem} interacts and communicates with the **master** system as a role of **slave**. - * - * This {@link MediatorSystem} object is created in {@link ParallelSystemArrayMediator.createMediator}. Override the - * method and return one of them, which are derived from this {@link MediatorSystem} class, considering which - * type and protocol the **master** system follows: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * When the **master** orders a *parallel process* to this **slave**, then the {@link MediatorSystem} delivers the - * *parallel process* to its parent {@link ParallelSystemArrayMediator} object. The - * {@link ParallelSystemArrayMediator} object distributes the *parallel process* to its slaves system, - * {@link ParallelSystem} objects. When the *parallel process* has completed, then {@link MediatorSystem} reports the - * result to its **master**. - * - * - * - * - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System), - * [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - class MediatorClient extends MediatorSystem implements slave.ISlaveClient { - /** - * @hidden - */ - private ip; - /** - * @hidden - */ - private port; - /** - * Initializer Constructor. - * - * @param systemArray The parent {@link ParallelSystemArrayMediator} object. - * @param ip IP address to connect. - * @param port Port number to connect. - */ - constructor(systemArray: ParallelSystemArrayMediator, ip: string, port: number); - /** - * Initializer Constructor. - * - * @param systemArray The parent {@link DistributedSystemArrayMediator} object. - * @param ip IP address to connect. - * @param port Port number to connect. - */ - constructor(systemArray: distributed.DistributedSystemArrayMediator, ip: string, port: number); - /** - * Factory method creating {@link IServerConnector} object. - * - * The {@link createServerConnector createServerConnector()} is an abstract method creating - * {@link IServerConnector} object. Overrides and returns one of them, considering which protocol the **master** - * server follows: - * - * - {@link ServerConnector} - * - {@link WebServerConnector} - * - {@link SharedWorkerServerConnector} - * - * @return A newly created {@link IServerConnector} object. - */ - protected createServerConnector(): protocol.IServerConnector; - /** - * @inheritdoc - */ - start(): void; - /** - * @inheritdoc - */ - connect(): void; - } - /** - * A mediator client, driver for the master server. - * - * The {@link MediatorWebClient} is a class being a client connecting to the **master** server, following the - * web-socket protocol. - * - * #### [Inherited] {@link MediatorSystem} - * The {@link MediatorSystem} is an abstract class helping {@link ParallelSystemArrayMediator} can be a **slave** - * system. The {@link MediatorSystem} interacts and communicates with the **master** system as a role of **slave**. - * - * This {@link MediatorSystem} object is created in {@link ParallelSystemArrayMediator.createMediator}. Override the - * method and return one of them, which are derived from this {@link MediatorSystem} class, considering which - * type and protocol the **master** system follows: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * When the **master** orders a *parallel process* to this **slave**, then the {@link MediatorSystem} delivers the - * *parallel process* to its parent {@link ParallelSystemArrayMediator} object. The - * {@link ParallelSystemArrayMediator} object distributes the *parallel process* to its slaves system, - * {@link ParallelSystem} objects. When the *parallel process* has completed, then {@link MediatorSystem} reports the - * result to its **master**. - * - * - * - * - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System), - * [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - class MediatorWebClient extends MediatorClient { - /** - * @inheritdoc - */ - protected createServerConnector(): protocol.IServerConnector; - } - /** - * A mediator client, driver for the master server. - * - * The {@link MediatorSharedWorkerClient} is a class being a client connecting to the **master** server, following - * the SharedWorker's protocol. - * - * #### [Inherited] {@link MediatorSystem} - * The {@link MediatorSystem} is an abstract class helping {@link ParallelSystemArrayMediator} can be a **slave** - * system. The {@link MediatorSystem} interacts and communicates with the **master** system as a role of **slave**. - * - * This {@link MediatorSystem} object is created in {@link ParallelSystemArrayMediator.createMediator}. Override the - * method and return one of them, which are derived from this {@link MediatorSystem} class, considering which - * type and protocol the **master** system follows: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * When the **master** orders a *parallel process* to this **slave**, then the {@link MediatorSystem} delivers the - * *parallel process* to its parent {@link ParallelSystemArrayMediator} object. The - * {@link ParallelSystemArrayMediator} object distributes the *parallel process* to its slaves system, - * {@link ParallelSystem} objects. When the *parallel process* has completed, then {@link MediatorSystem} reports the - * result to its **master**. - * - * - * - * - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System), - * [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) - * @author Jeongho Nam - */ - class MediatorSharedWorkerClient extends MediatorClient { - /** - * @inheritdoc - */ - protected createServerConnector(): protocol.IServerConnector; - } -} -declare namespace samchon.templates.parallel { - /** - * Master of Parallel Processing System, a server accepting slave clients. - * - * The {@link ParallelClientArray} is an abstract class, derived from the {@link ParallelSystemArray} class, opening - * a server accepting {@link ParallelSystem parallel clients}. - * - * Extends this {@link ParallelClientArray}, overrides {@link createServerBase createServerBase()} to determine which - * protocol to follow and {@link createExternalClient createExternalClient()} creating child {@link ParallelSystem} - * object. After the extending and overridings, open this server using the {@link open open()} method. - * - * #### [Inherited] {@link ParallelSystemArray} - * The {@link ParallelSystemArray} is an abstract class containing and managing remote parallel **slave** system - * drivers, {@link ParallelSystem} objects. Within framework of network, {@link ParallelSystemArray} represents your - * system, a **Master** of *Parallel Processing System* that requesting *parallel process* to slave systems and the - * children {@link ParallelSystem} objects represent the remote slave systems, who is being requested the - * *parallel processes*. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices - * will be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * - * - * - * - * #### Proxy Pattern - * This class {@link ParallelSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link ParallelSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *Proxy Pattern*: - * - * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
    - *
  • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
  • - *
  • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
  • - *
  • Those strategy is called *Proxy Pattern*.
  • - *
- * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ - abstract class ParallelClientArray extends ParallelSystemArray implements external.IExternalClientArray { - /** - * @hidden - */ - private server_base_; - /** - * Default Constructor. - */ - constructor(); - /** - * Factory method creating {@link IServerBase} object. - * - * This method {@link createServerBase createServerBase()} determines which protocol is used in this server, - * {@link ExternalClientArray}. If the protocol is determined, then {@link ExternalSystem external clients} who - * may connect to {@link ExternalClientArray this server} must follow the specified protocol. - * - * Overrides the {@link createServerBase createServerBase()} method to create and return one of them: - * - * - {@link ServerBase} - * - {@link WebServerBase} - * - {@link SharedWorkerServerBase} - * - * @return A new {@link IServerBase} object. - */ - protected abstract createServerBase(): protocol.IServerBase; - /** - * Add a newly connected remote client. - * - * When a {@link IClientDriver remote client} connects to this *master server of parallel processing system*, - * then this {@link ParallelClientArray} creates a child {@link ParallelSystem parallel client} object through - * the {@link createExternalClient createExternalClient()} method and {@link insert inserts} it. - * - * @param driver A communicator for external client. - */ - addClient(driver: protocol.IClientDriver): void; - /** - * (Deprecated) Factory method creating child object. - * - * The method {@link createChild createChild()} is deprecated. Don't use and override this. - * - * Note that, the {@link ParallelClientArray} is a server accepting {@link ParallelSystem parallel clients}. - * There's no way to creating the {@link ParallelSystem parallel clients} in advance before opening the server. - * - * @param xml An {@link XML} object represents the child {@link ParallelSystem} object. - * @return ```null``` - */ - createChild(xml: library.XML): System; - /** - * Factory method creating {@link ParallelSystem} object. - * - * The method {@link createExternalClient createExternalClient()} is a factory method creating a child - * {@link ParallelSystem} object, that is called whenever a parallel client has connected, by - * {@link addClient addClient()}. - * - * Overrides this {@link createExternalClient} method and creates a type of {@link ParallelSystem} object with - * the *driver* that communicates with the parallel client. After the creation, returns the {@link ParallelSystem} - * object. Then whenever a parallel client has connected, matched {@link ParallelSystem} object will be - * constructed and {@link insert inserted} into this {@link ParallelClientArray} object. - * - * @param driver A communicator with the parallel client. - * @return A newly created {@link ParallelSystem} object. - */ - protected abstract createExternalClient(driver: protocol.IClientDriver): System; - /** - * @inheritdoc - */ - open(port: number): void; - /** - * @inheritdoc - */ - close(): void; - } -} -declare namespace samchon.templates.parallel { - /** - * Mediator of Parallel Processing System. - * - * The {@link ParallelSystemArrayMediator} class be a **master** for its slave systems, and be a **slave** to its - * master system at the same time. This {@link ParallelSystemArrayMediator} be a **master **system, containing and - * managing {@link ParallelSystem} objects, which represent parallel slave systems, by extending - * {@link ParallelSystemArray} class. Also, be a **slave** system through {@link getMediator mediator} object, which is - * derived from the {@link SlaveSystem} class. - * - * As a **master**, you can specify this {@link ParallelSystemArrayMediator} class to be a master server accepting - * slave clients or a master client to connecting slave servers. Even both of them is possible. Extends one - * of them below and overrides abstract factory method(s) creating the child {@link ParallelSystem} object. - * - * - {@link ParallelClientArrayMediator}: A server accepting {@link ParallelSystem parallel clients}. - * - {@link ParallelServerArrayMediator}: A client connecting to {@link ParallelServer parallel servers}. - * - {@link ParallelServerClientArrayMediator}: Both of them. Accepts {@link ParallelSystem parallel clients} and - * connects to {@link ParallelServer parallel servers} at the same time. - * - * As a **slave**, you can specify this {@link ParallelSystemArrayMediator} to be a client slave connecting to - * master server or a server slave accepting master client by overriding the {@link createMediator} method. - * Overrides the {@link createMediator createMediator()} method and return one of them: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * #### [Inherited] {@link ParallelSystemArray} - * The {@link ParallelSystemArray} is an abstract class containing and managing remote parallel **slave** system - * drivers, {@link ParallelSystem} objects. Within framework of network, {@link ParallelSystemArray} represents your - * system, a **Master** of *Parallel Processing System* that requesting *parallel process* to slave systems and the - * children {@link ParallelSystem} objects represent the remote slave systems, who is being requested the - * *parallel processes*. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices - * will be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * - * - * - * - * #### Proxy Pattern - * This class {@link ParallelSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link ParallelSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *Proxy Pattern*: - * - * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
    - *
  • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
  • - *
  • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
  • - *
  • Those strategy is called *Proxy Pattern*.
  • - *
- * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ - abstract class ParallelSystemArrayMediator extends ParallelSystemArray { - /** - * @hidden - */ - private mediator_; - /** - * Default Constructor. - */ - constructor(); - /** - * Factory method creating a {@link MediatorSystem} object. - * - * The {@link createMediator createMediator()} is an abstract method creating the {@link MediatorSystem} object. - * - * You know what? this {@link ParallelSystemArrayMediator} class be a **master** for its slave systems, and be a - * **slave** to its master system at the same time. The {@link MediatorSystem} object makes it possible; be a - * **slave** system. This {@link createMediator} determines specific type of the {@link MediatorSystem}. - * - * Overrides the {@link createMediator createMediator()} method to create and return one of them following which - * protocol and which type of remote connection (server or client) will be used: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * @return A newly created {@link MediatorSystem} object. - */ - protected abstract createMediator(): MediatorSystem; - /** - * Start mediator. - * - * If the {@link getMediator mediator} is a type of server, then opens the server accepting master client. - * Otherwise, the {@link getMediator mediator} is a type of client, then connects the master server. - */ - protected startMediator(): void; - /** - * Get {@link MediatorSystem} object. - * - * When you need to send an {@link Invoke} message to the master system of this - * {@link ParallelSystemArrayMediator}, then send to the {@link MediatorSystem} through this {@link getMediator}. - * - * ```typescript - * this.getMediator().sendData(...); - * ``` - * - * @return The {@link MediatorSystem} object. - */ - getMediator(): MediatorSystem; - /** - * @hidden - */ - protected _Complete_history(history: PRInvokeHistory): boolean; - } -} -declare namespace samchon.templates.parallel { - /** - * Mediator of Parallel Processing System, a server accepting slave clients. - * - * The {@link ParallelClientArrayMediator} is an abstract class, derived from the {@link ParallelSystemArrayMediator} - * class, opening a server accepting {@link ParallelSystem parallel clients} as a **master**. - * - * Extends this {@link ParallelClientArrayMediator}, overrides {@link createServerBase createServerBase()} to - * determine which protocol to follow and {@link createExternalClient createExternalClient()} creating child - * {@link ParallelSystem} object. After the extending and overridings, open this server using the - * {@link open open()} method. - * - * #### [Inherited] {@link ParallelSystemArrayMediator} - * The {@link ParallelSystemArrayMediator} class be a **master** for its slave systems, and be a **slave** to its - * master system at the same time. This {@link ParallelSystemArrayMediator} be a **master **system, containing and - * managing {@link ParallelSystem} objects, which represent parallel slave systems, by extending - * {@link ParallelSystemArray} class. Also, be a **slave** system through {@link getMediator mediator} object, which is - * derived from the {@link SlaveSystem} class. - * - * As a **slave**, you can specify this {@link ParallelSystemArrayMediator} to be a client slave connecting to - * master server or a server slave accepting master client by overriding the {@link createMediator} method. - * Overrides the {@link createMediator createMediator()} method and return one of them: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * #### [Inherited] {@link ParallelSystemArray} - * The {@link ParallelSystemArray} is an abstract class containing and managing remote parallel **slave** system - * drivers, {@link ParallelSystem} objects. Within framework of network, {@link ParallelSystemArray} represents your - * system, a **Master** of *Parallel Processing System* that requesting *parallel process* to slave systems and the - * children {@link ParallelSystem} objects represent the remote slave systems, who is being requested the - * *parallel processes*. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices - * will be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * - * - * - * - * #### Proxy Pattern - * This class {@link ParallelSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link ParallelSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *Proxy Pattern*: - * - * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
    - *
  • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
  • - *
  • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
  • - *
  • Those strategy is called *Proxy Pattern*.
  • - *
- * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ - abstract class ParallelClientArrayMediator extends ParallelSystemArrayMediator implements external.IExternalClientArray { - /** - * @hidden - */ - private server_base_; - /** - * Default Constructor. - */ - constructor(); - /** - * Factory method creating {@link IServerBase} object. - * - * This method {@link createServerBase createServerBase()} determines which protocol is used in this server, - * {@link ParallelClientArrayMediator}. If the protocol is determined, then - * {@link ParallelSystem parallel clients} who may connect to {@link ParallelClientArrayMediator this server} - * must follow the specified protocol. - * - * Overrides the {@link createServerBase createServerBase()} method to create and return one of them: - * - * - {@link ServerBase} - * - {@link WebServerBase} - * - {@link SharedWorkerServerBase} - * - * @return A new {@link IServerBase} object. - */ - protected abstract createServerBase(): protocol.IServerBase; - /** - * Add a newly connected remote client. - * - * When a {@link IClientDriver remote client} connects to this *master server of parallel processing system*, - * then this {@link ParallelClientArrayMediator} creates a child {@link ParallelSystem parallel client} object - * through the {@link createExternalClient createExternalClient()} method and {@link insert inserts} it. - * - * @param driver A communicator for parallel client. - */ - addClient(driver: protocol.IClientDriver): void; - /** - * (Deprecated) Factory method creating child object. - * - * The method {@link createChild createChild()} is deprecated. Don't use and override this. - * - * Note that, the {@link ParallelClientArrayMediator} is a server accepting {@link ParallelSystem parallel - * clients} as a master. There's no way to creating the {@link ParallelSystem parallel clients} in advance before - * opening the server. - * - * @param xml An {@link XML} object represents the child {@link ParallelSystem} object. - * @return null - */ - createChild(xml: library.XML): System; - /** - * Factory method creating {@link ParallelSystem} object. - * - * The method {@link createExternalClient createExternalClient()} is a factory method creating a child - * {@link ParallelSystem} object, that is called whenever a parallel client has connected, by - * {@link addClient addClient()}. - * - * Overrides this {@link createExternalClient} method and creates a type of {@link ParallelSystem} object with - * the *driver* that communicates with the parallel client. After the creation, returns the {@link ParallelSystem} - * object. Then whenever a parallel client has connected, matched {@link ParallelSystem} object will be - * constructed and {@link insert inserted} into this {@link ParallelClientArrayMediator} object. - * - * @param driver A communicator with the parallel client. - * @return A newly created {@link ParallelSystem} object. - */ - protected abstract createExternalClient(driver: protocol.IClientDriver): System; - /** - * @inheritdoc - */ - open(port: number): void; - /** - * @inheritdoc - */ - close(): void; - } -} -declare namespace samchon.templates.parallel { - /** - * An interface for a parallel slave server driver. - * - * The easiest way to defining a driver for parallel **slave** server is extending {@link ParallelServer} class. - * However, if you've to interact with a prallel **slave** system who can be both server and client, them make a class - * (let's name it **BaseSystem**) extending the {@link ParallelSystem} class. At next, make a new class (now, I name it - * **BaseServer**) extending the **BaseSystem** and implements this interface {@link IParallelServer}. Define the - * **BaseServer** following those codes on below: - * - * - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ - interface IParallelServer extends ParallelSystem { - /** - * Connect to slave server. - */ - connect(): void; - } - /** - * A driver for parallel slave server. - * - * The {@link ParallelServer} is an abstract class, derived from the {@link ParallelSystem} class, connecting to - * remote, parallel **slave** server. Extends this {@link ParallelServer} class and overrides the - * {@link createServerConnector createServerConnector()} method following which protocol the **slave** server uses. - * - * #### [Inherited] {@link ParallelSystem} - * The {@link ParallelSystem} is an abstract class represents a **slave** system in *Parallel Processing System*, - * connected with this **master** system. This {@link ParallelSystem} takes full charge of network communication with - * the remote, parallel **slave** system has connected. - * - * When a *parallel process* is requested (by {@link ParallelSystemArray.sendSegmentData} or - * {@link ParallelSystemArray.sendPieceData}), the number of pieces to be allocated to a {@link ParallelSystem} is - * turn on its {@link getPerformance performance index}. Higher {@link getPerformance performance index}, then - * more pieces are requested. The {@link getPerformance performance index} is revaluated whenever a *parallel process* - * has completed, basic on the execution time and number of pieces. You can sugguest or enforce the - * {@link getPerformance performance index} with {@link setPerformance} or {@link enforcePerformance}. - * - * - * - * - * - * #### Bridge & Proxy Pattern - * This class {@link ParallelSystem} is derived from the {@link ExternalSystem} class. Thus, you can take advantage - * of the *Bridge & Proxy Pattern* in this {@link ParallelSystem} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *Bridge & Proxy Pattern*: - * - * The {@link ExternalSystem} class can be a *bridge* for *logical proxy*. In framework within user, - * which {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
    - *
  • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
  • - *
  • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
  • - *
  • Those strategy is called *Bridge Pattern* and *Proxy Pattern*.
  • - *
- * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ - abstract class ParallelServer extends ParallelSystem implements IParallelServer { - /** - * IP address of target external system to connect. - */ - protected ip: string; - /** - * Port number of target external system to connect. - */ - protected port: number; - /** - * Construct from parent {@link ParallelSystemArray}. - * - * @param systemArray The parent {@link ParallelSystemArray} object. - */ - constructor(systemArray: ParallelSystemArray); - /** - * Factory method creating {@link IServerConnector} object. - * - * The {@link createServerConnector createServerConnector()} is an abstract method creating - * {@link IServerConnector} object. Overrides and returns one of them, considering which protocol the slave server - * follows: - * - * - {@link ServerConnector} - * - {@link WebServerConnector} - * - {@link DedicatedWorkerServerConnector} - * - {@link SharedWorkerServerConnector} - * - * @return A newly created {@link IServerConnector} object. - */ - protected abstract createServerConnector(): protocol.IServerConnector; - /** - * @inheritdoc - */ - connect(): void; - } -} -declare namespace samchon.templates.parallel { - /** - * Master of Parallel Processing System, a client connecting to slave servers. - * - * The {@link ParallelServerArray} is an abstract class, derived from the {@link ParallelSystemArray} class, - * connecting to {@link IParallelServer parallel servers}. - * - * Extends this {@link ParallelServerArray} and overrides {@link createChild createChild()} method creating child - * {@link IParallelServer} object. After the extending and overriding, construct children {@link IParallelServer} - * objects and call the {@link connect connect()} method. - * - * #### [Inherited] {@link ParallelSystemArray} - * The {@link ParallelSystemArray} is an abstract class containing and managing remote parallel **slave** system - * drivers, {@link ParallelSystem} objects. Within framework of network, {@link ParallelSystemArray} represents your - * system, a **Master** of *Parallel Processing System* that requesting *parallel process* to slave systems and the - * children {@link ParallelSystem} objects represent the remote slave systems, who is being requested the - * *parallel processes*. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices - * will be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * - * - * - * - * #### Proxy Pattern - * This class {@link ParallelSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link ParallelSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *Proxy Pattern*: - * - * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
    - *
  • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
  • - *
  • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
  • - *
  • Those strategy is called *Proxy Pattern*.
  • - *
- * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ - abstract class ParallelServerArray extends ParallelSystemArray implements external.IExternalServerArray { - /** - * Default Constructor. - */ - constructor(); - /** - * @inheritdoc - */ - connect(): void; - } -} -declare namespace samchon.templates.parallel { - /** - * Mediator of Parallel Processing System, a client connecting to slave servers. - * - * The {@link ParallelServerArrayMediator} is an abstract class, derived from the {@link ParallelSystemArrayMediator} - * class, connecting to {@link IParallelServer parallel servers}. - * - * Extends this {@link ParallelServerArrayMediator} and overrides {@link createChild createChild()} method creating - * child {@link IParallelServer} object. After the extending and overriding, construct children - * {@link IParallelServer} objects and call the {@link connect connect()} method. - * - * #### [Inherited] {@link ParallelSystemArrayMediator} - * The {@link ParallelSystemArrayMediator} class be a **master** for its slave systems, and be a **slave** to its - * master system at the same time. This {@link ParallelSystemArrayMediator} be a **master **system, containing and - * managing {@link ParallelSystem} objects, which represent parallel slave systems, by extending - * {@link ParallelSystemArray} class. Also, be a **slave** system through {@link getMediator mediator} object, which is - * derived from the {@link SlaveSystem} class. - * - * As a **master**, you can specify this {@link ParallelSystemArrayMediator} class to be a master server accepting - * slave clients or a master client to connecting slave servers. Even both of them is possible. Extends one - * of them below and overrides abstract factory method(s) creating the child {@link ParallelSystem} object. - * - * - {@link ParallelClientArrayMediator}: A server accepting {@link ParallelSystem parallel clients}. - * - {@link ParallelServerArrayMediator}: A client connecting to {@link ParallelServer parallel servers}. - * - {@link ParallelServerClientArrayMediator}: Both of them. Accepts {@link ParallelSystem parallel clients} and - * connects to {@link ParallelServer parallel servers} at the same time. - * - * As a **slave**, you can specify this {@link ParallelSystemArrayMediator} to be a client slave connecting to - * master server or a server slave accepting master client by overriding the {@link createMediator} method. - * Overrides the {@link createMediator createMediator()} method and return one of them: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * #### [Inherited] {@link ParallelSystemArray} - * The {@link ParallelSystemArray} is an abstract class containing and managing remote parallel **slave** system - * drivers, {@link ParallelSystem} objects. Within framework of network, {@link ParallelSystemArray} represents your - * system, a **Master** of *Parallel Processing System* that requesting *parallel process* to slave systems and the - * children {@link ParallelSystem} objects represent the remote slave systems, who is being requested the - * *parallel processes*. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices - * will be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * - * - * - * - * #### Proxy Pattern - * This class {@link ParallelSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link ParallelSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *Proxy Pattern*: - * - * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
    - *
  • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
  • - *
  • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
  • - *
  • Those strategy is called *Proxy Pattern*.
  • - *
- * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ - abstract class ParallelServerArrayMediator extends ParallelSystemArrayMediator implements external.IExternalServerArray { - /** - * Default Constructor. - */ - constructor(); - /** - * @inheritdoc - */ - connect(): void; - } -} -declare namespace samchon.templates.parallel { - /** - * Master of Parallel Processing System, be a server and client at the same time. - * - * The {@link ParallelServerClientArray} is an abstract class, derived from the {@link ParallelSystemArray} class, - * opening a server accepting {@link ParallelSystem parallel clients} and being a client connecting to - * {@link IParallelServer parallel servers} at the same time. - * - * Extends this {@link ParallelServerClientArray} and overrides below methods. After the overridings, open server - * with {@link open open()} method and connect to {@link IParallelServer parallel servers} through the - * {@link connect connect()} method. - * - * - {@link createServerBase createServerBase()} - * - {@link createExternalClient createExternalClient()} - * - {@link createExternalServer createExternalServer()} - * - * #### [Inherited] {@link ParallelSystemArray} - * The {@link ParallelSystemArray} is an abstract class containing and managing remote parallel **slave** system - * drivers, {@link ParallelSystem} objects. Within framework of network, {@link ParallelSystemArray} represents your - * system, a **Master** of *Parallel Processing System* that requesting *parallel process* to slave systems and the - * children {@link ParallelSystem} objects represent the remote slave systems, who is being requested the - * *parallel processes*. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices - * will be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * - * - * - * - * #### Proxy Pattern - * This class {@link ParallelSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link ParallelSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *Proxy Pattern*: - * - * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
    - *
  • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
  • - *
  • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
  • - *
  • Those strategy is called *Proxy Pattern*.
  • - *
- * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ - abstract class ParallelServerClientArray extends ParallelClientArray implements external.IExternalServerClientArray { - /** - * Default Constructor. - */ - constructor(); - /** - * Factory method of a child Entity. - * - * This method is migrated to {@link createExternalServer}. Override the {@link createExternalServer} method. - * - * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. - * @return A new child Entity via {@link createExternalServer createExternalServer()}. - */ - createChild(xml: library.XML): System; - /** - * Factory method creating an {@link IParallelServer} object. - * - * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. - * @return A newly created {@link IParallelServer} object. - */ - protected abstract createExternalServer(xml: library.XML): System; - /** - * @inheritdoc - */ - connect(): void; - } -} -declare namespace samchon.templates.parallel { - /** - * Mediator of Parallel Processing System, be a server and client at the same time as a **master**. - * - * The {@link ParallelServerClientArrayMediator} is an abstract class, derived from the - * {@link ParallelSystemArrayMediator} class, opening a server accepting {@link ParallelSystem parallel clients} and - * being a client connecting to {@link IParallelServer parallel servers} at the same time. - * - * Extends this {@link ParallelServerClientArrayMediator} and overrides below methods. After the overridings, open - * server with {@link open open()} method and connect to {@link IParallelServer parallel servers} through the - * {@link connect connect()} method. - * - * - {@link createServerBase createServerBase()} - * - {@link createExternalClient createExternalClient()} - * - {@link createExternalServer createExternalServer()} - * - * #### [Inherited] {@link ParallelSystemArrayMediator} - * The {@link ParallelSystemArrayMediator} class be a **master** for its slave systems, and be a **slave** to its - * master system at the same time. This {@link ParallelSystemArrayMediator} be a **master **system, containing and - * managing {@link ParallelSystem} objects, which represent parallel slave systems, by extending - * {@link ParallelSystemArray} class. Also, be a **slave** system through {@link getMediator mediator} object, which is - * derived from the {@link SlaveSystem} class. - * - * As a **master**, you can specify this {@link ParallelSystemArrayMediator} class to be a master server accepting - * slave clients or a master client to connecting slave servers. Even both of them is possible. Extends one - * of them below and overrides abstract factory method(s) creating the child {@link ParallelSystem} object. - * - * - {@link ParallelClientArrayMediator}: A server accepting {@link ParallelSystem parallel clients}. - * - {@link ParallelServerArrayMediator}: A client connecting to {@link ParallelServer parallel servers}. - * - {@link ParallelServerClientArrayMediator}: Both of them. Accepts {@link ParallelSystem parallel clients} and - * connects to {@link ParallelServer parallel servers} at the same time. - * - * As a **slave**, you can specify this {@link ParallelSystemArrayMediator} to be a client slave connecting to - * master server or a server slave accepting master client by overriding the {@link createMediator} method. - * Overrides the {@link createMediator createMediator()} method and return one of them: - * - * - A client slave connecting to master server: - * - {@link MediatorClient} - * - {@link MediatorWebClient} - * - {@link MediatorSharedWorkerClient} - * - A server slave accepting master client: - * - {@link MediatorServer} - * - {@link MediatorWebServer} - * - {@link MediatorDedicatedWorkerServer} - * - {@link MediatorSharedWorkerServer} - * - * #### [Inherited] {@link ParallelSystemArray} - * The {@link ParallelSystemArray} is an abstract class containing and managing remote parallel **slave** system - * drivers, {@link ParallelSystem} objects. Within framework of network, {@link ParallelSystemArray} represents your - * system, a **Master** of *Parallel Processing System* that requesting *parallel process* to slave systems and the - * children {@link ParallelSystem} objects represent the remote slave systems, who is being requested the - * *parallel processes*. - * - * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. - * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s - * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices - * will be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. - * - * - * - * - * - * #### Proxy Pattern - * This class {@link ParallelSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take - * advantage of the *Proxy Pattern* in the {@link ParallelSystemArray} class. If a process to request is not the - * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it - * may better to utilizing the *Proxy Pattern*: - * - * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not - * important. Only interested in user's perspective is *which can be done*. - * - * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged - * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. - * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. - * - *
    - *
  • - * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring - * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. - *
  • - *
  • - * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call - * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the - * external system. - *
  • - *
  • Those strategy is called *Proxy Pattern*.
  • - *
- * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ - abstract class ParallelServerClientArrayMediator extends ParallelClientArrayMediator implements external.IExternalServerClientArray { - /** - * Default Constructor. - */ - constructor(); - /** - * Factory method of a child Entity. - * - * This method is migrated to {@link createExternalServer}. Override the {@link createExternalServer} method. - * - * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. - * @return A new child Entity via {@link createExternalServer createExternalServer()}. - */ - createChild(xml: library.XML): System; - /** - * Factory method creating an {@link IParallelServer} object. - * - * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. - * @return A newly created {@link IParallelServer} object. - */ - protected abstract createExternalServer(xml: library.XML): System; - /** - * @inheritdoc - */ - connect(): void; - } -} -declare namespace samchon.templates.parallel { - /** - * History of an {@link Invoke} message. - * - * The {@link PRInvokeHistory} is a class archiving history log of an {@link Invoke} message which requests the - * *parallel process*, created whenever {@link ParallelSystemArray.sendSegmentData} or - * {@link ParallelSystemArray.sendSegmentData} is called. - * - * When the *parallel process* has completed, then {@link complete complete()} is called and the *elapsed time* is - * determined. The elapsed time is utilized for computation of {@link ParallelSystem.getPerformance performance index} - * of each {@link ParallelSystem parallel slave system}. - * - * - * - * - * - * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) - * @author Jeongho Nam - */ - class PRInvokeHistory extends protocol.InvokeHistory { - /** - * @hidden - */ - private first; - /** - * @hidden - */ - private last; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from an {@link Invoke} message. - * - * @param invoke An {@link Invoke} message requesting a *parallel process*. - */ - constructor(invoke: protocol.Invoke); - /** - * Get initial piece's index. - * - * Returns initial piece's index in the section of requested *parallel process*. - * - * @return The initial index. - */ - getFirst(): number; - /** - * Get final piece's index. - * - * Returns initial piece's index in the section of requested *parallel process*. The range used is - * [*first*, *last*), which contains all the pieces' indices between *first* and *last*, including the piece - * pointed by index *first*, but not the piece pointed by the index *last*. - * - * @return The final index. - */ - getLast(): number; - /** - * Compute number of allocated pieces. - */ - computeSize(): number; - } -} -declare namespace samchon.templates.service { - /** - * A driver of remote client. - * - * The {@link Client} is an abstract class representing and interacting with a remote client. It deals the network - * communication with the remote client and shifts {@link Invoke} message to related {@link User} and {@link Service} - * objects. - * - * Extends this {@link Client} class and override the {@link createService} method, a factory method creating a child - * {@link Service} object. Note that, {@link Client} represents a remote client, not *an user*, a specific *web page* - * or *service*. Do not define logics about user or account information. It must be declared in the parent - * {@link User} class. Also, don't define processes of a specific a web page or service. Defines them in the child - * {@link Service} class. - * - * - * - * - * - * @handbook [Templates - Cloud Service](https://github.com/samchon/framework/wiki/TypeScript-Templates-Cloud_Service) - * @author Jeongho Nam - */ - abstract class Client implements protocol.IProtocol { - /** - * @hidden - */ - private user_; - /** - * @hidden - */ - private no_; - /** - * @hidden - */ - private communicator_; - /** - * @hidden - */ - private service_; - /** - * Construct from parent {@link User} and communicator. - * - * @param user Parent {@link User} object. - * @param driver Communicator with remote client. - */ - constructor(user: User, driver: protocol.WebClientDriver); - /** - * Default Destructor. - * - * This {@link destructor destructor()} method is called when the {@link Client} object is destructed and this - * {@link Client} object is destructed when connection with the remote client is closed or this {@link Client} - * object is {@link User.erase erased} from its parent {@link User} object. - * - * Note that, don't call this {@link destructor destructor()} method by yourself. It must be called automatically - * by those *destruction* cases. Also, if your derived {@link Client} class has something to do on the - * *destruction*, then overrides this {@link destructor destructor()} method and defines the something to do. - * Overriding this {@link destructor destructor()}, don't forget to calling ```super.destructor();``` on tail. - * - * ```typescript - * class MyUser extends protocol.service.Client - * { - * protected destructor(): void - * { - * // DO SOMETHING - * this.do_something(); - * - * // CALL SUPER.DESTRUCTOR() ON TAIL. DON'T FORGET THIS - * super.destructor(); - * } - * } - * ``` - */ - protected destructor(): void; - /** - * Factory method creating {@link Service} object. - * - * @param path Requested path. - * @return A newly created {@link Service} object or ```null```. - */ - protected abstract createService(path: string): Service; - /** - * Close connection. - */ - close(): void; - /** - * Get parent {@link User} object. - * - * Get the parent {@link User} object, who is groupping {@link Client} objects with same session id. - * - * @return The parent {@link User} object. - */ - getUser(): User; - /** - * Get child {@link Service} object. - * - * @return The child {@link Service} object. - */ - getService(): Service; - /** - * Get sequence number. - * - * Get sequence number of this {@link Client} object in the parent {@link User} object. This sequence number also - * be a *key* in the parent {@link User} object, who extended the ```std.HashMap```. - * - * @return Sequence number. - */ - getNo(): number; - /** - * Change related {@link Service} object. - * - * @param path Requested, identifier path. - */ - protected changeService(path: string): void; - /** - * Change {@link Service} to another. - * - * @param service {@link service} object to newly assigned. - */ - protected changeService(service: Service): void; - /** - * Send an {@link Invoke} message. - * - * Sends an {@link Invoke} message to remote client. - * - * @param invoke An {@link Invoke} messgae to send to remote client. - */ - sendData(invoke: protocol.Invoke): void; - /** - * Handle a replied {@link Invoke} message. - * - * The default {@link Client.replyData Client.replyData()} shifts chain to its parent {@link User} and belonged - * {@link Service} objects, by calling the the {@link User.replyData User.replyData()} and - * {@link Service.replyData Service.replyData()} methods. - * - * Note that, {@link Client} represents a remote client, not *an user*, a specific *web page* or *service*. Do not - * define logics about user or account information. It must be declared in the parent {@link User} class. Also, - * don't define processes of a specific a web page or service. Defines them in the child {@link Service} class. - * - * ```typescript - * class protocol.service.Client - * { - * public replyData(invoke: protocol.Invoke): void - * { - * // SHIFT TO PARENT USER - * // THE PARENT USER ALSO MAY SHIFT TO ITS PARENT SERVER - * this.getUser().replyData(invoke); - * - * // SHIFT TO BELOGED SERVICE - * if (this.getService() != null) - * this.getService().replyData(invoke); - * } - * } - * - * class MyClient extends protocol.service.Client - * { - * public replyData(invoke: protocol.Invoke): void - * { - * if (invoke.getListener() == "do_something_in_client_level") - * this.do_something_in_client_level(); - * else - * super.replyData(invoke); - * } - * } - * ``` - * - * @param invoke An {@link Invoke invoke} message to be handled in {@link Client} level. - */ - replyData(invoke: protocol.Invoke): void; - } -} -/** - * A system template for Cloud Service. - * - * @handbook [Templates - Cloud Service](https://github.com/samchon/framework/wiki/TypeScript-Templates-Cloud_Service) - * @author Jeongho Nam - */ -declare namespace samchon.templates.service { - /** - * A cloud server. - * - * The {@link Server} is an abstract server class, who can build a real-time cloud server, that is following the - * web-socket protocol. Extends this {@link Server} and related classes and overrides abstract methods under below. - * After the overridings, open this {@link Server cloud server} using the {@link open open()} method. - * - * - Objects in composite relationship and their factory methods - * - {@link User}: {@link Server.createUser Server.createUser()} - * - {@link Client}: {@link User.createClient User.createClient()} - * - {@link Service}: {@link Client.createService Client.createService()} - * - {@link Invoke} message chains; {@link IProtocol.replyData replyData} - * - {@link Server.replyData} - * - {@link User.replyData} - * - {@link Client.replyData} - * - {@link Service.replyData} - * - * - * - * - * - * @handbook [Templates - Cloud Service](https://github.com/samchon/framework/wiki/TypeScript-Templates-Cloud_Service) - * @author Jeongho Nam - */ - abstract class Server extends protocol.WebServer implements protocol.IProtocol { - /** - * @hidden - */ - private session_map_; - /** - * @hidden - */ - private account_map_; - /** - * Default Constructor. - */ - constructor(); - /** - * Factory method creating {@link User} object. - * - * @return A newly created {@link User} object. - */ - protected abstract createUser(): User; - /** - * Test wheter an {@link User} exists with the *accountID*. - * - * @param accountID Account id of {@link User} to find. - * @return Exists or not. - */ - has(accountID: string): boolean; - /** - * Get an {@link User} object by its *accountID*. - * - * @param accountID Account id of {@link User} to get. - * @return An {@link User} object. - */ - get(accountID: string): User; - /** - * Send an {@link Invoke} message. - * - * Sends an {@link Invoke} message to all remote clients through the belonged {@link User} and {@link Client} - * objects. Sending the {@link Invoke} message to all remote clients, it's came true by passing through - * {@link User.sendData User.sendData()}. And the {@link User.sendData} also pass through the - * {@link Client.sendData Client.sendData()}. - * - * ```typescript - * class protocol.service.Server - * { - * public sendData(invoke: Invoke): void - * { - * for (user: User in this) - * for (client: Client in user) - * client.sendData(invoke); - * } - * } - * ``` - * - * @param invoke {@link Invoke} message to send to all remote clients. - */ - sendData(invoke: protocol.Invoke): void; - /** - * Handle a replied {@link Invoke} message. - * - * The {@link Server.replyData Server.replyData()} is an abstract method that handling {@link Invoke} message - * that should be handled in the {@link Server} level. Overrides this {@link replyData replyData()} method and - * defines what to do with the {@link Invoke} message in this {@link Server} level. - * - * @param invoke An {@link Invoke invoke} message to be handled in {@link Server} level. - */ - abstract replyData(invoke: protocol.Invoke): void; - /** - * Add a newly connected remote client. - * - * When a {@link WebClientDriver remote client} connects to this cloud server, then {@link Server} queries the - * {WebClientDriver.getSessionID session id} of the {@link WebClientDriver remote client}. If the - * {WebClientDriver.getSessionID session id} is new one, then creates a new {@link User} object. - * - * At next, creates a {@link Client} object who represents the newly connected remote client and insert the - * {@link Client} object to the matched {@link User} object which is new or ordinary one following the - * {WebClientDriver.getSessionID session id}. At last, a {@link Service} object can be created with referencing - * the {@link WebClientDriver.getPath path}. - * - * List of objects can be created by this method. - * - {@link User} by {@link createUser createUser()}. - * - {@link Client} by {@link User.createClient User.createClient()}. - * - {@link Service} by {@link Client.createService Client.createService()}. - * - * @param driver A web communicator for remote client. - */ - addClient(driver: protocol.WebClientDriver): void; - /** - * @hidden - */ - private erase_user(user); - } -} -declare namespace samchon.templates.service { - /** - * A service. - * - * The {@link Service} is an abstract class who represents a service, that is providing functions a specific page. - * - * Extends the {@link Service} class and defines its own service, which to be provided for the specific weg page, - * by overriding the {@link replyData replyData()} method. Note that, the service, functions for the specific page - * should be defined in this {@link Service} class, not its parent {@link Client} class who represents a remote client - * and takes communication responsibility. - * - * - * - * - * - * @handbook [Templates - Cloud Service](https://github.com/samchon/framework/wiki/TypeScript-Templates-Cloud_Service) - * @author Jeongho Nam - */ - abstract class Service implements protocol.IProtocol { - /** - * @hidden - */ - private client_; - /** - * @hidden - */ - private path_; - /** - * Construct from parent {@link Client} and requested path. - * - * @param client Driver of remote client. - * @param path Requested path that identifies this {@link Service}. - */ - constructor(client: Client, path: string); - /** - * Default Destructor. - * - * This {@link destructor destructor()} method is call when the {@link Service} object is destructed and the - * {@link Service} object is destructed when its parent {@link Client} object has - * {@link Client.destructor destructed} or the {@link Client} object {@link Client.changeService changed} its - * child {@link Service service} object to another one. - * - * Note that, don't call this {@link destructor destructor()} method by yourself. It must be called automatically - * by those *destruction* cases. Also, if your derived {@link Service} class has something to do on the - * *destruction*, then overrides this {@link destructor destructor()} method and defines the something to do. - */ - protected destructor(): void; - /** - * Get client. - */ - getClient(): Client; - /** - * Get requested path. - */ - getPath(): string; - /** - * Send an {@link Invoke} message. - * - * Sends an {@link Invoke} message to remote system through parent {@link Client} object ({@link Client.sendData}). - * - * @param invoke An {@link Invoke} message to send to the remte system. - */ - sendData(invoke: protocol.Invoke): void; - /** - * @inheritdoc - */ - abstract replyData(invoke: protocol.Invoke): void; - } -} -declare namespace samchon.templates.service { - /** - * An user. - * - * The {@link User} is an abstract class groupping {@link Client} objects, who communicates with remote client, with - * same *session id*. This {@link User} represents a *remote user* literally. Within framework of remote system, - * an {@link User} corresponds to a web-browser and a {@link Client} represents a window in the web-browser. - * - * Extends this {@link User} class and override the {@link createClient} method, a factory method creating a child - * {@link Client} object. I repeat, the {@link User} class represents a *remote user*, groupping {@link Client} - * objects with same *session id*. If your cloud server has some processes to be handled in the **user level**, then - * defines method in this {@link User} class. Methods managing **account** under below are some of them: - * - * - {@link setAccount setAccount()} - * - {@link getAccountID getAccountID()} - * - {@link getAuthority getAuthority()} - * - * The children {@link Client} objects, they're contained with their key, the {@link Client.getNo sequence number}. - * If you {@link User.erase erase} the children {@link Client} object by yourself, then their connection with the - * remote clients will be {@link Client.close closed} and their {@link Client.destructor destruction method} will be - * called. If you remove {@link clear all children}, then this {@link User} object will be also - * {@link destructor destructed} and erased from the parent {@link Server} object. - * - * - * - * - * - * @handbook [Templates - Cloud Service](https://github.com/samchon/framework/wiki/TypeScript-Templates-Cloud_Service) - * @author Jeongho Nam - */ - abstract class User extends collections.HashMapCollection implements protocol.IProtocol { - /** - * @hidden - */ - private server_; - /** - * @hidden - */ - private session_id_; - /** - * @hidden - */ - private sequence_; - /** - * @hidden - */ - private account_id_; - /** - * @hidden - */ - private authority_; - /** - * Construct from its parent {@link Server}. - * - * @param server The parent {@link Server} object. - */ - constructor(server: Server); - /** - * Default Destructor. - * - * This {@link destructor destructor()} method is called when the {@link User} object is destructed. The - * {@link User} object is destructed when connections with the remote clients are all closed, that is all the - * children {@link Client} objects are all removed, and 30 seconds has left. If some remote client connects - * within the 30 seconds, then the {@link User} object doesn't be destructed. - * - * Note that, don't call this {@link destructor destructor()} method by yourself. It must be called automatically - * by those *destruction* cases. Also, if your derived {@link User} class has something to do on the - * *destruction*, then overrides this {@link destructor destructor()} method and defines the something to do. - * Overriding this {@link destructor destructor()}, don't forget to calling ```super.destructor();``` on tail. - * - * ```typescript - * class MyUser extends protocol.service.User - * { - * protected destructor(): void - * { - * // DO SOMETHING - * this.do_something(); - * - * // CALL SUPER.DESTRUCTOR() ON TAIL. DON'T FORGET THIS - * super.destructor(); - * } - * } - * ``` - */ - protected destructor(): void; - /** - * Factory method creating a {@link Client} object. - * - * @param driver A web communicator for remote client. - * @return A newly created {@link Client} object. - */ - protected abstract createClient(driver: protocol.WebClientDriver): Client; - /** - * @hidden - */ - private handle_erase_client(event); - /** - * Get parent {@lin Server} object. - * - * @return Parent {@link Server} object. - */ - getServer(): Server; - /** - * Get account id. - * - * @return Account ID. - */ - getAccountID(): string; - /** - * Get authority. - * - * @return Authority - */ - getAuthority(): number; - /** - * Set *account id* and *authority*. - * - * The {@link setAccount setAccount()} is a method configuring *account id* and *authority* of this {@link User}. - * - * After the configuring, the {@link getAccountID account id} is enrolled into the parent {@link Server} as a - * **key** for this {@link User} object. You can test existence and access this {@link User} object from - * {@link Server.has Server.has()} and {@link Server.get Server.get()} with the {@link getAccountID account id}. - * Of course, if ordinary {@link getAccountID account id} had existed, then the ordinary **key** will be - * replaced. - * - * As you suggest, this {@link setAccount setAccount()} is something like a **log-in** function. If what you want - * is not **logging-in**, but **logging-out**, then configure the *account id* to empty string ``""```` or call - * the {@link lgout logout()} method. - * - * @param id To be account id. - * @param authority To be authority. - */ - setAccount(id: string, authority: number): void; - /** - * Log-out. - * - * This {@link logout logout()} method configures {@link getAccountID account id} to empty string and - * {@link getAuthority authority} to zero. - * - * The ordinary {@link getAccountID account id} will be also erased from the parent {@link Server} object. You - * can't access this {@link User} object from {@link Server.has Server.has()} and {@link Server.get Server.get()} - * with the ordinary {@link getAccountID account id} more. - */ - logout(): void; - /** - * Send an {@link Invoke} message. - * - * Sends an {@link Invoke} message to all remote clients through the belonged {@link Client} objects. Sending the - * {@link Invoke} message to all remote clients, it's came true by passing through the - * {@link Client.sendData Client.sendData()} methods. - * - * ```typescript - * class protocol.service.User - * { - * public sendData(invoke: Invoke): void - * { - * for (let it = this.begin(); !it.equal_to(this.end()); it = it.next()) - * it.second.sendData(invoke); - * } - * } - * ``` - * - * @param invoke {@link Invoke} message to send to all remote clients. - */ - sendData(invoke: protocol.Invoke): void; - /** - * Handle a replied {@link Invoke} message. - * - * The default {@link User.replyData User.replyData()} shifts chain to its parent {@link Server} object, by - * calling the {@link Server.replyData Server.replyData()} method. If there're some {@link Invoke} message to be - * handled in this {@link User} level, then override this method and defines what to do with the {@link Invoke} - * message in this {@link User} level. - * - * ```typescript - * class protocol.service.User - * { - * public replyData(invoke: protocol.Invoke): void - * { - * this.getServer().replyData(invoke); - * } - * } - * - * class MyUser extends protocol.service.User - * { - * public replyData(invoke: protocol.Invoke): void - * { - * if (invoke.apply(this) == false) // IS TARGET TO BE HANDLED IN THIS USER LEVEL - * super.replyData(invoke); // SHIFT TO SERVER - * } - * } - * ``` - * - * @param invoke An {@link Invoke invoke} message to be handled in {@link User} level. - */ - replyData(invoke: protocol.Invoke): void; - } -} -declare namespace samchon.templates.slave { - interface ISlaveClient extends SlaveSystem { - connect(ip: string, port: number): void; - } - abstract class SlaveClient extends SlaveSystem implements ISlaveClient { - /** - * Default Constructor. - */ - constructor(); - /** - * @inheritdoc - */ - protected abstract createServerConnector(): protocol.IServerConnector; - /** - * @inheritdoc - */ - connect(ip: string, port: number): void; - } -} -declare namespace samchon.templates.slave { - interface ISlaveServer extends SlaveSystem, protocol.IServer { - } - abstract class SlaveServer extends SlaveSystem implements ISlaveServer { - private server_base_; - constructor(); - protected abstract createServerBase(): protocol.IServerBase; - open(port: number): void; - close(): void; - addClient(driver: protocol.IClientDriver): void; - } -} +} \ No newline at end of file diff --git a/samchon/index.d.ts b/samchon/index.d.ts new file mode 100644 index 0000000000..6f2bc17b43 --- /dev/null +++ b/samchon/index.d.ts @@ -0,0 +1,8403 @@ +// Type definitions for Samchon Framework v2.0.7 +// Project: https://github.com/samchon/framework +// Definitions by: Jeongho Nam +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "samchon" +{ + export = samchon; +} + +/** + * # Samchon Framework + * + * + * + * + * Samchon, a OON (Object-Oriented Network) framework. + * + * With Samchon Framework, you can implement distributed processing system within framework of OOD like handling S/W + * objects (classes). You can realize cloud and distributed system very easily with provided system templates and even + * integration with C++ is possible. + * + * The goal, ultimate utilization model of Samchon Framework is, building cloud system with NodeJS and taking heavy works + * to C++ distributed systems with provided modules (those are system templates). + * + * @git https://github.com/samchon/framework + * @author Jeongho Nam + */ +declare namespace samchon { +} +declare namespace samchon.collections { + /** + * A {@link Vector} who can detect element I/O events. + * + * Below is the list of methods who are dispatching {@link CollectionEvent}: + * - *insert* typed events: + * - {@link assign} + * - {@link insert} + * - {@link push} + * - {@link push_back} + * - *erase* typed events: + * - {@link assign} + * - {@link clear} + * - {@link erase} + * - {@link pop_back} + * - *refresh* typed events: + * - {@link refresh} + * + * #### [Inherited] {@link Vector} + * @copydoc Vector + */ + class ArrayCollection extends std.Vector implements ICollection { + /** + * @hidden + */ + private event_dispatcher_; + /** + * @inheritdoc + */ + push(...items: T[]): number; + /** + * @inheritdoc + */ + push_back(val: T): void; + /** + * @hidden + */ + protected _Insert_by_range>(position: std.VectorIterator, begin: InputIterator, end: InputIterator): std.VectorIterator; + /** + * @hidden + */ + protected _Erase_by_range(first: std.VectorIterator, last: std.VectorIterator): std.VectorIterator; + /** + * @hidden + */ + private _Notify_insert(first, last); + /** + * @hidden + */ + private _Notify_erase(first, last); + /** + * @inheritdoc + */ + hasEventListener(type: string): boolean; + /** + * @inheritdoc + */ + dispatchEvent(event: library.BasicEvent): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.VectorIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.VectorIterator, last: std.VectorIterator): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener): void; + addEventListener(type: "insert", listener: CollectionEventListener): void; + addEventListener(type: "erase", listener: CollectionEventListener): void; + addEventListener(type: "refresh", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener): void; + removeEventListener(type: "insert", listener: CollectionEventListener): void; + removeEventListener(type: "erase", listener: CollectionEventListener): void; + removeEventListener(type: "refresh", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; + } +} +declare namespace samchon.library { + /** + * A basic event class of Samchon Framework. + * + * @reference https://developer.mozilla.org/en-US/docs/Web/API/Event + * @handbook https://github.com/samchon/framework/wiki/TypeScript-Library-EventDispatcher + * @author Jeongho Nam + */ + class BasicEvent { + protected type_: string; + protected target_: IEventDispatcher; + private currentTarget_; + protected trusted_: boolean; + protected bubbles_: boolean; + protected cancelable_: boolean; + protected defaultPrevented_: boolean; + protected cancelBubble_: boolean; + private timeStamp_; + constructor(type: string, bubbles?: boolean, cancelable?: boolean); + /** + * @inheritdoc + */ + initEvent(type: string, bubbles: boolean, cancelable: boolean): void; + /** + * @inheritdoc + */ + /** + * @inheritdoc + */ + stopImmediatePropagation(): void; + /** + * @inheritdoc + */ + stopPropagation(): void; + /** + * @inheritdoc + */ + readonly type: string; + /** + * @inheritdoc + */ + target: IEventDispatcher; + /** + * @inheritdoc + */ + readonly currentTarget: IEventDispatcher; + /** + * @inheritdoc + */ + readonly bubbles: boolean; + /** + * @inheritdoc + */ + readonly cancelable: boolean; + /** + * @inheritdoc + */ + readonly eventPhase: number; + /** + * @inheritdoc + */ + readonly defaultPrevented: boolean; + /** + * @inheritdoc + */ + readonly srcElement: Element; + /** + * @inheritdoc + */ + readonly cancelBubble: boolean; + /** + * @inheritdoc + */ + readonly timeStamp: number; + /** + * Don't know what it is. + */ + readonly returnValue: boolean; + } +} +declare namespace samchon.collections { + /** + * Type of function pointer for listener of {@link CollectionEvent CollectionEvents}. + */ + type CollectionEventListener = (event: CollectionEvent) => void; +} +declare namespace samchon.collections { + /** + * An event occured in a {@link ICollection collection} object. + * + * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) + * @author Jeongho Nam + */ + class CollectionEvent extends library.BasicEvent { + /** + * @hidden + */ + private first_; + /** + * @hidden + */ + private last_; + /** + * @hidden + */ + private temporary_container_; + /** + * @hidden + */ + private origin_first_; + /** + * Initialization Constructor. + * + * @param type Type of collection event. + * @param first An {@link Iterator} to the initial position in this {@link CollectionEvent}. + * @param last An {@link Iterator} to the final position in this {@link CollectionEvent}. + */ + constructor(type: string, first: std.Iterator, last: std.Iterator); + constructor(type: "insert", first: std.Iterator, last: std.Iterator); + constructor(type: "erase", first: std.Iterator, last: std.Iterator); + constructor(type: "refresh", first: std.Iterator, last: std.Iterator); + /** + * Associative target, the {@link ICollection collection}. + */ + readonly target: ICollection; + /** + * An {@link Iterator} to the initial position in this {@link CollectionEvent}. + */ + readonly first: std.Iterator; + /** + * An {@link Iterator} to the final position in this {@link CollectionEvent}. + */ + readonly last: std.Iterator; + /** + * @inheritdoc + */ + preventDefault(): void; + } +} +declare namespace samchon.collections.CollectionEvent { + const INSERT: "insert"; + const ERASE: "erase"; + const REFRESH: "refresh"; +} +declare namespace samchon.collections { + /** + * A {@link Deque} who can detect element I/O events. + * + * Below is the list of methods who are dispatching {@link CollectionEvent}: + * - *insert* typed events: + * - {@link assign} + * - {@link insert} + * - {@link push} + * - {@link push_front} + * - {@link push_back} + * - *erase* typed events: + * - {@link assign} + * - {@link clear} + * - {@link erase} + * - {@link pop_front} + * - {@link pop_back} + * - *refresh* typed events: + * - {@link refresh} + * + * #### [Inherited] {@link Deque} + * @copydoc Deque + */ + class DequeCollection extends std.Deque implements ICollection { + /** + * @hidden + */ + private event_dispatcher_; + /** + * @inheritdoc + */ + push_front(val: T): void; + /** + * @inheritdoc + */ + push_back(val: T): void; + /** + * @hidden + */ + protected _Insert_by_range>(position: std.DequeIterator, begin: InputIterator, end: InputIterator): std.DequeIterator; + /** + * @inheritdoc + */ + pop_front(): void; + /** + * @inheritdoc + */ + pop_back(): void; + /** + * @hidden + */ + protected _Erase_by_range(first: std.DequeIterator, last: std.DequeIterator): std.DequeIterator; + /** + * @hidden + */ + private _Notify_insert(first, last); + /** + * @hidden + */ + private _Notify_erase(first, last); + /** + * @inheritdoc + */ + hasEventListener(type: string): boolean; + /** + * @inheritdoc + */ + dispatchEvent(event: library.BasicEvent): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.DequeIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.DequeIterator, last: std.DequeIterator): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener): void; + addEventListener(type: "insert", listener: CollectionEventListener): void; + addEventListener(type: "erase", listener: CollectionEventListener): void; + addEventListener(type: "refresh", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener): void; + removeEventListener(type: "insert", listener: CollectionEventListener): void; + removeEventListener(type: "erase", listener: CollectionEventListener): void; + removeEventListener(type: "refresh", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; + } +} +declare namespace samchon.collections { + /** + * A {@link HashMap} who can detect element I/O events. + * + * Below is the list of methods who are dispatching {@link MapCollectionEvent}: + * - *insert* typed events: + * - {@link assign} + * - {@link insert} + * - {@link insert_or_assign} + * - {@link emplace} + * - {@link set} + * - {@link push} + * - *erase* typed events: + * - {@link assign} + * - {@link clear} + * - {@link erase} + * - {@link extract} + * - *refresh* typed events: + * - {@link refresh} + * + * #### [Inherited] {@link HashMap} + * @copydoc HashMap + */ + class HashMapCollection extends std.HashMap implements ICollection> { + /** + * @hidden + */ + private event_dispatcher_; + /** + * @hidden + */ + protected _Handle_insert(first: std.MapIterator, last: std.MapIterator): void; + /** + * @hidden + */ + protected _Handle_erase(first: std.MapIterator, last: std.MapIterator): void; + /** + * @inheritdoc + */ + hasEventListener(type: string): boolean; + /** + * @inheritdoc + */ + dispatchEvent(event: library.BasicEvent): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.MapIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.MapIterator, last: std.MapIterator): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener): void; + addEventListener(type: "insert", listener: MapCollectionEventListener): void; + addEventListener(type: "erase", listener: MapCollectionEventListener): void; + addEventListener(type: "refresh", listener: MapCollectionEventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; + addEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; + addEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener): void; + removeEventListener(type: "insert", listener: MapCollectionEventListener): void; + removeEventListener(type: "erase", listener: MapCollectionEventListener): void; + removeEventListener(type: "refresh", listener: MapCollectionEventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; + removeEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; + removeEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; + } +} +declare namespace samchon.collections { + /** + * A {@link HashMultiMap} who can detect element I/O events. + * + * Below is the list of methods who are dispatching {@link MapCollectionEvent}: + * - *insert* typed events: + * - {@link assign} + * - {@link insert} + * - {@link emplace} + * - {@link push} + * - *erase* typed events: + * - {@link assign} + * - {@link clear} + * - {@link erase} + * - *refresh* typed events: + * - {@link refresh} + * + * #### [Inherited] {@link HashMultiMap} + * @copydoc HashMultiMap + */ + class HashMultiMapCollection extends std.HashMultiMap implements ICollection> { + /** + * @hidden + */ + private event_dispatcher_; + /** + * @hidden + */ + protected _Handle_insert(first: std.MapIterator, last: std.MapIterator): void; + /** + * @hidden + */ + protected _Handle_erase(first: std.MapIterator, last: std.MapIterator): void; + /** + * @inheritdoc + */ + hasEventListener(type: string): boolean; + /** + * @inheritdoc + */ + dispatchEvent(event: library.BasicEvent): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.MapIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.MapIterator, last: std.MapIterator): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener): void; + addEventListener(type: "insert", listener: MapCollectionEventListener): void; + addEventListener(type: "erase", listener: MapCollectionEventListener): void; + addEventListener(type: "refresh", listener: MapCollectionEventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; + addEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; + addEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener): void; + removeEventListener(type: "insert", listener: MapCollectionEventListener): void; + removeEventListener(type: "erase", listener: MapCollectionEventListener): void; + removeEventListener(type: "refresh", listener: MapCollectionEventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; + removeEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; + removeEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; + } +} +declare namespace samchon.collections { + /** + * A {@link HashMultiSet} who can detect element I/O events. + * + * Below is the list of methods who are dispatching {@link CollectionEvent}: + * - *insert* typed events: + * - {@link assign} + * - {@link insert} + * - {@link push} + * - *erase* typed events: + * - {@link assign} + * - {@link clear} + * - {@link erase} + * - *refresh* typed events: + * - {@link refresh} + * + * #### [Inherited] {@link HashMultiSet} + * @copydoc HashMultiSet + */ + class HashMultiSetCollection extends std.HashMultiSet implements ICollection { + /** + * @hidden + */ + private event_dispatcher_; + /** + * @hidden + */ + protected _Handle_insert(first: std.SetIterator, last: std.SetIterator): void; + /** + * @hidden + */ + protected _Handle_erase(first: std.SetIterator, last: std.SetIterator): void; + /** + * @inheritdoc + */ + hasEventListener(type: string): boolean; + /** + * @inheritdoc + */ + dispatchEvent(event: library.BasicEvent): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.SetIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.SetIterator, last: std.SetIterator): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener): void; + addEventListener(type: "insert", listener: CollectionEventListener): void; + addEventListener(type: "erase", listener: CollectionEventListener): void; + addEventListener(type: "refresh", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener): void; + removeEventListener(type: "insert", listener: CollectionEventListener): void; + removeEventListener(type: "erase", listener: CollectionEventListener): void; + removeEventListener(type: "refresh", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; + } +} +declare namespace samchon.collections { + /** + * A {@link HashSet} who can detect element I/O events. + * + * Below is the list of methods who are dispatching {@link CollectionEvent}: + * - *insert* typed events: + * - {@link assign} + * - {@link insert} + * - {@link push} + * - {@link insert_or_assign} + * - *erase* typed events: + * - {@link assign} + * - {@link clear} + * - {@link erase} + * - {@link extract} + * - *refresh* typed events: + * - {@link refresh} + * + * #### [Inherited] {@link HashSet} + * @copydoc HashSet + */ + class HashSetCollection extends std.HashSet implements ICollection { + /** + * @hidden + */ + private event_dispatcher_; + /** + * @hidden + */ + protected _Handle_insert(first: std.SetIterator, last: std.SetIterator): void; + /** + * @hidden + */ + protected _Handle_erase(first: std.SetIterator, last: std.SetIterator): void; + /** + * @inheritdoc + */ + hasEventListener(type: string): boolean; + /** + * @inheritdoc + */ + dispatchEvent(event: library.BasicEvent): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.SetIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.SetIterator, last: std.SetIterator): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener): void; + addEventListener(type: "insert", listener: CollectionEventListener): void; + addEventListener(type: "erase", listener: CollectionEventListener): void; + addEventListener(type: "refresh", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener): void; + removeEventListener(type: "insert", listener: CollectionEventListener): void; + removeEventListener(type: "erase", listener: CollectionEventListener): void; + removeEventListener(type: "refresh", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; + } +} +/** + * Collections, elements I/O detectable STL containers. + * + * STL Containers | Collections + * ---------------------|------------------- + * {@link Vector} | {@link ArrayCollection} + * {@link List} | {@link ListCollection} + * {@link Deque} | {@link DequeCollection} + * | + * {@link TreeSet} | {@link TreeSetCollection} + * {@link HashSet} | {@link HashSetCollection} + * {@link TreeMultiSet} | {@link TreeMultiSetCollection} + * {@link HashMultiSet} | {@link HashMultiSetCollection} + * | + * {@link TreeMap} | {@link TreeMapCollection} + * {@link HashMap} | {@link HashMapCollection} + * {@link TreeMultiMap} | {@link TreeMultiMapCollection} + * {@link HashMultiMap} | {@link HashMultiMapCollection} + * + * @author Jeongho Nam + */ +declare namespace samchon.collections { + /** + * An interface for {@link IContainer containers} who can detect element I/O events. + * + * Below are list of methods who are dispatching {@link CollectionEvent}: + * - *insert* typed events: + * - {@link assign} + * - {@link insert} + * - {@link push} + * - *erase* typed events: + * - {@link assign} + * - {@link clear} + * - {@link erase} + * - *refresh* typed events: + * - {@link refresh} + * + * @author Jeongho Nam + */ + interface ICollection extends std.base.Container, library.IEventDispatcher { + /** + * Dispatch a {@link CollectionEvent} with *refresh* typed. + * + * {@link ICollection} dispatches {@link CollectionEvent} typed *insert* or *erase* whenever elements I/O has + * occured. However, unlike those elements I/O events, content change in element level can't be detected. + * There's no way to detect those events automatically by {@link IContainer}. + * + * If you want to dispatch those typed events (notifying change on contents in element level), you've to + * dispatch *refresh* typed event manually, by yourself. Call {@link refresh refresh()} with specified + * iterators who're pointing the elements whose content have changed. Then a {@link CollectionEvent} with + * *refresh* typed will be dispatched. + * + * If you don't specify any iterator, then the range of the *refresh* event will be all elements in this + * {@link ICollection collection}; {@link begin begin()} to {@link end end()}. + */ + refresh(): void; + /** + * Dispatch a {@link CollectionEvent} with *refresh* typed. + * + * {@link ICollection} dispatches {@link CollectionEvent} typed *insert* or *erase* whenever elements I/O has + * occured. However, unlike those elements I/O events, content change in element level can't be detected. + * There's no way to detect those events automatically by {@link IContainer}. + * + * If you want to dispatch those typed events (notifying change on contents in element level), you've to + * dispatch *refresh* typed event manually, by yourself. Call {@link refresh refresh()} with specified + * iterators who're pointing the elements whose content have changed. Then a {@link CollectionEvent} with + * *refresh* typed will be dispatched. + * + * @param it An iterator targeting the content changed element. + */ + refresh(it: std.Iterator): void; + /** + * Dispatch a {@link CollectionEvent} with *refresh* typed. + * + * {@link ICollection} dispatches {@link CollectionEvent} typed *insert* or *erase* whenever elements I/O has + * occured. However, unlike those elements I/O events, content change in element level can't be detected. + * There's no way to detect those events automatically by {@link IContainer}. + * + * If you want to dispatch those typed events (notifying change on contents in element level), you've to + * dispatch *refresh* typed event manually, by yourself. Call {@link refresh refresh()} with specified + * iterators who're pointing the elements whose content have changed. Then a {@link CollectionEvent} with + * *refresh* typed will be dispatched. + * + * @param first An Iterator to the initial position in a sequence of the content changed elmeents. + * @param last An {@link Iterator} to the final position in a sequence of the content changed elements. The range + * used is [*first*, *last*), which contains all the elements between *first* and + * *last*, including the element pointed by *first* but not the element pointed by + * *last*. + */ + refresh(first: std.Iterator, last: std.Iterator): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener): void; + addEventListener(type: "insert", listener: CollectionEventListener): void; + addEventListener(type: "erase", listener: CollectionEventListener): void; + addEventListener(type: "refresh", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener): void; + removeEventListener(type: "insert", listener: CollectionEventListener): void; + removeEventListener(type: "erase", listener: CollectionEventListener): void; + removeEventListener(type: "refresh", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; + } + /** + * @hidden + */ + namespace ICollection { + /** + * @hidden + */ + function _Dispatch_CollectionEvent(collection: ICollection, type: string, first: std.Iterator, last: std.Iterator): void; + /** + * @hidden + */ + function _Dispatch_MapCollectionEvent(collection: ICollection>, type: string, first: std.MapIterator, last: std.MapIterator): void; + } +} +declare namespace samchon.collections { + /** + * A {@link List} who can detect element I/O events. + * + * Below is the list of methods who are dispatching {@link CollectionEvent}: + * - *insert* typed events: + * - {@link assign} + * - {@link insert} + * - {@link push} + * - {@link push_front} + * - {@link push_back} + * - {@link merge} + * - *erase* typed events: + * - {@link assign} + * - {@link clear} + * - {@link erase} + * - {@link pop_front} + * - {@link pop_back} + * - {@link unique} + * - {@link remove} + * - {@link remove_if} + * - {@link splice} + * - *refresh* typed events: + * - {@link refresh} + * - {@link sort} + * + * #### [Inherited] {@link List} + * @copydoc List + */ + class ListCollection extends std.List implements ICollection { + /** + * @hidden + */ + private event_dispatcher_; + /** + * @hidden + */ + protected _Insert_by_range>(position: std.ListIterator, begin: InputIterator, end: InputIterator): std.ListIterator; + /** + * @hidden + */ + protected _Erase_by_range(first: std.ListIterator, last: std.ListIterator): std.ListIterator; + /** + * @hidden + */ + private _Notify_insert(first, last); + /** + * @hidden + */ + private _Notify_erase(first, last); + /** + * @inheritdoc + */ + hasEventListener(type: string): boolean; + /** + * @inheritdoc + */ + dispatchEvent(event: library.BasicEvent): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.ListIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.ListIterator, last: std.ListIterator): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener): void; + addEventListener(type: "insert", listener: CollectionEventListener): void; + addEventListener(type: "erase", listener: CollectionEventListener): void; + addEventListener(type: "refresh", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener): void; + removeEventListener(type: "insert", listener: CollectionEventListener): void; + removeEventListener(type: "erase", listener: CollectionEventListener): void; + removeEventListener(type: "refresh", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; + } +} +declare namespace samchon.collections { + type MapCollectionEventListener = (event: MapCollectionEvent) => void; + /** + * An event occured in a {@link MapContainer map container} object. + * + * @handbook [Collections](https://github.com/samchon/framework/wiki/TypeScript-STL#collections) + * @author Jeongho Nam + */ + class MapCollectionEvent extends CollectionEvent> { + /** + * @inheritdoc + */ + readonly first: std.MapIterator; + /** + * @inheritdoc + */ + readonly last: std.MapIterator; + } +} +declare namespace samchon.collections { + /** + * A {@link TreeMap} who can detect element I/O events. + * + * Below is the list of methods who are dispatching {@link MapCollectionEvent}: + * - *insert* typed events: + * - {@link assign} + * - {@link insert} + * - {@link insert_or_assign} + * - {@link emplace} + * - {@link set} + * - {@link push} + * - *erase* typed events: + * - {@link assign} + * - {@link clear} + * - {@link erase} + * - {@link extract} + * - *refresh* typed events: + * - {@link refresh} + * + * #### [Inherited] {@link TreeMap} + * @copydoc TreeMap + */ + class TreeMapCollection extends std.TreeMap implements ICollection> { + /** + * @hidden + */ + private event_dispatcher_; + /** + * @hidden + */ + protected _Handle_insert(first: std.MapIterator, last: std.MapIterator): void; + /** + * @hidden + */ + protected _Handle_erase(first: std.MapIterator, last: std.MapIterator): void; + /** + * @inheritdoc + */ + hasEventListener(type: string): boolean; + /** + * @inheritdoc + */ + dispatchEvent(event: library.BasicEvent): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.MapIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.MapIterator, last: std.MapIterator): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener): void; + addEventListener(type: "insert", listener: MapCollectionEventListener): void; + addEventListener(type: "erase", listener: MapCollectionEventListener): void; + addEventListener(type: "refresh", listener: MapCollectionEventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; + addEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; + addEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener): void; + removeEventListener(type: "insert", listener: MapCollectionEventListener): void; + removeEventListener(type: "erase", listener: MapCollectionEventListener): void; + removeEventListener(type: "refresh", listener: MapCollectionEventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; + removeEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; + removeEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; + } +} +declare namespace samchon.collections { + /** + * A {@link TreeMultiMap} who can detect element I/O events. + * + * Below is the list of methods who are dispatching {@link MapCollectionEvent}: + * - *insert* typed events: + * - {@link assign} + * - {@link insert} + * - {@link emplace} + * - {@link push} + * - *erase* typed events: + * - {@link assign} + * - {@link clear} + * - {@link erase} + * - *refresh* typed events: + * - {@link refresh} + * + * #### [Inherited] {@link TreeMultiMap} + * @copydoc TreeMultiMap + */ + class TreeMultiMapCollection extends std.TreeMultiMap implements ICollection> { + /** + * @hidden + */ + private event_dispatcher_; + /** + * @hidden + */ + protected _Handle_insert(first: std.MapIterator, last: std.MapIterator): void; + /** + * @hidden + */ + protected _Handle_erase(first: std.MapIterator, last: std.MapIterator): void; + /** + * @inheritdoc + */ + hasEventListener(type: string): boolean; + /** + * @inheritdoc + */ + dispatchEvent(event: library.BasicEvent): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.MapIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.MapIterator, last: std.MapIterator): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener): void; + addEventListener(type: "insert", listener: MapCollectionEventListener): void; + addEventListener(type: "erase", listener: MapCollectionEventListener): void; + addEventListener(type: "refresh", listener: MapCollectionEventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; + addEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; + addEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener): void; + removeEventListener(type: "insert", listener: MapCollectionEventListener): void; + removeEventListener(type: "erase", listener: MapCollectionEventListener): void; + removeEventListener(type: "refresh", listener: MapCollectionEventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; + removeEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; + removeEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; + } +} +declare namespace samchon.collections { + /** + * A {@link TreeMultiSet} who can detect element I/O events. + * + * Below is the list of methods who are dispatching {@link CollectionEvent}: + * - *insert* typed events: + * - {@link assign} + * - {@link insert} + * - {@link push} + * - *erase* typed events: + * - {@link assign} + * - {@link clear} + * - {@link erase} + * - *refresh* typed events: + * - {@link refresh} + * + * #### [Inherited] {@link TreeMultiSet} + * @copydoc TreeMultiSet + */ + class TreeMultiSetCollection extends std.TreeMultiSet implements ICollection { + /** + * @hidden + */ + private event_dispatcher_; + /** + * @hidden + */ + protected _Handle_insert(first: std.SetIterator, last: std.SetIterator): void; + /** + * @hidden + */ + protected _Handle_erase(first: std.SetIterator, last: std.SetIterator): void; + /** + * @inheritdoc + */ + hasEventListener(type: string): boolean; + /** + * @inheritdoc + */ + dispatchEvent(event: library.BasicEvent): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.SetIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.SetIterator, last: std.SetIterator): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener): void; + addEventListener(type: "insert", listener: CollectionEventListener): void; + addEventListener(type: "erase", listener: CollectionEventListener): void; + addEventListener(type: "refresh", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener): void; + removeEventListener(type: "insert", listener: CollectionEventListener): void; + removeEventListener(type: "erase", listener: CollectionEventListener): void; + removeEventListener(type: "refresh", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; + } +} +declare namespace samchon.collections { + /** + * A {@link TreeMap} who can detect element I/O events. + * + * Below is the list of methods who are dispatching {@link CollectionEvent}: + * - *insert* typed events: + * - {@link assign} + * - {@link insert} + * - {@link insert_or_assign} + * - {@link push} + * - *erase* typed events: + * - {@link assign} + * - {@link clear}7 + * - {@link erase} + * - {@link extract} + * - *refresh* typed events: + * - {@link refresh} + * + * #### [Inherited] {@link TreeSet} + * @copydoc TreeSet + */ + class TreeSetCollection extends std.TreeSet implements ICollection { + /** + * @hidden + */ + private event_dispatcher_; + /** + * @hidden + */ + protected _Handle_insert(first: std.SetIterator, last: std.SetIterator): void; + /** + * @hidden + */ + protected _Handle_erase(first: std.SetIterator, last: std.SetIterator): void; + /** + * @inheritdoc + */ + hasEventListener(type: string): boolean; + /** + * @inheritdoc + */ + dispatchEvent(event: library.BasicEvent): boolean; + /** + * @inheritdoc + */ + refresh(): void; + /** + * @inheritdoc + */ + refresh(it: std.SetIterator): void; + /** + * @inheritdoc + */ + refresh(first: std.SetIterator, last: std.SetIterator): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener): void; + addEventListener(type: "insert", listener: CollectionEventListener): void; + addEventListener(type: "erase", listener: CollectionEventListener): void; + addEventListener(type: "refresh", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener): void; + removeEventListener(type: "insert", listener: CollectionEventListener): void; + removeEventListener(type: "erase", listener: CollectionEventListener): void; + removeEventListener(type: "refresh", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; + removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; + } +} +declare namespace samchon.library { + /** + * Case generator. + * + * {@link CaseGenerator} is an abstract case generator being used like a matrix. + *
    + *
  • n��r(n^r) -> {@link CombinedPermutationGenerator}
  • + *
  • nPr -> {@link PermutationGenerator}
  • + *
  • n! -> {@link FactorialGenerator}
  • + *
+ * + * @author Jeongho Nam + */ + abstract class CaseGenerator { + /** + * Size, the number of all cases. + */ + protected size_: number; + /** + * N, size of the candidates. + */ + protected n_: number; + /** + * R, size of elements of each case. + */ + protected r_: number; + /** + * Construct from size of N and R. + * + * @param n Size of candidates. + * @param r Size of elements of each case. + */ + constructor(n: number, r: number); + /** + * Get size of all cases. + * + * @return Get a number of the all cases. + */ + size(): number; + /** + * Get size of the N. + */ + n(): number; + /** + * Get size of the R. + */ + r(): number; + /** + * Get index'th case. + * + * @param index Index number + * @return The row of the index'th in combined permuation case + */ + abstract at(index: number): number[]; + } + /** + * A combined-permutation case generator. + * + * n��r + * + * @author Jeongho Nam + */ + class CombinedPermutationGenerator extends CaseGenerator { + /** + * An array using for dividing each element index. + */ + private divider_array; + /** + * Construct from size of N and R. + * + * @param n Size of candidates. + * @param r Size of elements of each case. + */ + constructor(n: number, r: number); + at(index: number): number[]; + } + /** + * A permutation case generator. + * + * nPr + * + * @author Jeongho Nam + */ + class PermuationGenerator extends CaseGenerator { + /** + * Construct from size of N and R. + * + * @param n Size of candidates. + * @param r Size of elements of each case. + */ + constructor(n: number, r: number); + /** + * @inheritdoc + */ + at(index: number): number[]; + } + /** + * Factorial case generator. + * + * n! = nPn + * + * @author Jeongho Nam + */ + class FactorialGenerator extends PermuationGenerator { + /** + * Construct from factorial size N. + * + * @param n Factoria size N. + */ + constructor(n: number); + } +} +declare namespace samchon.library { + type BasicEventListener = (event: BasicEvent) => void; + /** + * The IEventDispatcher interface defines methods for adding or removing event listeners, checks whether specific + * types of event listeners are registered, and dispatches events. + * + * The event target serves as the local point for how events flow through the display list hierarchy. When an + * event such as a mouse click or a key press occurs, an event object is dispatched into the event flow from the + * root of the display list. The event object makes a round-trip journey to the event target, which is + * conceptually divided into three phases: the capture phase includes the journey from the root to the last node + * before the event target's node; the target phase includes only the event target node; and the bubbling phase + * includes any subsequent nodes encountered on the return trip to the root of the display list. + * + * In general, the easiest way for a user-defined class to gain event dispatching capabilities is to extend + * {@link EventDispatcher}. If this is impossible (that is, if the class is already extending another class), you + * can instead implement the {@link IEventDispatcher} interface, create an {@link EventDispatcher} member, and + * write simple hooks to route calls into the aggregated {@link EventDispatcher}. + * + * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/events/IEventDispatcher.html + * @handbook https://github.com/samchon/framework/wiki/TypeScript-Library-EventDispatcher + * @author Migrated by Jeongho Nam + */ + interface IEventDispatcher { + /** + * Checks whether the {@link EventDispatcher} object has any listeners registered for a specific type of event. + * This allows you to determine where an {@link EventDispatcher} object has altered handling of an event type + * in the event flow hierarchy. To determine whether a specific event type actually triggers an event listener, + * use {@link willTrigger willTrigger()}. + * + * The difference between {@link hasEventListener hasEventListener()} and {@link willTrigger willTrigger()} is + * that {@link hasEventListener} examines only the object to which it belongs, whereas {@link willTrigger} + * examines the entire event flow for the event specified by the type parameter. + * + * @param type The type of event. + */ + hasEventListener(type: string): boolean; + /** + * Dispatches an event into the event flow. + * + * The event target is the {@link EventDispatcher} object upon which the {@link dispatchEvent dispatchEvent()} + * method is called. + * + * @param event The {@link BasicEvent} object that is dispatched into the event flow. If the event is being + * redispatched, a clone of the event is created automatically. After an event is dispatched, its + * target property cannot be changed, so you must create a new copy + * of the event for redispatching to work. + */ + dispatchEvent(event: library.BasicEvent): boolean; + /** + * Registers an event listener object with an {@link EventDispatcher} object so that the listener receives + * notification of an event. You can register event listeners on all nodes in the display list for a specific + * type of event, phase, and priority. + * + * After you successfully register an event listener, you cannot change its priority through additional calls + * to {@link addEventListener addEventListener()|} To change a listener's priority, you must first call + * {@link removeEventListener removeEventListener()}. Then you can register the listener again with the new + * priority level. + * + * Keep in mind that after the listener is registered, subsequent calls to {@link addEventListener} with a + * different type or useCapture value result in the creation of a separate listener registration. For example, + * if you first register a listener with useCapture set to true, it listens only during the capture phase. If + * you call {@link addEventListener} again using the same listener object, but with useCapture set to false, + * you have two separate listeners: one that listens during the capture phase and another that listens during + * the target and bubbling phases. + * + * You cannot register an event listener for only the target phase or the bubbling phase. Those phases are + * coupled during registration because bubbling applies only to the ancestors of the target node. + * + * If you no longer need an event listener, remove it by calling {@link removeEventListener}, or memory + * problems could result. Event listeners are not automatically removed from memory because the garbage + * collector does not remove the listener as long as the dispatching object exists (unless the + * useWeakReference parameter is set to true). + * + * Copying an {@link EventDispatcher} instance does not copy the event listeners attached to it. (If your n + * ewly created node needs an event listener, you must attach the listener after creating the node.) However, + * if you move an {@link EventDispatcher} instance, the event listeners attached to it move along with it. + * + * If the event listener is being registered on a node while an event is also being processed on this node, + * the event listener is not triggered during the current phase but may be triggered during a later phase in + * the event flow, such as the bubbling phase. + * + * If an event listener is removed from a node while an event is being processed on the node, it is still + * triggered by the current actions. After it is removed, the event listener is never invoked again (unless it + * is registered again for future processing). + * + * @param event The type of event. + * @param listener The listener function that processes the event. + * This function must accept an Event object as its only parameter and must return + * nothing. + */ + addEventListener(type: string, listener: library.BasicEventListener): void; + /** + * Registers an event listener object with an {@link EventDispatcher} object so that the listener receives + * notification of an event. You can register event listeners on all nodes in the display list for a specific + * type of event, phase, and priority. + * + * After you successfully register an event listener, you cannot change its priority through additional calls + * to {@link addEventListener addEventListener()|} To change a listener's priority, you must first call + * {@link removeEventListener removeEventListener()}. Then you can register the listener again with the new + * priority level. + * + * Keep in mind that after the listener is registered, subsequent calls to {@link addEventListener} with a + * different type or useCapture value result in the creation of a separate listener registration. For example, + * if you first register a listener with useCapture set to true, it listens only during the capture phase. If + * you call {@link addEventListener} again using the same listener object, but with useCapture set to false, + * you have two separate listeners: one that listens during the capture phase and another that listens during + * the target and bubbling phases. + * + * You cannot register an event listener for only the target phase or the bubbling phase. Those phases are + * coupled during registration because bubbling applies only to the ancestors of the target node. + * + * If you no longer need an event listener, remove it by calling {@link removeEventListener}, or memory + * problems could result. Event listeners are not automatically removed from memory because the garbage + * collector does not remove the listener as long as the dispatching object exists (unless the + * useWeakReference parameter is set to true). + * + * Copying an {@link EventDispatcher} instance does not copy the event listeners attached to it. (If your n + * ewly created node needs an event listener, you must attach the listener after creating the node.) However, + * if you move an {@link EventDispatcher} instance, the event listeners attached to it move along with it. + * + * If the event listener is being registered on a node while an event is also being processed on this node, + * the event listener is not triggered during the current phase but may be triggered during a later phase in + * the event flow, such as the bubbling phase. + * + * If an event listener is removed from a node while an event is being processed on the node, it is still + * triggered by the current actions. After it is removed, the event listener is never invoked again (unless it + * is registered again for future processing). + * + * @param event The type of event. + * @param listener The listener function that processes the event. + * This function must accept an Event object as its only parameter and must return + * nothing. + * @param thisArg The object to be used as the **this** object. + */ + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + /** + * Removes a listener from the {@link EventDispatcher} object. If there is no matching listener registered + * with the {@link EventDispatcher} object, a call to this method has no effect. + * + * @param type The type of event. + * @param listener The listener object to remove. + */ + removeEventListener(type: string, listener: library.BasicEventListener): void; + /** + * Removes a listener from the {@link EventDispatcher} object. If there is no matching listener registered + * with the {@link EventDispatcher} object, a call to this method has no effect. + * + * @param type The type of event. + * @param listener The listener object to remove. + * @param thisArg The object to be used as the **this** object. + */ + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + } + /** + * The {@link EventDispatcher} class is the base class for all classes that dispatch events. The + * {@link EventDispatcher} class implements the {@link IEventDispatcher} interface and is the base class for the + * {@link DisplayObject} class. The {@link EventDispatcher} class allows any object on the display list to be an + * event target and as such, to use the methods of the {@link IEventDispatcher} interface. + * + * The event target serves as the local point for how events flow through the display list hierarchy. When an + * event such as a mouse click or a key press occurs, an event object is dispatched into the event flow from the + * root of the display list. The event object makes a round-trip journey to the event target, which is + * conceptually divided into three phases: the capture phase includes the journey from the root to the last node + * before the event target's node; the target phase includes only the event target node; and the bubbling phase + * includes any subsequent nodes encountered on the return trip to the root of the display list. + * + * In general, the easiest way for a user-defined class to gain event dispatching capabilities is to extend + * {@link EventDispatcher}. If this is impossible (that is, if the class is already extending another class), you + * can instead implement the {@link IEventDispatcher} interface, create an {@link EventDispatcher} member, and + * write simple hooks to route calls into the aggregated {@link EventDispatcher}. + * + * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/events/EventDispatcher.html + * @author Migrated by Jeongho Nam + */ + class EventDispatcher implements IEventDispatcher { + /** + * @hidden + */ + private event_dispatcher_; + /** + * @hidden + */ + private event_listeners_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from the origin event dispatcher. + * + * @param dispatcher The origin object who issuing events. + */ + constructor(dispatcher: IEventDispatcher); + /** + * @inheritdoc + */ + hasEventListener(type: string): boolean; + /** + * @inheritdoc + */ + dispatchEvent(event: library.BasicEvent): boolean; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + } +} +declare namespace samchon.library { + /** + * The {@link FileReference} class provides a means to load and save files in browser level. + * + * The {@link FileReference} class provides a means to {@link load} and {@link save} files in browser level. A + * browser-system dialog box prompts the user to select a file to {@link load} or a location for {@link svae}. Each + * {@link FileReference} object refers to a single file on the user's disk and has properties that contain + * information about the file's size, type, name, creation date, modification date, and creator type (Macintosh only). + * + * + * FileReference instances are created in the following ways: + *
    + *
  • + * When you use the new operator with the {@link FileReference} constructor: + * let myFileReference: FileReference = new FileReference(); + *
  • + *
  • + * When you call the {@link FileReferenceList.browse} method, which creates an array of {@link FileReference} + * objects. + *
  • + *
+ * + * During a load operation, all the properties of a {@link FileReference} object are populated by calls to the + * {@link FileReference.browse} or {@link FileReferenceList.browse} methods. During a save operation, the name + * property is populated when the select event is dispatched; all other properties are populated when the complete + * event is dispatched. + * + * The {@link browse browse()} method opens an browser-system dialog box that prompts the user to select a file + * for {@link load}. The {@link FileReference.browse} method lets the user select a single file; the + * {@link FileReferenceList.browse} method lets the user select multiple files. After a successful call to the + * {@link browse browse()} method, call the {@link FileReference.load} method to load one file at a time. The + * {@link FileReference.save} method prompts the user for a location to save the file and initiates downloading from + * a binary or string data. + * + * The {@link FileReference} and {@link FileReferenceList} classes do not let you set the default file location + * for the dialog box that the {@link browse} or {@link save} methods generate. The default location shown in the + * dialog box is the most recently browsed folder, if that location can be determined, or the desktop. The classes do + * not allow you to read from or write to the transferred file. They do not allow the browser that initiated the + * {@link load} or {@link save} to access the loaded or saved file or the file's location on the user's disk. + * + * @references http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/FileReference.html + * @author Jeongho Nam + */ + class FileReference extends EventDispatcher { + /** + * @hidden + */ + private file_; + /** + * @hidden + */ + private data_; + /** + * Default Constructor. + */ + constructor(); + /** + * The data from the loaded file after a successful call to the {@link load load()} method. + * + * If the {@link FileReference} object was not populated (by a valid call to {@link FileReference.browse}), + * an {@link LogicError exception} will be thrown when you try to get the value of this property. + * + * All the properties of a {@link FileReference} object are populated by calling the {@link browse browse()}. + * + */ + readonly data: any; + /** + * The name of the file on the local disk. + * + * If the {@link FileReference} object was not populated (by a valid call to {@link FileReference.browse}), + * an {@link LogicError exception} will be thrown when you try to get the value of this property. + * + * All the properties of a {@link FileReference} object are populated by calling the {@link browse browse()}. + * + */ + readonly name: string; + /** + * The filename extension. + * + * A file's extension is the part of the name following (and not including) the final dot ("."). If + * there is no dot in the filename, the extension is null. + * + * If the {@link FileReference} object was not populated (by a valid call to {@link FileReference.browse}), + * an {@link LogicError exception} will be thrown when you try to get the value of this property. + * + * All the properties of a {@link FileReference} object are populated by calling the {@link browse browse()}. + * + */ + readonly extension: string; + /** + * The file type, metadata of the {@link extension}. + * + * If the {@link FileReference} object was not populated (by a valid call to {@link FileReference.browse}), + * an {@link LogicError exception} will be thrown when you try to get the value of this property. + * + * All the properties of a {@link FileReference} object are populated by calling the {@link browse browse()}. + * + */ + readonly type: string; + /** + * The size of the file on the local disk in bytes. + * + * If the {@link FileReference} object was not populated (by a valid call to {@link FileReference.browse}), + * an {@link LogicError exception} will be thrown when you try to get the value of this property. + * + * All the properties of a {@link FileReference} object are populated by calling the {@link browse browse()}. + * + */ + readonly size: number; + /** + * The date that the file on the local disk was last modified. + * + * If the {@link FileReference} object was not populated (by a valid call to {@link FileReference.browse}), + * an {@link LogicError exception} will be thrown when you try to get the value of this property. + * + * All the properties of a {@link FileReference} object are populated by calling the {@link browse browse()}. + * + */ + readonly modificationDate: Date; + /** + * Displays a file-browsing dialog box that lets the user select a file to upload. The dialog box is native + * to the user's browser system. The user can select a file on the local computer or from other systems, for + * example, through a UNC path on Windows. + * + * When you call this method and the user successfully selects a file, the properties of this + * {@link FileReference} object are populated with the properties of that file. Each subsequent time that the + * {@link FileReference.browse} method is called, the {@link FileReference} object's properties are reset to + * the file that the user selects in the dialog box. Only one {@link browse browse()} can be performed at a time + * (because only one dialog box can be invoked at a time). + * + * Using the *typeFilter parameter*, you can determine which files the dialog box displays. + * + * @param typeFilter An array of filter strings used to filter the files that are displayed in the dialog box. + * If you omit this parameter, all files are displayed. + */ + browse(...typeFilter: string[]): void; + /** + * Starts the load of a local file selected by a user. + * + * You must call the {@link FileReference.browse} or {@link FileReferenceList.browse} method before you call + * the {@link load load()} method. + * + * Listeners receive events to indicate the progress, success, or failure of the load. Although you can use + * the {@link FileReferenceList} object to let users select multiple files to load, you must {@link load} the + * {@link FileReferenceList files} one by one. To {@link load} the files one by one, iterate through the + * {@link FileReferenceList.fileList} array of {@link FileReference} objects. + * + * If the file finishes loading successfully, its contents are stored in the {@link data} property. + */ + load(): void; + /** + * Save a file to local filesystem. + * + * {@link FileReference.save} implemented the save function by downloading a file from a hidden anchor tag. + * However, the plan, future's {@link FileReference} will follow such rule: + * + * Opens a dialog box that lets the user save a file to the local filesystem. + * + * The {@link save save()} method first opens an browser-system dialog box that asks the user to enter a + * filename and select a location on the local computer to save the file. When the user selects a location and + * confirms the save operation (for example, by clicking Save), the save process begins. Listeners receive events + * to indicate the progress, success, or failure of the save operation. To ascertain the status of the dialog box + * and the save operation after calling {@link save save()}, your code must listen for events such as cancel, + * open, progress, and complete. + * + * When the file is saved successfully, the properties of the {@link FileReference} object are populated with + * the properties of the local file. The complete event is dispatched if the save is successful. + * + * Only one {@link browse browse()} or {@link save()} session can be performed at a time (because only one + * dialog box can be invoked at a time). + * + * @param data The data to be saved. The data can be in one of several formats, and will be treated appropriately. + * @param fileName File name to be saved. + */ + save(data: string, fileName: string): void; + /** + * Save a file to local filesystem. + * + * {@link FileReference.save} implemented the save function by downloading a file from a hidden anchor tag. + * However, the plan, future's {@link FileReference} will follow such rule: + * + * Opens a dialog box that lets the user save a file to the local filesystem. + * + * The {@link save save()} method first opens an browser-system dialog box that asks the user to enter a + * filename and select a location on the local computer to save the file. When the user selects a location and + * confirms the save operation (for example, by clicking Save), the save process begins. Listeners receive events + * to indicate the progress, success, or failure of the save operation. To ascertain the status of the dialog box + * and the save operation after calling {@link save save()}, your code must listen for events such as cancel, + * open, progress, and complete. + * + * When the file is saved successfully, the properties of the {@link FileReference} object are populated with + * the properties of the local file. The complete event is dispatched if the save is successful. + * + * Only one {@link browse browse()} or {@link save()} session can be performed at a time (because only one + * dialog box can be invoked at a time). + * + * @param data The data to be saved. The data can be in one of several formats, and will be treated appropriately. + * @param fileName File name to be saved. + */ + static save(data: string, fileName: string): void; + } + /** + * The {@link FileReferenceList} class provides a means to let users select one or more files for + * {@link FileReference.load loading}. A {@link FileReferenceList} object represents a group of one or more local + * files on the user's disk as an array of {@link FileReference} objects. For detailed information and important + * considerations about {@link FileReference} objects and the FileReference class, which you use with + * {@link FileReferenceList}, see the {@link FileReference} class. + * + * To work with the {@link FileReferenceList} class: + *
    + *
  • Instantiate the class: var myFileRef = new FileReferenceList();
  • + *
  • + * Call the {@link FileReferenceList.browse} method, which opens a dialog box that lets the user select one or + * more files for upload: myFileRef.browse(); + *
  • + *
  • + * After the {@link browse browse()} method is called successfully, the {@link fileList} property of the + * {@link FileReferenceList} object is populated with an array of {@link FileReference} objects. + *
  • + *
  • Call {@link FileReference.load} on each element in the {@link fileList} array.
  • + *
+ * + * The {@link FileReferenceList} class includes a {@link browse browse()} method and a {@link fileList} property + * for working with multiple files. + * + * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/FileReferenceList.html + * @author Jeongho Nam + */ + class FileReferenceList extends EventDispatcher { + /** + * @hidden + */ + file_list: std.Vector; + /** + * Default Constructor. + */ + constructor(); + /** + * An array of {@link FileReference} objects. + * + * When the {@link FileReferenceList.browse} method is called and the user has selected one or more files + * from the dialog box that the {@link browse browse()} method opens, this property is populated with an array of + * {@link FileReference} objects, each of which represents the files the user selected. + * + * The {@link fileList} property is populated anew each time {@link browse browse()} is called on that + * {@link FileReferenceList} object. + */ + readonly fileList: std.Vector; + /** + * Displays a file-browsing dialog box that lets the user select one or more local files to upload. The + * dialog box is native to the user's browser system. + * + * When you call this method and the user successfully selects files, the {@link fileList} property of this + * {@link FileReferenceList} object is populated with an array of {@link FileReference} objects, one for each + * file that the user selects. Each subsequent time that the {@link FileReferenceList.browse} method is called, + * the {@link FileReferenceList.fileList} property is reset to the file(s) that the user selects in the dialog + * box. + * + * Using the *typeFilter* parameter, you can determine which files the dialog box displays. + * + * Only one {@link FileReference.browse}, {@link FileReference.load}, or {@link FileReferenceList.browse} + * session can be performed at a time on a {@link FileReferenceList} object (because only one dialog box can be + * opened at a time). + * + * @param typeFilter An array of filter strings used to filter the files that are displayed in the dialog box. + * If you omit this parameter, all files are displayed. + */ + browse(...typeFilter: string[]): void; + } +} +declare namespace samchon.library { + /** + * A genetic algorithm class. + * + * In the field of artificial intelligence, a genetic algorithm (GA) is a search heuristic that mimics the + * process of natural selection. This heuristic (also sometimes called a metaheuristic) is routinely used to generate + * useful solutions to optimization and search problems. + * + * Genetic algorithms belong to the larger class of evolutionary algorithms (EA), which generate solutions to + * optimization problems using techniques inspired by natural evolution, such as inheritance, {@link mutate mutation}, + * {@link selection}, and {@link crossover}. + * + * @reference https://en.wikipedia.org/wiki/Genetic_algorithm + * @author Jeongho Nam + */ + class GeneticAlgorithm { + /** + * Whether each element (Gene) is unique in their GeneArray. + */ + private unique_; + /** + * Rate of mutation. + * + * The {@link mutation_rate} determines the percentage of occurence of mutation in GeneArray. + * + *
    + *
  • When {@link mutation_rate} is too high, it is hard to ancitipate studying on genetic algorithm.
  • + *
  • + * When {@link mutation_rate} is too low and initial set of genes (GeneArray) is far away from optimal, the + * evolution tends to wandering outside of he optimal. + *
  • + *
+ */ + private mutation_rate_; + /** + * Number of tournaments in selection. + */ + private tournament_; + /** + * Initialization Constructor. + * + * @param unique Whether each Gene is unique in their GeneArray. + * @param mutation_rate Rate of mutation. + * @param tournament Number of tournaments in selection. + */ + constructor(unique?: boolean, mutation_rate?: number, tournament?: number); + /** + * Evolove *GeneArray*. + * + * Convenient method accessing to {@link evolvePopulation evolvePopulation()}. + * + * @param individual An initial set of genes; sequence listing. + * @param population Size of population in a generation. + * @param generation Size of generation in evolution. + * @param compare A comparison function returns whether left gene is more optimal. + * + * @return An evolved *GeneArray*, optimally. + * + * @see {@link GAPopulation.compare} + */ + evolveGeneArray>(individual: GeneArray, population: number, generation: number, compare?: (left: T, right: T) => boolean): GeneArray; + /** + * Evolve *population*, a mass of *GeneArraies*. + * + * @param population An initial population. + * @param compare A comparison function returns whether left gene is more optimal. + * + * @return An evolved population. + * + * @see {@link GAPopulation.compare} + */ + evolvePopulation>(population: GAPopulation, compare?: (left: T, right: T) => boolean): GAPopulation; + /** + * Select the best GeneArray in *population* from tournament. + * + * {@link selection Selection} is the stage of a genetic algorithm in which individual genomes are chosen + * from a population for later breeding (using {@linlk crossover} operator). A generic {@link selection} + * procedure may be implemented as follows: + * + *
    + *
  1. + * The fitness function is evaluated for each individual, providing fitness values, which are then + * normalized. ization means dividing the fitness value of each individual by the sum of all fitness + * values, so that the sum of all resulting fitness values equals 1. + *
  2. + *
  3. The population is sorted by descending fitness values.
  4. + *
  5. + * Accumulated normalized fitness values are computed (the accumulated fitness value of an individual is the + * sum of its own fitness value plus the fitness values of all the previous individuals). The accumulated + * fitness of the last individual should be 1 (otherwise something went wrong in the normalization step). + *
  6. + *
  7. A random number R between 0 and 1 is chosen.
  8. + *
  9. The selected individual is the first one whose accumulated normalized value is greater than R.
  10. + *
+ * + * @param population The target of tournament. + * @return The best genes derived by the tournament. + * + * @reference https://en.wikipedia.org/wiki/Selection_(genetic_algorithm) + */ + private selection(population); + /** + * Create a new GeneArray by crossing over two *GeneArray*(s). + * + * {@link crossover} is a genetic operator used to vary the programming of a chromosome or chromosomes from + * one generation to the next. It is analogous to reproduction and biological crossover, upon which genetic + * algorithms are based. + * + * {@link crossover Cross over} is a process of taking more than one parent solutions and producing a child + * solution from them. There are methods for selection of the chromosomes. + * + * @param parent1 A parent sequence listing + * @param parent2 A parent sequence listing + * + * @reference https://en.wikipedia.org/wiki/Crossover_(genetic_algorithm) + */ + private crossover(parent1, parent2); + /** + * Cause a mutation on the *GeneArray*. + * + * {@link mutate Mutation} is a genetic operator used to maintain genetic diversity from one generation of a + * population of genetic algorithm chromosomes to the next. It is analogous to biological mutation. + * + * {@link mutate Mutation} alters one or more gene values in a chromosome from its initial state. In + * {@link mutate mutation}, the solution may change entirely from the previous solution. Hence GA can come to + * better solution by using {@link mutate mutation}. + * + * {@link mutate Mutation} occurs during evolution according to a user-definable mutation probability. This + * probability should be set low. If it is set too high, the search will turn into a primitive random search. + * + *

Note

+ * Muttion is pursuing diversity. Mutation is useful for avoiding the following problem. + * + * When initial set of genes(GeneArray) is far away from optimail, without mutation (only with selection and + * crossover), the genetic algorithm has a tend to wandering outside of the optimal. + * + * Genes in the GeneArray will be swapped following percentage of the {@link mutation_rate}. + * + * @param individual A container of genes to mutate + * + * @reference https://en.wikipedia.org/wiki/Mutation_(genetic_algorithm) + * @see {@link mutation_rate} + */ + private mutate(individual); + } + /** + * A population in a generation. + * + * {@link GAPopulation} is a class representing population of candidate genes (sequence listing) having an array + * of GeneArray as a member. {@link GAPopulation} also manages initial set of genes and handles fitting test direclty + * by the method {@link fitTest fitTest()}. + * + * The success of evolution of genetic algorithm is depend on the {@link GAPopulation}'s initial set and fitting + * test. (*GeneArray* and {@link compare}.) + * + *

Warning

+ * Be careful for the mistakes of direction or position of the {@link compare}. + * Most of logical errors failed to access optimal solution are occured from those mistakes. + * + * @param Type of gene elements. + * @param An array containing genes as elments; sequnce listing. + * + * @author Jeongho Nam + */ + class GAPopulation> { + /** + * Genes representing the population. + */ + private children_; + /** + * A comparison function returns whether left gene is more optimal, greater. + * + * Default value of this {@link compare} is {@link std.greater}. It means to compare two array + * (GeneArray must be a type of {@link std.base.IArrayContainer}). Thus, you've to keep follwing rule. + * + *
    + *
  • GeneArray is implemented from {@link std.base.IArrayContainer}.
  • + *
      + *
    • {@link std.Vector}
    • + *
    • {@link std.Deque}
    • + *
    + *
  • GeneArray has custom public less(obj: T): boolean; function.
  • + *
+ * + * If you don't want to follow the rule or want a custom comparison function, you have to realize a + * comparison function. + */ + private compare_; + /** + * Private constructor with population. + * + * Private constructor of GAPopulation does not create {@link children}. (candidate genes) but only assigns + * *null* repeatedly following the *population size*. + * + * This private constructor is designed only for {@link GeneticAlgorithm}. Don't create {@link GAPopulation} + * with this constructor, by yourself. + * + * @param size Size of the population. + */ + constructor(size: number); + /** + * Construct from a {@link GeneArray} and *size of the population*. + * + * This public constructor creates *GeneArray(s)* as population (size) having shuffled genes which are + * came from the initial set of genes (*geneArray*). It uses {@link std.greater} as default comparison function. + * + * + * @param geneArray An initial sequence listing. + * @param size The size of population to have as children. + */ + constructor(geneArray: GeneArray, size: number); + /** + * Constructor from a GeneArray, size of the poluation and custom comparison function. + * + * This public constructor creates *GeneArray(s)* as population (size) having shuffled genes which are + * came from the initial set of genes (*geneArray*). The *compare* is used for comparison function. + * + * + * @param geneArray An initial sequence listing. + * @param size The size of population to have as children. + * @param compare A comparison function returns whether left gene is more optimal. + */ + constructor(geneArray: GeneArray, size: number, compare: (left: GeneArray, right: GeneArray) => boolean); + children(): std.Vector; + /** + * Test fitness of each *GeneArray* in the {@link population}. + * + * @return The best *GeneArray* in the {@link population}. + */ + fitTest(): GeneArray; + /** + * @hidden + */ + private clone(obj); + } +} +declare namespace samchon.library { + /** + * A utility class supporting static methods of string. + * + * The {@link StringUtil} utility class is an all-static class with methods for working with string objects. + * You do not create instances of {@link StringUtil}; instead you call methods such as the + * ```StringUtil.substitute()``` method. + * + * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/utils/StringUtil.html + * @author Jeongho Nam + */ + class StringUtil { + /** + * Generate a substring. + * + * Extracts a substring consisting of the characters from specified start to end. + * It's same with str.substring( ? = (str.find(start) + start.size()), str.find(end, ?) ) + * + * ```typescript + * let str: string = StringUtil.between("ABCD(EFGH)IJK", "(", ")"); + * console.log(str); // PRINTS "EFGH" + * ``` + * + * - If start is not specified, extracts from begin of the string to end. + * - If end is not specified, extracts from start to end of the string. + * - If start and end are all omitted, returns str, itself. + * + * @param str Target string to be applied between. + * @param start A string for separating substring at the front. + * @param end A string for separating substring at the end. + * + * @return substring by specified terms. + */ + static between(str: string, start?: string, end?: string): string; + /** + * Fetch substrings. + * + * Splits a string into an array of substrings dividing by specified delimeters of start and end. + * It's the array of substrings adjusted the between. + * + *
    + *
  • If startStr is omitted, it's same with the split by endStr not having last item.
  • + *
  • If endStr is omitted, it's same with the split by startStr not having first item.
  • + *
  • If startStr and endStar are all omitted, returns *str*.
  • + *
+ * + * @param str Target string to split by between. + * @param start A string for separating substring at the front. + * If omitted, it's same with split(end) not having last item. + * @param end A string for separating substring at the end. + * If omitted, it's same with split(start) not having first item. + * @return An array of substrings. + */ + static betweens(str: string, start?: string, end?: string): Array; + /** + * An array containing whitespaces. + */ + private static SPACE_ARRAY; + /** + * Remove all designated characters from the beginning and end of the specified string. + * + * @param str The string whose designated characters should be trimmed. + * @param args Designated character(s). + * + * @return Updated string where designated characters was removed from the beginning and end. + */ + static trim(str: string, ...args: string[]): string; + /** + * Remove all designated characters from the beginning of the specified string. + * + * @param str The string should be trimmed. + * @param delims Designated character(s). + * + * @return Updated string where designated characters was removed from the beginning + */ + static ltrim(str: string, ...args: string[]): string; + /** + * Remove all designated characters from the end of the specified string. + * + * @param str The string should be trimmed. + * @param delims Designated character(s). + * + * @return Updated string where designated characters was removed from the end. + */ + static rtrim(str: string, ...args: string[]): string; + /** + * Substitute `{n}` tokens within the specified string. + * + * @param format The string to make substitutions in. This string can contain special tokens of the form + * `{n}`, where *n* is a zero based index, that will be replaced with the additional parameters + * found at that index if specified. + * @param args Additional parameters that can be substituted in the *format* parameter at each + * `{n}` location, where *n* is an integer (zero based) index value into the array of values + * specified. + * + * @return New string with all of the `{n}` tokens replaced with the respective arguments specified. + */ + static substitute(format: string, ...args: any[]): string; + /** + * Substitute `{n}` tokens within the specified SQL-string. + * + * @param format The string to make substitutions in. This string can contain special tokens of the form + * `{n}`, where *n* is a zero based index, that will be replaced with the additional parameters + * found at that index if specified. + * @param args Additional parameters that can be substituted in the *format* parameter at each + * `{n}` location, where *n* is an integer (zero based) index value into the array of values + * specified. + * + * @return New SQL-string with all of the `{n}` tokens replaced with the respective arguments specified. + */ + static substituteSQL(format: string, ...args: any[]): string; + /** + * @hidden + */ + private static _Fetch_substitute_index(format); + /** + * Returns a string specified word is replaced. + * + * @param str Target string to replace + * @param before Specific word you want to be replaced + * @param after Specific word you want to replace + * + * @return A string specified word is replaced + */ + static replaceAll(str: string, before: string, after: string): string; + /** + * Returns a string specified words are replaced. + * + * @param str Target string to replace + * @param pairs A specific word's pairs you want to replace and to be replaced + * + * @return A string specified words are replaced + */ + static replaceAll(str: string, ...pairs: std.Pair[]): string; + /** + * Replace all HTML spaces to a literal space. + * + * @param str Target string to replace. + */ + static removeHTMLSpaces(str: string): string; + /** + * Repeat a string. + * + * Returns a string consisting of a specified string concatenated with itself a specified number of times. + * + * @param str The string to be repeated. + * @param n The repeat count. + * + * @return The repeated string. + */ + static repeat(str: string, n: number): string; + /** + * Number to formatted string with "," sign. + * + * Returns a string converted from the number rounded off from specified precision with "," symbols. + * + * @param val A number wants to convert to string. + * @param precision Target precision of round off. + * + * @return A string who represents the number with roundoff and "," symbols. + */ + static numberFormat(val: number, precision?: number): string; + static percentFormat(val: number, precision?: number): string; + } +} +declare namespace samchon.library { + /** + * URLVariables class is for representing variables of HTTP. + * + * {@link URLVariables} class allows you to transfer variables between an application and server. + * + * When transfering, {@link URLVariables} will be converted to a *URI* string. + * - URI: Uniform Resource Identifier + * + * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/URLVariables.html + * @author Migrated by Jeongho Nam + */ + class URLVariables extends std.HashMap { + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from a URL-encoded string. + * + * The {@link decode decode()} method is automatically called to convert the string to properties of the {@link URLVariables} object. + * + * @param str A URL-encoded string containing name/value pairs. + */ + constructor(str: string); + /** + * Converts the variable string to properties of the specified URLVariables object. + * + * @param str A URL-encoded query string containing name/value pairs. + */ + decode(str: string): void; + /** + * Returns a string containing all enumerable variables, in the MIME content encoding application/x-www-form-urlencoded. + */ + toString(): string; + } +} +declare namespace samchon.library { + /** + * A tree-structured XML object. + * + * The {@link XML| class contains methods and properties for working with XML objects. The {@link XML} class (along + * with the {@link XMLList}) implements the powerful XML-handling standards defined in ECMAScript for XML (E4X) + * specification (ECMA-357 edition 2). + * + * An XML object, it is composed with three members; {@link getTag tag}, {@link getProperty properties} and + * {@link getValue value}. As you know, XML is a tree structured data expression method. The tree-stucture; + * {@link XML} class realizes it by extending ```std.HashMap```. Child {@link XML} objects are + * contained in the matched {@link XMLList} object being grouped by their {@link getTag tag name}. The + * {@link XMLList} objects, they're stored in the {@link std.HashMap} ({@link XML} itself) with its **key**; common + * {@link getTag tag name} of children {@link XML} objects. + * + * ```typescript + * class XML extends std.HashMap + * { + * private tag_: string; + * private properties_: std.HashMap; + * private value_: string; + * } + * ``` + * + * ```xml + * + * + * + * {value} + * {value} + * {value} + * + * + * + * + * ``` + * + * Use the {@link toString toString()} method to return a string representation of the {@link XML} object regardless + * of whether the {@link XML} object has simple content or complex content. + * + * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/XML.html + * @handbook https://github.com/samchon/framework/wiki/TypeScript-Library-XML + * @author Jeongho Nam + */ + class XML extends std.HashMap { + /** + * @hidden + */ + private tag_; + /** + * @hidden + */ + private value_; + /** + * @hidden + */ + private property_map_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from string. + * + * Creates {@link XML} object by parsing a string who represents xml structure. + * + * @param str A string represents XML structure. + */ + constructor(str: string); + /** + * @hidden + */ + private _Parse(str); + /** + * @hidden + */ + private _Parse_tag(str); + /** + * @hidden + */ + private _Parse_properties(str); + /** + * @hidden + */ + private _Parse_value(str); + /** + * @hidden + */ + private _Parse_children(str); + /** + * Get tag. + * + * ```xml + * {value} + * ``` + * + * @return tag. + */ + getTag(): string; + /** + * Get value. + * + * ```xml + * {VALUE} + * ``` + * + * @return value. + */ + getValue(): string; + /** + * Get iterator to property element. + * + * Searches the {@link getPropertyMap properties} for an element with a identifier equivalent to key + * and returns an iterator to it if found, otherwise it returns an iterator to {@link HashMap.end end()}. + * + *

Two keys are considered equivalent if the properties' comparison object returns false reflexively + * (i.e., no matter the order in which the elements are passed as arguments).

+ * + * Another member function, {@link hasProperty hasProperty()} can be used to just check whether a particular + * key exists. + * + * ```xml + * {value} + * ``` + * + * @param key Key to be searched for + * @return An iterator to the element, if an element with specified key is found, or + * {@link end HashMap.end()} otherwise. + */ + findProperty(key: string): std.MapIterator; + /** + * Test whether a property exists. + * + * ```xml + * {value} + * ``` + * + * @return Whether a property has the *key* exists or not. + */ + hasProperty(key: string): boolean; + /** + * Get property. + * + * Get property by its *key*, property name. If the matched *key* does not exist, then exception + * {@link std.OutOfRange} is thrown. Thus, it would better to test whether the *key* exits or not by calling the + * {@link hasProperty hasProperty()} method before calling this {@link getProperty getProperty()}. + * + * This method can be substituted by {@link getPropertyMap getPropertyMap()} such below: + * - ```getPropertyMap().get(key, value);``` + * - ```getPropertyMap().find(key).second;``` + * + * ```xml + * {value} + * ``` + * + * @return Value of the matched property. + */ + getProperty(key: string): string; + /** + * Get property map. + * + * ```xml + * {value} + * ``` + * + * @return {@link HashMap} containing properties' keys and values. + */ + getPropertyMap(): std.HashMap; + /** + * Set tag. + * + * Set tag name, identifier of this {@link XML} object. + * + * If this {@link XML} object is belonged to, a child of, an {@link XMLList} and its related {@link XML} objects, + * then calling this {@link setTag setTag()} method direclty is not recommended. Erase this {@link XML} object + * from parent objects and insert this object again. + * + * ```xml + * {value} + * ``` + * + * @param val To be new {@link getTag tag}. + */ + setTag(val: string): void; + /** + * Set value. + * + * ```xml + * {VALUE} + * ``` + * + * @param val To be new {@link getValue value}. + */ + setValue(val: string): void; + /** + * Set property. + * + * Set a property *value* with its *key*. If the *key* already exists, then the *value* will be overwritten to + * the property. Otherwise the *key* is not exist yet, then insert the *key* and *value* {@link Pair pair} to + * {@link getPropertyMao property map}. + * + * This method can be substituted by {@link getPropertyMap getPropertyMap()} such below: + * - ```getPropertyMap().set(key, value);``` + * - ```getPropertyMap().emplace(key, value);``` + * - ```getPropertyMap().insert([key, value]);``` + * - ```getPropertyMap().insert(std.make_pair(key, value));``` + * + * ```xml + * {value} + * ``` + * + * @param key Key, identifier of property to be newly inserted. + * @param value Value of new property to be newly inserted. + */ + setProperty(key: string, value: string): void; + /** + * Erase property. + * + * Erases a property by its *key*, property name. If the matched *key* does not exist, then exception + * {@link std.OutOfRange} is thrown. Thus, it would better to test whether the *key* exits or not by calling the + * {@link hasProperty hasProperty()} method before calling this {@link eraseProperty eraseProperty()}. + * + * This method can be substituted by ``getPropertyMap().erase(key)````. + * + * ```xml + * {value} + * ``` + * + * @param key Key of the property to erase + * @throw {@link std.OutOfRange} + */ + eraseProperty(key: string): void; + /** + * @hidden + */ + push(...args: std.Pair[]): number; + /** + * @hidden + */ + push(...args: [string, XMLList][]): number; + push(...xmls: XML[]): number; + push(...xmlLists: XMLList[]): number; + /** + * Add all properties from other {@link XML} object. + * + * All the properties in the *obj* are copied to this {@link XML} object. If this {@link XML} object has same + * property key in the *obj*, then value of the property will be replaced to *obj*'s own. If you don't want to + * overwrite properties with same key, then use {@link getPropertyMap getPropertyMap()} method. + * + * ```typescript + * let x: library.XML; + * let y: library.XML; + * + * x.addAllProperties(y); // duplicated key exists, then overwrites + * x.getPropertyMap().insert(y.getPropertyMap().begin(), y.getPropertyMap().end()); + * // ducpliated key, then ignores. only non-duplicateds are copied. + * ``` + * + * ```xml + * {value} + * ``` + * + * @param obj Target {@link XML} object to copy properties. + */ + insertAllProperties(obj: XML): void; + /** + * Clear properties. + * + * Remove all properties. It's same with calling ```getPropertyMap().clear()```. + * + * ```xml + * {value} + * ``` + */ + clearProperties(): void; + /** + * @hidden + */ + private _Compute_min_index(...args); + /** + * @hidden + */ + private _Decode_value(str); + /** + * @hidden + */ + private _Encode_value(str); + /** + * @hidden + */ + private _Decode_property(str); + /** + * @hidden + */ + private _Encode_property(str); + /** + * {@link XML} object to xml string. + * + * Returns a string representation of the {@link XML} object. + * + * @param tab Number of tabs to spacing. + * @return The string representation of the {@link XML} object. + */ + toString(tab?: number): string; + } +} +declare namespace samchon.library { + /** + * List of {@link XML} objects with same tag. + * + * @reference http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/XMLList.html + * @handbook https://github.com/samchon/framework/wiki/TypeScript-Library-XML + * @author Jeongho Nam + */ + class XMLList extends std.Deque { + /** + * Get tag. + */ + getTag(): string; + /** + * {@link XMLList XML objects} to string. + * + * Returns a string representation of the {@link XMLList XML objects}. + * + * @param tab Number of tabs to spacing. + * @return The string representation of the {@link XMLList XML objects}. + */ + toString(level?: number): string; + } +} +declare namespace samchon.protocol { + /** + * An interface of entity. + * + * Entity is a class for standardization of expression method using on network I/O by XML. If + * Invoke is a standard message protocol of Samchon Framework which must be kept, Entity is a + * recommended semi-protocol of message for expressing a data class. Following the semi-protocol + * Entity is not imposed but encouraged. + * + * As we could get advantages from standardization of message for network I/O with Invoke, + * we can get additional advantage from standardizing expression method of data class with Entity. + * We do not need to know a part of network communication. Thus, with the Entity, we can only + * concentrate on entity's own logics and relationships between another entities. Entity does not + * need to how network communications are being done. + * + * I say repeatedly. Expression method of Entity is recommended, but not imposed. It's a semi + * protocol for network I/O but not a essential protocol must be kept. The expression method of + * Entity, using on network I/O, is expressed by XML string. + * + * If your own network system has a critical performance issue on communication data class, + * it would be better to using binary communication (with ByteArray). + * Don't worry about the problem! Invoke also provides methods for binary data (ByteArray). + * + * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_message_protocol.png) + * + * @author Jeongho Nam + */ + interface IEntity { + /** + * Construct data of the Entity from a XML object. + * + * Overrides the construct() method and fetch data of member variables from the XML. + * + * By recommended guidance, data representing member variables are contained in properties + * of the put XML object. + * + * @param xml An xml used to contruct data of entity. + */ + construct(xml: library.XML): void; + /** + * Get a key that can identify the Entity uniquely. + * + * If identifier of the Entity is not atomic value, returns a paired or tuple object + * that can represents the composite identifier. + * + * + * class Point extends Entity + * { + * private x: number; + * private y: number; + * + * public key(): std.Pair + * { + * return std.make_pair(this.x, this.y); + * } + * } + * + */ + key(): any; + /** + * A tag name when represented by XML. + * + * + */ + TAG(): string; + /** + * Get a XML object represents the Entity. + * + * A member variable (not object, but atomic value like number, string or date) is categorized + * as a property within the framework of entity side. Thus, when overriding a toXML() method and + * archiving member variables to an XML object to return, puts each variable to be a property + * belongs to only a XML object. + * + * Don't archive the member variable of atomic value to XML::value causing enormouse creation + * of XML objects to number of member variables. An Entity must be represented by only a XML + * instance (tag). + * + *

Standard Usage.

+ * + * + * + * + * + * + * + *

Non-standard usage abusing value.

+ * + * + * jhnam88 + * Jeongho Nam + * 1988-03-11 + * + * + * master + * Administartor + * 2011-07-28 + * + * + * + * @return An XML object representing the Entity. + */ + toXML(): library.XML; + } + /** + * @hidden + */ + namespace IEntity { + function construct(entity: IEntity, xml: library.XML, ...prohibited_names: string[]): void; + function toXML(entity: IEntity, ...prohibited_names: string[]): library.XML; + } + /** + * An entity, a standard data class. + * + * Entity is a class for standardization of expression method using on network I/O by XML. If + * Invoke is a standard message protocol of Samchon Framework which must be kept, Entity is a + * recommended semi-protocol of message for expressing a data class. Following the semi-protocol + * Entity is not imposed but encouraged. + * + * As we could get advantages from standardization of message for network I/O with Invoke, + * we can get additional advantage from standardizing expression method of data class with Entity. + * We do not need to know a part of network communication. Thus, with the Entity, we can only + * concentrate on entity's own logics and relationships between another entities. Entity does not + * need to how network communications are being done. + * + * I say repeatedly. Expression method of Entity is recommended, but not imposed. It's a semi + * protocol for network I/O but not a essential protocol must be kept. The expression method of + * Entity, using on network I/O, is expressed by XML string. + * + * If your own network system has a critical performance issue on communication data class, + * it would be better to using binary communication (with ByteArray). + * Don't worry about the problem! Invoke also provides methods for binary data (ByteArray). + * + * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_message_protocol.png) + * + * @author Jeongho Nam + */ + abstract class Entity implements IEntity { + /** + * Default Constructor. + */ + constructor(); + construct(xml: library.XML): void; + /** + * @inheritdoc + */ + key(): any; + /** + * @inheritdoc + */ + abstract TAG(): string; + /** + * @inheritdoc + */ + toXML(): library.XML; + } +} +declare namespace samchon.protocol { + /** + * @inheritdoc + */ + interface IEntityCollection extends IEntityGroup, collections.ICollection { + } +} +declare namespace samchon.protocol { + /** + * @inheritdoc + */ + abstract class EntityArrayCollection extends collections.ArrayCollection implements IEntityCollection { + /** + * @inheritdoc + */ + construct(xml: library.XML): void; + /** + * @inheritdoc + */ + abstract createChild(xml: library.XML): T; + /** + * @inheritdoc + */ + key(): any; + /** + * @inheritdoc + */ + has(key: any): boolean; + /** + * @inheritdoc + */ + count(key: any): number; + /** + * @inheritdoc + */ + get(key: any): T; + /** + * @inheritdoc + */ + abstract TAG(): string; + /** + * @inheritdoc + */ + abstract CHILD_TAG(): string; + /** + * @inheritdoc + */ + toXML(): library.XML; + } +} +declare namespace samchon.protocol { + /** + * @inheritdoc + */ + abstract class EntityListCollection extends collections.ListCollection implements IEntityCollection { + /** + * @inheritdoc + */ + construct(xml: library.XML): void; + /** + * @inheritdoc + */ + abstract createChild(xml: library.XML): T; + /** + * @inheritdoc + */ + key(): any; + /** + * @inheritdoc + */ + has(key: any): boolean; + /** + * @inheritdoc + */ + count(key: any): number; + /** + * @inheritdoc + */ + get(key: any): T; + /** + * @inheritdoc + */ + abstract TAG(): string; + /** + * @inheritdoc + */ + abstract CHILD_TAG(): string; + /** + * @inheritdoc + */ + toXML(): library.XML; + } +} +declare namespace samchon.protocol { + /** + * @inheritdoc + */ + abstract class EntityDequeCollection extends collections.DequeCollection implements IEntityCollection { + /** + * @inheritdoc + */ + construct(xml: library.XML): void; + /** + * @inheritdoc + */ + abstract createChild(xml: library.XML): T; + /** + * @inheritdoc + */ + key(): any; + /** + * @inheritdoc + */ + has(key: any): boolean; + /** + * @inheritdoc + */ + count(key: any): number; + /** + * @inheritdoc + */ + get(key: any): T; + /** + * @inheritdoc + */ + abstract TAG(): string; + /** + * @inheritdoc + */ + abstract CHILD_TAG(): string; + /** + * @inheritdoc + */ + toXML(): library.XML; + } +} +/** + * A template for External Systems Manager. + * + * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) + * @author Jeongho Nam + */ +declare namespace samchon.templates.external { + /** + * An array and manager of {@link ExternalSystem external system drivers}. + * + * The {@link ExternalSystemArray} is an abstract class containing and managing external system drivers, + * {@link ExternalSystem} objects. Within framewokr of network, {@link ExternalSystemArray} represents your system + * and children {@link ExternalSystem} objects represent remote, external systems connected with your system. + * With this {@link ExternalSystemArray}, you can manage multiple external systems as a group. + * + * You can specify this {@link ExternalSystemArray} class to be *a server accepting external clients* or + * *a client connecting to external servers*. Even both of them is also possible. + * + * - {@link ExternalClientArray}: A server accepting {@link ExternalSystem external clients}. + * - {@link ExternalServerArray}: A client connecting to {@link ExternalServer external servers}. + * - {@link ExternalServerClientArray}: Both of them. Accepts {@link ExternalSystem external clients} and connects to + * {@link ExternalServer external servers} at the same time. + * + * + * + * + * + * #### Proxy Pattern + * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which + * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not + * important. Only interested in user's perspective is *which can be done*. + * + * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged + * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. + * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. + * + *
    + *
  • + * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring + * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. + *
  • + *
  • + * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call + * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the + * external system. + *
  • + *
  • Those strategy is called *Proxy Pattern*.
  • + *
+ * + * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) + * @author Jeongho Nam + */ + abstract class ExternalSystemArray extends protocol.EntityDequeCollection implements protocol.IProtocol { + /** + * Default Constructor. + */ + constructor(); + /** + * @hidden + */ + private _Handle_system_erase(event); + /** + * Test whether the role exists. + * + * @param name Name, identifier of target {@link ExternalSystemRole role}. + * + * @return Whether the role has or not. + */ + hasRole(name: string): boolean; + /** + * Get a role. + * + * @param name Name, identifier of target {@link ExternalSystemRole role}. + * + * @return The specified role. + */ + getRole(name: string): ExternalSystemRole; + /** + * Send an {@link Invoke} message. + * + * @param invoke An {@link Invoke} message to send. + */ + sendData(invoke: protocol.Invoke): void; + /** + * Handle an {@Invoke} message have received. + * + * @param invoke An {@link Invoke} message have received. + */ + abstract replyData(invoke: protocol.Invoke): void; + /** + * Tag name of the {@link ExternalSytemArray} in {@link XML}. + * + * @return *systemArray*. + */ + TAG(): string; + /** + * Tag name of {@link ExternalSystem children elements} belonged to the {@link ExternalSytemArray} in {@link XML}. + * + * @return *system*. + */ + CHILD_TAG(): string; + } +} +/** + * A template for Parallel Processing System. + * + * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) + * @author Jeongho Nam + */ +declare namespace samchon.templates.parallel { + /** + * Master of Parallel Processing System. + * + * The {@link ParallelSystemArray} is an abstract class containing and managing remote parallel **slave** system + * drivers, {@link ParallelSystem} objects. Within framework of network, {@link ParallelSystemArray} represents your + * system, a **Master** of *Parallel Processing System* that requesting *parallel process* to **slave** systems and the + * children {@link ParallelSystem} objects represent the remote **slave** systems, who is being requested the + * *parallel processes*. + * + * You can specify this {@link ParallelSystemArray} class to be *a server accepting parallel clients* or + * *a client connecting to parallel servers*. Even both of them is possible. Extends one of them below and overrides + * abstract factory method(s) creating the child {@link ParallelSystem} object. + * + * - {@link ParallelClientArray}: A server accepting {@link ParallelSystem parallel clients}. + * - {@link ParallelServerArray}: A client connecting to {@link ParallelServer parallel servers}. + * - {@link ParallelServerClientArray}: Both of them. Accepts {@link ParallelSystem parallel clients} and connects to + * {@link ParallelServer parallel servers} at the same time. + * + * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. + * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s + * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices + * will be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. + * + * + * + * + * + * #### Proxy Pattern + * This class {@link ParallelSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take + * advantage of the *Proxy Pattern* in the {@link ParallelSystemArray} class. If a process to request is not the + * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it + * may better to utilizing the *Proxy Pattern*: + * + * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which + * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not + * important. Only interested in user's perspective is *which can be done*. + * + * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged + * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. + * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. + * + *
    + *
  • + * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring + * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. + *
  • + *
  • + * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call + * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the + * external system. + *
  • + *
  • Those strategy is called *Proxy Pattern*.
  • + *
+ * + * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) + * @author Jeongho Nam + */ + abstract class ParallelSystemArray extends external.ExternalSystemArray { + /** + * @hidden + */ + private history_sequence_; + /** + * Default Constructor. + */ + constructor(); + /** + * Send an {@link Invoke} message with segment size. + * + * Sends an {@link Invoke} message requesting a **parallel process** with its *segment size*. The {@link Invoke} + * message will be delivered to children {@link ParallelSystem} objects with the *piece size*, which is divided + * from the *segment size*, basis on their {@link ParallelSystem.getPerformance performance indices}. + * + * - If segment size is 100, + * - The segment will be allocated such below: + * + * Name | Performance index | Number of pieces to be allocated | Formula + * --------|-------------------|----------------------------------|-------------- + * Snail | 1 | 10 | 100 / 10 * 1 + * Cheetah | 4 | 40 | 100 / 10 * 4 + * Rabbit | 3 | 30 | 100 / 10 * 3 + * Turtle | 2 | 20 | 100 / 10 * 2 + * + * When the **parallel process** has completed, then this {@link ParallelSystemArraY} will estimate + * {@link ParallelSystem.getPerformance performance indices} of {@link ParallelSystem} objects basis on their + * execution time. + * + * @param invoke An {@link Invoke} message requesting parallel process. + * @param size Number of pieces to segment. + * + * @return Number of {@link ParallelSystem slave systems} participating in the *Parallel Process*. + * + * @see {@link sendPieceData}, {@link ParallelSystem.getPerformacen} + */ + sendSegmentData(invoke: protocol.Invoke, size: number): number; + /** + * Send an {@link Invoke} message with range of pieces. + * + * Sends an {@link Invoke} message requesting a **parallel process** with its *range of pieces [first, last)*. + * The {@link Invoke} will be delivered to children {@link ParallelSystem} objects with the newly computed + * *range of sub-pieces*, which is divided from the *range of pieces (first to last)*, basis on their + * {@link ParallelSystem.getPerformance performance indices}. + * + * - If indices of pieces are 0 to 50, + * - The sub-pieces will be allocated such below: + * + * Name | Performance index | Range of sub-pieces to be allocated | Formula + * --------|-------------------|-------------------------------------|------------------------ + * Snail | 1 | ( 0, 5] | (50 - 0) / 10 * 1 + * Cheetah | 4 | ( 5, 25] | (50 - 0) / 10 * 4 + 5 + * Rabbit | 3 | (25, 40] | (50 - 0) / 10 * 3 + 25 + * Turtle | 2 | (40, 50] | (50 - 0) / 10 * 2 + 40 + * + * When the **parallel process** has completed, then this {@link ParallelSystemArraY} will estimate + * {@link ParallelSystem.getPerformance performance indices} of {@link ParallelSystem} objects basis on their + * execution time. + * + * @param invoke An {@link Invoke} message requesting parallel process. + * @param first Initial piece's index in a section. + * @param last Final piece's index in a section. The range used is [*first*, *last*), which contains + * all the pieces' indices between *first* and *last*, including the piece pointed by index + * *first*, but not the piece pointed by the index *last*. + * + * @return Number of {@link ParallelSystem slave systems} participating in the *Parallel Process*. + * + * @see {@link sendSegmentData}, {@link ParallelSystem.getPerformacen} + */ + sendPieceData(invoke: protocol.Invoke, first: number, last: number): number; + /** + * @hidden + */ + protected _Complete_history(history: slave.InvokeHistory): boolean; + /** + * @hidden + */ + protected _Normalize_performance(): void; + } +} +/** + * A template for Distributed Processing System. + * + * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) + * @author Jeongho Nam + */ +declare namespace samchon.templates.distributed { + /** + * Master of Distributed Processing System. + * + * The {@link DistributedSystemArray} is an abstract class containing and managing remote distributed **slave** system + * drivers, {@link DistributedSystem} objects. Within framework of network, {@link DistributedSystemArray} represents + * your system, a **Master** of *Distributed Processing System* that requesting *distributed process* to **slave** + * systems and the children {@link DistributedSystem} objects represent the remote **slave** systems, who is being + * requested the *distributed processes*. + * + * You can specify this {@link DistributedSystemArray} class to be *a server accepting distributed clients* or + * *a client connecting to distributed servers*. Even both of them is possible. Extends one of them below and overrides + * abstract factory method(s) creating the child {@link DistributedSystem} object. + * + * - {@link DistributedClientArray}: A server accepting {@link DistributedSystem distributed clients}. + * - {@link DistributedServerArray}: A client connecting to {@link DistributedServer distributed servers}. + * - {@link DistributedServerClientArray}: Both of them. Accepts {@link DistributedSystem distributed clients} and + * connects to {@link DistributedServer distributed servers} at the same time. + * + * The {@link DistributedSystemArray} contains {@link DistributedProcess} objects directly. You can request a + * **distributed process** through the {@link DistributedProcess} object. You can access the + * {@link DistributedProcess} object(s) with those methods: + * + * - {@link hasProcess} + * - {@link getProcess} + * - {@link insertProcess} + * - {@link eraseProcess} + * - {@link getProcessMap} + * + * When you need the **distributed process**, call the {@link DistributedProcess.sendData} method. Then the + * {@link DistributedProcess} will find the most idle {@link DistributedSystem} object who represents a distributed + * **slave **system. The {@link Invoke} message will be sent to the most idle {@link DistributedSystem} object. When + * the **distributed process** has completed, then {@link DistributedSystem.getPerformance performance index} and + * {@link DistributedProcess.getResource resource index} of related objects will be revaluated. + * + * + * + * + * + * #### Parallel Process + * This {@link DistributedSystemArray} class is derived from the {@link ParallelSystemArray} class, so you can request + * a **parallel process**, too. + * + * When you need the **parallel process**, then call one of them: {@link sendSegmentData} or {@link sendPieceData}. + * When the **parallel process** has completed, {@link ParallelSystemArray} estimates each {@link ParallelSystem}'s + * {@link ParallelSystem.getPerformance performance index} basis on their execution time. Those performance indices will + * be reflected to the next **parallel process**, how much pieces to allocate to each {@link ParallelSystem}. + * + * #### Proxy Pattern + * This class {@link DistributedSystemArray} is derived from the {@link ExternalSystemArray} class. Thus, you can take + * advantage of the *Proxy Pattern* in the {@link DistributedSystemArray} class. If a process to request is not the + * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it + * may better to utilizing the *Proxy Pattern*: + * + * The {@link ExternalSystemArray} class can use *Proxy Pattern*. In framework within user, which + * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not + * important. Only interested in user's perspective is *which can be done*. + * + * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged + * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. + * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. + * + *
    + *
  • + * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring + * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. + *
  • + *
  • + * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call + * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the + * external system. + *
  • + *
  • Those strategy is called *Proxy Pattern*.
  • + *
+ * + * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) + * @author Jeongho Nam + */ + abstract class DistributedSystemArray extends parallel.ParallelSystemArray { + /** + * @hidden + */ + private process_map_; + /** + * Default Constructor. + */ + constructor(); + /** + * @inheritdoc + */ + construct(xml: library.XML): void; + /** + * Factory method creating a child {@link DistributedProcess process} object. + * + * @param xml {@link XML} represents the {@link DistributedProcess child} object. + * @return A new {@link DistributedProcess} object. + */ + protected abstract createProcess(xml: library.XML): DistributedProcess; + /** + * Get process map. + * + * Gets an {@link HashMap} containing {@link DistributedProcess} objects with their *key*. + * + * @return An {@link HasmMap> containing pairs of string and {@link DistributedProcess} object. + */ + getProcessMap(): std.HashMap; + /** + * Test whether the process exists. + * + * @param name Name, identifier of target {@link DistributedProcess process}. + * + * @return Whether the process has or not. + */ + hasProcess(name: string): boolean; + /** + * Get a process. + * + * @param name Name, identifier of target {@link DistributedProcess process}. + * + * @return The specified process. + */ + getProcess(name: string): DistributedProcess; + /** + * Insert a process. + * + * @param process A process to be inserted. + * @return Success flag. + */ + insertProcess(process: DistributedProcess): boolean; + /** + * Erase a process. + * + * @param name Name, identifier of target {@link DistributedProcess process}. + */ + eraseProcess(name: string): boolean; + /** + * @hidden + */ + protected _Complete_history(history: slave.InvokeHistory): boolean; + /** + * @hidden + */ + private estimate_process_resource(history); + /** + * @hidden + */ + private estimate_system_performance(history); + /** + * @hidden + */ + protected _Normalize_performance(): void; + /** + * @inheritdoc + */ + toXML(): library.XML; + } +} +declare namespace samchon.templates.distributed { + /** + * Mediator of Distributed Processing System. + * + * The {@link DistributedSystemArrayMediator} class be a master for its slave systems, and be a slave to its master + * system at the same time. This {@link DistributedSystemArrayMediator} be a master system, containing and managing + * {@link DistributedSystem} objects, which represent distributed slave systems, by extending + * {@link DistributedSystemArray} class. Also, be a slave system through {@link getMediator mediator} object, which is + * derived from the {@link SlaveSystem} class. + * + * As a master, you can specify this {@link DistributedSystemArrayMediator} class to be a master server accepting + * slave clients or a master client to connecting slave servers. Even both of them is possible. Extends one + * of them below and overrides abstract factory method(s) creating the child {@link DistributedSystem} object. + * + * - {@link DistributedClientArrayMediator}: A server accepting {@link DistributedSystem distributed clients}. + * - {@link DistributedServerArrayMediator}: A client connecting to {@link DistributedServer distributed servers}. + * - {@link DistributedServerClientArrayMediator}: Both of them. Accepts {@link DistributedSystem distributed clients} and + * connects to {@link DistributedServer distributed servers} at the same time. + * + * As a slave, you can specify this {@link DistributedSystemArrayMediator} to be a client slave connecting to master + * server or a server slave accepting master client by overriding the {@link createMediator} method. + * Overrides the {@link createMediator createMediator()} method and return one of them: + * + * - A client slave connecting to master server: + * - {@link MediatorClient} + * - {@link MediatorWebClient} + * - {@link MediatorSharedWorkerClient} + * - A server slave accepting master client: + * - {@link MediatorServer} + * - {@link MediatorWebServer} + * - {@link MediatorDedicatedWorkerServer} + * - {@link MediatorSharedWorkerServer} + * + * #### [Inherited] {@link DistributedSystemArray} + * @copydoc DistributedSystemArray + */ + abstract class DistributedSystemArrayMediator extends DistributedSystemArray { + /** + * @hidden + */ + private mediator_; + /** + * Default Constructor. + */ + constructor(); + /** + * Factory method creating a {@link MediatorSystem} object. + * + * The {@link createMediator createMediator()} is an abstract method creating the {@link MediatorSystem} object. + * + * You know what? this {@link DistributedSystemArrayMediator} class be a master for its slave systems, and be a + * slave to its master system at the same time. The {@link MediatorSystem} object makes it possible; be a slave + * system. This {@link createMediator} determines specific type of the {@link MediatorSystem}. + * + * Overrides the {@link createMediator createMediator()} method to create and return one of them following which + * protocol and which type of remote connection (server or client) will be used: + * + * - A client slave connecting to master server: + * - {@link MediatorClient} + * - {@link MediatorWebClient} + * - {@link MediatorSharedWorkerClient} + * - A server slave accepting master client: + * - {@link MediatorServer} + * - {@link MediatorWebServer} + * - {@link MediatorDedicatedWorkerServer} + * - {@link MediatorSharedWorkerServer} + * + * @return A newly created {@link MediatorSystem} object. + */ + protected abstract createMediator(): parallel.MediatorSystem; + /** + * Start mediator. + * + * If the {@link getMediator mediator} is a type of server, then opens the server accepting master client. + * Otherwise, the {@link getMediator mediator} is a type of client, then connects the master server. + */ + protected startMediator(): void; + /** + * Get {@link MediatorSystem} object. + * + * When you need to send an {@link Invoke} message to the master system of this + * {@link DistributedSystemArrayMediator}, then send to the {@link MediatorSystem} through this + * {@link getMediator}. + * + * ```typescript + * this.getMediator().sendData(...); + * ``` + * + * @return The {@link MediatorSystem} object. + */ + getMediator(): parallel.MediatorSystem; + /** + * @hidden + */ + protected _Complete_history(history: slave.InvokeHistory): boolean; + } +} +declare namespace samchon.protocol { + /** + * @hidden + */ + namespace socket { + type socket = any; + type server = any; + type http_server = any; + } + /** + * @hidden + */ + namespace websocket { + type connection = any; + type request = any; + type IMessage = any; + type ICookie = any; + type client = any; + } +} +declare namespace samchon.protocol { + /** + * @hidden + */ + abstract class _CommunicatorBase implements ICommunicator { + /** + * @hidden + */ + protected listener_: IProtocol; + /** + * @inheritdoc + */ + onClose: Function; + /** + * @hidden + */ + protected connected_: boolean; + /** + * @hidden + */ + private binary_invoke_; + /** + * @hidden + */ + private binary_parameters_; + /** + * @hidden + */ + private unhandled_invokes_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from *listener*. + * + * @param listener An {@link IProtocol} object to listen {@link Invoke} messages. + */ + constructor(listener: IProtocol); + /** + * @inheritdoc + */ + abstract close(): void; + /** + * @inheritdoc + */ + isConnected(): boolean; + /** + * @hidden + */ + protected _Is_binary_invoke(): boolean; + /** + * @inheritdoc + */ + abstract sendData(invoke: Invoke): void; + /** + * @inheritdoc + */ + replyData(invoke: Invoke): void; + /** + * @hidden + */ + protected _Handle_string(str: string): void; + /** + * @hidden + */ + protected _Handle_binary(binary: Uint8Array): void; + } +} +declare namespace samchon.protocol { + /** + * A communicator following Samchon Framework's own protocol. + * + * {@link Communicator} is an abstract class following Samchon Framework's own protocol. This {@link Communicator} + * class is specified to {@link ServerConnector} and {@link ClientDriver} whether the remote system is a server (that + * my system is connecting to) or a client (a client conneting to to my server). + * + * Note that, if one of this or remote system is web-browser based, then you don't have to use this + * {@link Communicator} class who follows Samchon Framework's own protocol. Web-browser supports only Web-socket + * protocol. Thus in that case, you have to use {@link WebCommunicator} instead. + * + * #### [Inherited] {@link ICommunicator} + * @copydoc ICommunicator + */ + abstract class Communicator extends _CommunicatorBase { + /** + * @hidden + */ + protected socket_: socket.socket; + /** + * @hidden + */ + private header_bytes_; + /** + * @hidden + */ + private data_; + /** + * @hidden + */ + private data_index_; + /** + * @hidden + */ + private listening_; + /** + * @inheritdoc + */ + close(): void; + /** + * @hidden + */ + protected _Start_listen(): void; + /** + * @hidden + */ + private _Handle_error(); + /** + * @hidden + */ + private _Handle_close(); + /** + * @inheritdoc + */ + sendData(invoke: Invoke): void; + /** + * @hidden + */ + private _Listen_piece(piece); + /** + * @hidden + */ + private _Listen_header(piece, piece_index); + /** + * @hidden + */ + private _Listen_data(piece, piece_index); + } +} +declare namespace samchon.protocol { + /** + * Communicator with remote client. + * + * {@link ClientDriver} is a class taking full charge of network communication with remote client who follows Samchon + * Framework's own protocol. This {@link ClientDriver} object is always created by {@link Server} class. When you got + * this {@link ClientDriver} object from the {@link Server.addClient Server.addClient()}, then specify + * {@link IProtocol listener} with the {@link ClientDriver.listen ClientDriver.listen()} method. + * + * #### [Inherited] {@link IClientDriver} + * @copydoc IClientDriver + */ + class ClientDriver extends Communicator implements IClientDriver { + /** + * Construct from a socket. + */ + constructor(socket: socket.socket); + /** + * @inheritdoc + */ + listen(listener: IProtocol): void; + } +} +declare namespace samchon.protocol { + /** + * A communicator for shared worker. + * + * {@link DedicatedWorkerCommunicator} is an abstract class for communication between DedicatedWorker and Web-browser. + * This {@link DedicatedWorkerCommunicator} is specified to {@link DedicatedWorkerServerConnector} and + * {@link DedicatedWorkerClientDriver} whether the remote system is a server (that my system is connecting to) or a + * client (a client conneting to to my server). + * + * #### Why DedicatedWorker be a server? + * In JavaScript environment, there's no way to implement multi-threading function. Instead, JavaScript supports the + * **Worker**, creating a new process. However, the **Worker** does not shares memory addresses. To integrate the + * **Worker** with its master, only communication with string or binary data is allowed. Doesn't it seem like a network + * communication? Furthermore, there's not any difference between the worker communication and network communication. + * It's the reason why Samchon Framework considers the **Worker** as a network node. + * + * The class {@link DedicatedWorkerCommunicator} is designed make such relationship. From now on, DedicatedWorker is a + * {@link DedicatedWorkerServer server} and {@link DedicatedWorkerServerConnector browser} is a client. Integrate the + * server and clients with this {@link DedicatedWorkerCommunicator}. + * + * #### [Inherited] {@link ICommunicator} + * @copydoc ICommunicator + */ + abstract class DedicatedWorkerCommunicator extends _CommunicatorBase { + /** + * @hidden + */ + protected _Handle_message(event: MessageEvent): void; + } +} +declare namespace samchon.protocol { + /** + * Communicator with master web-browser. + * + * {@link DedicatedWorkerClientDriver} is a class taking full charge of network communication with web browsers. This + * {@link DedicatedWorkerClientDriver} object is always created by {@link DedicatedWorkerServer} class. When you got + * this {@link DedicatedWorkerClientDriver} object from + * {@link DedicatedWorkerServer.addClient DedicatedWorkerServer.addClient()}, then specify {@link IProtocol listener} + * with the {@link DedicatedWorkerClientDriver.listen DedicatedWorkerClientDriver.listen()} method. + * + * #### Why DedicatedWorker be a server? + * In JavaScript environment, there's no way to implement multi-threading function. Instead, JavaScript supports the + * **Worker**, creating a new process. However, the **Worker** does not shares memory addresses. To integrate the + * **Worker** with its master, only communication with string or binary data is allowed. Doesn't it seem like a network + * communication? Furthermore, there's not any difference between the worker communication and network communication. + * It's the reason why Samchon Framework considers the **Worker** as a network node. + * + * The class {@link DedicatedWorkerCommunicator} is designed make such relationship. From now on, DedicatedWorker is a + * {@link DedicatedWorkerServer server} and {@link DedicatedWorkerServerConnector browser} is a client. Integrate the + * server and clients with this {@link DedicatedWorkerCommunicator}. + * + * #### [Inherited] {@link IClientDriver} + * @copydoc IClientDriver + */ + class DedicatedWorkerClientDriver extends DedicatedWorkerCommunicator implements IClientDriver { + /** + * Default Constructor. + */ + constructor(); + /** + * @inheritdoc + */ + listen(listener: IProtocol): void; + /** + * @inheritdoc + */ + close(): void; + /** + * @inheritdoc + */ + sendData(invoke: Invoke): void; + } +} +declare namespace samchon.protocol { + /** + * A communicator for shared worker. + * + * {@link SharedWorkerCommunicator} is an abstract class for communication between SharedWorker and Web-browser. This + * {@link SharedWorkerCommunicator} is specified to {@link SharedWorkerServerConnector} and + * {@link SharedWorkerClientDriver} whether the remote system is a server (that my system is connecting to) or a client + * (a client conneting to to my server). + * + * Note that, SharedWorker is a conception only existed in web-browser. This {@link SharedWorkerCommunicator} is not + * supported in NodeJS. Only web-browser environment can utilize this {@link SharedWorkerCommunicator}. + * + * #### Why SharedWorker be a server? + * SharedWorker, it allows only an instance (process) to be created whether the SharedWorker is declared in a browser + * or multiple browsers. To integrate them, messages are being sent and received. Doesn't it seem like a relationship + * between a server and clients? Thus, Samchon Framework consider the SharedWorker as a server and browsers as + * clients. + * + * The class {@link SharedWorkerCommunicator} is designed make such relationship. From now on, SharedWorker is a + * {@link SharedWorkerServer server} and {@link SharedWorkerServerConnector browsers} are clients. Integrate the + * server and clients with this {@link SharedWorkerCommunicator}. + * + * #### [Inherited] {@link ICommunicator} + * @copydoc ICommunicator + */ + abstract class SharedWorkerCommunicator extends _CommunicatorBase { + /** + * @hidden + */ + protected port_: MessagePort; + /** + * @inheritdoc + */ + close(): void; + /** + * @inheritdoc + */ + sendData(invoke: Invoke): void; + /** + * @hidden + */ + protected _Handle_message(event: MessageEvent): void; + } +} +declare namespace samchon.protocol { + /** + * Communicator with remote web-browser. + * + * {@link SharedWorkerClientDriver} is a class taking full charge of network communication with web browsers. This + * {@link SharedWorkerClientDriver} object is always created by {@link SharedWorkerServer} class. When you got this + * {@link SharedWorkerClientDriver} object from {@link SharedWorkerServer.addClient SharedWorkerServer.addClient()}, + * then specify {@link IProtocol listener} with the + * {@link SharedWorkerClientDriver.listen SharedWorkerClientDriver.listen()} method. + * + * #### Why SharedWorker be a server? + * SharedWorker, it allows only an instance (process) to be created whether the SharedWorker is declared in a browser + * or multiple browsers. To integrate them, messages are being sent and received. Doesn't it seem like a relationship + * between a server and clients? Thus, Samchon Framework consider the SharedWorker as a server and browsers as + * clients. + * + * The class {@link SharedWorkerCommunicator} is designed make such relationship. From now on, SharedWorker is a + * {@link SharedWorkerServer server} and {@link SharedWorkerServerConnector browsers} are clients. Integrate the + * server and clients with this {@link SharedWorkerCommunicator}. + * + * #### [Inherited] {@link IClientDriver} + * @copydoc IClientDriver + */ + class SharedWorkerClientDriver extends SharedWorkerCommunicator implements IClientDriver { + /** + * @hidden + */ + private listening_; + /** + * Construct from a MessagePort object. + */ + constructor(port: MessagePort); + /** + * @inheritdoc + */ + listen(listener: IProtocol): void; + } +} +declare namespace samchon.protocol { + /** + * A communicator following Web-socket protocol. + * + * {@link WebCommunicator} is an abstract class following Web-socket protocol. This {@link WebCommunicator} class is + * specified to {@link WebServerConnector} and {@link WebClientDriver} whether the remote system is a server (that my + * system is connecting to) or a client (a client conneting to to my server). + * + * Note that, one of this or remote system is web-browser based, then there's not any alternative choice. Web browser + * supports only Web-socket protocol. In that case, you've use this {@link WebCommunicator} class. + * + * #### [Inherited] {@link ICommunicator} + * @copydoc ICommunicator + */ + abstract class WebCommunicator extends _CommunicatorBase { + /** + * @hidden + */ + protected connection_: websocket.connection; + /** + * @inheritdoc + */ + close(): void; + /** + * @inheritdoc + */ + sendData(invoke: Invoke): void; + /** + * @hidden + */ + protected _Handle_message(message: websocket.IMessage): void; + /** + * @hidden + */ + protected _Handle_close(): void; + } +} +declare namespace samchon.protocol { + /** + * Communicator with remote web-client. + * + * {@link WebClientDriver} is a class taking full charge of network communication with remote client who follows + * Web-socket protocol. This {@link WebClientDriver} object is always created by {@link WebServer} class. When you + * got this {@link WebClientDriver} object from the {@link WebServer.addClient WebServer.addClient()}, then specify + * {@link IProtocol listener} with the {@link WebClientDriver.listen WebClientDriver.listen()} method. + * + * Unlike other protocol, Web-socket protocol's clients notify two parameters on their connection; + * {@link getSessionID session-id} and {@link getPath path}. The {@link getSessionID session-id} can be used to + * identify *user* of each client, and the {@link getPath path} can be used which type of *service* that client wants. + * In {@link service} module, you can see the best utilization case of them. + * - {@link service.User}: utlization of the {@link getSessionID session-id}. + * - {@link service.Service}: utilization of the {@link getPath path}. + * + * #### [Inherited] {@link IClientDriver} + * @copydoc IClientDriver + */ + class WebClientDriver extends WebCommunicator implements IClientDriver { + /** + * @hidden + */ + private path_; + /** + * @hidden + */ + private session_id_; + /** + * @hidden + */ + private listening_; + /** + * Initialization Constructor. + * + * @param connection Connection driver, a socket for web-socket. + * @param path Requested path. + * @param session_id Session ID, an identifier of the remote client. + */ + constructor(connection: websocket.connection, path: string, session_id: string); + /** + * @inheritdoc + */ + listen(listener: IProtocol): void; + /** + * Get requested path. + */ + getPath(): string; + /** + * Get session ID, an identifier of the remote client. + */ + getSessionID(): string; + } +} +declare namespace samchon.protocol { + /** + * An interface for communicator with remote client. + * + * {@link IClientDriver} is a type of {@link ICommunicator}, specified for communication with remote client who has + * connected in a {@link IServer server}. It takes full charge of network communication with the remote client. + * + * The {@link IClientDriver} object is created and delivered from {@link IServer} and + * {@link IServer.addClient IServer.addClient()}. Those are derived types from this {@link IClientDriver}, being + * created by the matched {@link IServer} object. + * + * Protocol | Derived Type | Created By + * ------------------------|-------------------------------------|---------------------------- + * Samchon Framework's own | {@link ClientDriver} | {@link Server} + * Web-socket protocol | {@link WebClientDriver} | {@link WebServer} + * DedicatedWorker | {@link DedicatedWorkerClinetDriver} | {@link DedicatedWorkerServer} + * SharedWorker | {@link SharedWorkerClientDriver} | {@link SharedWorkerServer} + * + * When you've got an {@link IClientDriver} object from the {@link IServer.addClient IServer.addClient()}, then + * specify {@link IProtocol listener} with {@link IClient.listen IClient.listen()}. Whenever a replied message comes + * from the remote system, the message will be converted to an {@link Invoke} class and the {@link Invoke} object + * will be shifted to the {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} method. + * Below code is an example specifying and managing the {@link IProtocol listener} objects. + * + * - https://github.com/samchon/framework-examples/blob/master/calculator/calculator-server.ts + * + * + * + * + * + * @see {@link IServer}, {@link IProtocol} + * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iclientdriver) + * @author Jeongho Nam + */ + interface IClientDriver extends ICommunicator { + /** + * Listen message from the newly connected client. + * + * Starts listening message from the newly connected client. Replied message from the connected client will be + * converted to {@link Invoke} classes and shifted to the *listener*'s {@link IProtocol.replyData replyData()} + * method. + * + * @param listener A listener object to listen replied message from newly connected client in + * {@link IProtocol.replyData replyData()} as an {@link Invoke} object. + */ + listen(listener: IProtocol): void; + } +} +declare namespace samchon.protocol { + /** + * An interface taking full charge of network communication. + * + * {@link ICommunicator} is an interface for communicator classes who take full charge of network communication with + * remote system, without reference to whether the remote system is a server or a client. Type of the + * {@link ICommunicator} is specified to {@link IServerConnector} and {@link IClientDriver} whether the remote system + * is a server (that I've to connect) or a client (a client connected to my server). + * + * Whenever a replied message comes from the remote system, the message will be converted to an {@link Invoke} class + * and the {@link Invoke} object will be shifted to the {@link IProtocol listener}'s + * {@link IProtocol.replyData IProtocol.replyData()} method. + * + * + * + * + * + * @see {@link IClientDriver}, {@link IServerConnector}, {@link IProtocol} + * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#icommunicator) + * @author Jeongho Nam + */ + interface ICommunicator extends IProtocol { + /** + * Callback function for connection closed. + */ + onClose: Function; + /** + * Close connection. + */ + close(): void; + /** + * Test connection. + * + * Test whether this {@link ICommunicator communicator} object is connected with the remote system. If the + * connection is alive, then returns ```true```. Otherwise, the connection is not alive or this + * {@link ICommunicator communicator has not connected with the remote system yet, then returns ```false```. + * + * @return true if connected, otherwise false. + */ + isConnected(): boolean; + /** + * Send message. + * + * Send {@link Invoke} message to remote system. + * + * @param invoke An {@link Invoke} message to send. + */ + sendData(invoke: protocol.Invoke): void; + /** + * Handle replied message. + * + * Handles replied {@link Invoke} message recived from remove system. The {@link Invoke} message will be shifted + * to the {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} by this method. + * + * @param invoke An {@link Invoke} message received from remote system. + */ + replyData(invoke: protocol.Invoke): void; + } +} +declare namespace samchon.protocol { + /** + * An interface for server connector. + * + * {@link IServerConnector} is a type of {@link ICommunicator}, specified for server connector classes who connect to + * the remote server as a client. {@link IServerConnector} provides {@link connect connection method} and takes full + * charge of network communication with the remote server. + * + * Declare specific type of {@link IServerConnector} from {@link IProtocol listener} and call the + * {@link connect connect()} method. Then whenever a replied message comes from the remote system, the message will + * be converted to an {@link Invoke} object and the {@link Invoke} object will be shifted to the + * {@link IProtocol listener}'s {@link IProtocol.replyData IProtocol.replyData()} method. Below code is an example + * connecting to remote server and interacting with it. + * + * - https://github.com/samchon/framework-examples/blob/master/calculator/calculator-application.ts + * + * Note that, protocol of this client and remote server must be matched. Thus, before determining specific type of + * this {@link IServerConnector}, you've to consider which protocol and type the remote server follows. + * + * Protocol | Derived Type | Connect to + * ------------------------|----------------------------------------|------------------------------- + * Samchon Framework's own | {@link ServerConnector} | {@link Server} + * Web-socket protocol | {@link WebServerConnector} | {@link WebServer} + * DedicatedWorker | {@link DedicatedWorkerServerConnector} | {@link DedicatedWorkerServer} + * SharedWorker | {@link SharedWorkerServerConnector} | {@link SharedWorkerServer} + * + * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_basic_components.png) + * + * @see {@link IServer}, {@link IProtocol} + * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserverconnector) + * @author Jeongho Nam + */ + interface IServerConnector extends ICommunicator { + /** + * Callback function for connection completed. + * + * When you call {@link connect connect()} and the connection has completed, then this call back function + * {@link onConnect} will be called. Note that, if the listener of this {@link onConnect} is a member method of + * some class, then you've use the ```bind```. + */ + onConnect: Function; + /** + * Connect to a server. + * + * Connects to a server with specified *host* address and *port* number. After the connection has + * succeeded, callback function {@link onConnect} is called. Listening data from the connected server also begins. + * Replied messages from the connected server will be converted to {@link Invoke} classes and will be shifted to + * the {@link WebCommunicator.listener listener}'s {@link IProtocol.replyData replyData()} method. + * + * If the connection fails immediately, either an event is dispatched or an exception is thrown: an error + * event is dispatched if a host was specified, and an exception is thrown if no host was specified. Otherwise, + * the status of the connection is reported by an event. If the socket is already connected, the existing + * connection is closed first. + * + * @param ip The name or IP address of the host to connect to. + * If no host is specified, the host that is contacted is the host where the calling file resides. + * If you do not specify a host, use an event listener to determine whether the connection was + * successful. + * @param port The port number to connect to. + */ + connect(ip: string, port: number): void; + } +} +declare namespace samchon.protocol { + /** + * A server connector for DedicatedWorker. + * + * {@link DedicatedWorkerServerConnector} is a class connecting to SharedWorker and taking full charge of network + * communication with the SharedWorker. Create an {@link DedicatedWorkerServer} instance from the + * {@IProtocol listener} and call the {@link connect connect()} method. + * + * #### Why DedicatedWorker be a server? + * In JavaScript environment, there's no way to implement multi-threading function. Instead, JavaScript supports the + * **Worker**, creating a new process. However, the **Worker** does not shares memory addresses. To integrate the + * **Worker** with its master, only communication with string or binary data is allowed. Doesn't it seem like a network + * communication? Furthermore, there's not any difference between the worker communication and network communication. + * It's the reason why Samchon Framework considers the **Worker** as a network node. + * + * The class {@link DedicatedWorkerCommunicator} is designed make such relationship. From now on, DedicatedWorker is a + * {@link DedicatedWorkerServer server} and {@link DedicatedWorkerServerConnector browser} is a client. Integrate the + * server and clients with this {@link DedicatedWorkerCommunicator}. + * + * #### [Inherited] {@link IServerConnector} + * @copydoc IServerConnector + */ + class DedicatedWorkerServerConnector extends DedicatedWorkerCommunicator implements IServerConnector { + /** + * @hidden + */ + private worker_; + /** + * @inheritdoc + */ + onConnect: Function; + /** + * Construct from *listener*. + * + * @param listener A listener object to listen replied message from newly connected client in + * {@link IProtocol.replyData replyData()} as an {@link Invoke} object. + */ + constructor(listener: IProtocol); + /** + * @inheritdoc + */ + connect(jsFile: string): void; + /** + * @inheritdoc + */ + close(): void; + /** + * @inheritdoc + */ + sendData(invoke: Invoke): void; + } +} +declare namespace samchon.protocol { + /** + * Server connnector. + * + * {@link ServerConnector} is a class connecting to remote server who follows Samchon Framework's own protocol and + * taking full charge of network communication with the remote server. Create a {@link ServerConnector} instance from + * the {@IProtocol listener} and call the {@link connect connect()} method. + * + * #### [Inherited] {@link IServerConnector} + * @copydoc IServerConnector + */ + class ServerConnector extends Communicator implements IServerConnector { + /** + * @inheritdoc + */ + onConnect: Function; + /** + * Construct from *listener*. + * + * @param listener A listener object to listen replied message from newly connected client in + * {@link IProtocol.replyData replyData()} as an {@link Invoke} object. + */ + constructor(listener: IProtocol); + /** + * @inheritdoc + */ + connect(ip: string, port: number): void; + /** + * @hidden + */ + private _Handle_connect(...arg); + /** + * @hidden + */ + private _Send_dummy_packet_repeatedly(); + } +} +declare namespace samchon.protocol { + /** + * A server connector for SharedWorker. + * + * {@link SharedWorkerServerConnector} is a class connecting to SharedWorker and taking full charge of network + * communication with the SharedWorker. Create an {@link SharedWorkerServerConnector} instance from the + * {@IProtocol listener} and call the {@link connect connect()} method. + * + * #### Why SharedWorker be a server? + * SharedWorker, it allows only an instance (process) to be created whether the SharedWorker is declared in a browser + * or multiple browsers. To integrate them, messages are being sent and received. Doesn't it seem like a relationship + * between a server and clients? Thus, Samchon Framework consider the SharedWorker as a server and browsers as + * clients. + * + * The class {@link SharedWorkerCommunicator} is designed make such relationship. From now on, SharedWorker is a + * {@link SharedWorkerServer server} and {@link SharedWorkerServerConnector browsers} are clients. Integrate the + * server and clients with this {@link SharedWorkerCommunicator}. + * + * #### [Inherited] {@link IServerConnector} + * @copydoc IServerConnector + */ + class SharedWorkerServerConnector extends SharedWorkerCommunicator implements IServerConnector { + /** + * @inheritdoc + */ + onConnect: Function; + /** + * Construct from *listener*. + * + * @param listener A listener object to listen replied message from newly connected client in + * {@link IProtocol.replyData replyData()} as an {@link Invoke} object. + */ + constructor(listener: IProtocol); + /** + * Connect to a SharedWorker. + * + * Connects to a server with specified *jstFile* path. If a SharedWorker instance of the *jsFile* is not + * constructed yet, then the SharedWorker will be newly constructed. Otherwise the SharedWorker already exists, + * then connect to the SharedWorker. After those processes, callback function {@link onConnect} is called. + * Listening data from the connected server also begins. Replied messages from the connected server will be + * converted to {@link Invoke} classes and will be shifted to the {@link WebCommunicator.listener listener}'s + * {@link IProtocol.replyData replyData()} method. + * + * If the connection fails immediately, either an event is dispatched or an exception is thrown: an error + * event is dispatched if a host was specified, and an exception is thrown if no host was specified. Otherwise, + * the status of the connection is reported by an event. If the socket is already connected, the existing + * connection is closed first. + * + * @param jsFile Path of JavaScript file to execute who defines SharedWorker. + */ + connect(jsFile: string): void; + } +} +declare namespace samchon.protocol { + /** + * A server connector for web-socket protocol. + * + * {@link WebServerConnector} is a class connecting to remote server who follows Web-socket protocol and taking full + * charge of network communication with the remote server. Create an {@link WebServerConnector} instance from the + * {@IProtocol listener} and call the {@link connect connect()} method. + * + * #### [Inherited] {@link IServerConnector} + * @copydoc IServerConnector + */ + class WebServerConnector extends WebCommunicator implements IServerConnector { + /** + * @hidden + */ + private browser_socket_; + /** + * @hidden + */ + private node_client_; + /** + * @inheritdoc + */ + onConnect: Function; + /** + * Construct from *listener*. + * + * @param listener A listener object to listen replied message from newly connected client in + * {@link IProtocol.replyData replyData()} as an {@link Invoke} object. + */ + constructor(listener: IProtocol); + /** + * Connect to a web server. + * + * Connects to a server with specified *host* address, *port* number and *path*. After the connection has + * succeeded, callback function {@link onConnect} is called. Listening data from the connected server also begins. + * Replied messages from the connected server will be converted to {@link Invoke} classes and will be shifted to + * the {@link WebCommunicator.listener listener}'s {@link IProtocol.replyData replyData()} method. + * + * If the connection fails immediately, either an event is dispatched or an exception is thrown: an error + * event is dispatched if a host was specified, and an exception is thrown if no host was specified. Otherwise, + * the status of the connection is reported by an event. If the socket is already connected, the existing + * connection is closed first. + * + * @param ip The name or IP address of the host to connect to. + * If no host is specified, the host that is contacted is the host where the calling file resides. + * If you do not specify a host, use an event listener to determine whether the connection was + * successful. + * @param port The port number to connect to. + * @param path Path of service which you want. + */ + connect(ip: string, port: number, path?: string): void; + /** + * @inheritdoc + */ + close(): void; + /** + * @inheritdoc + */ + sendData(invoke: Invoke): void; + /** + * @hidden + */ + private _Handle_browser_connect(event); + /** + * @hidden + */ + private _Handle_browser_message(event); + /** + * @hidden + */ + private _Handle_node_connect(connection); + } +} +declare namespace samchon.protocol { + /** + * A container of entity, and it's a type of entity, too. + * + * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_message_protocol.png) + * + * @handbook [Protocol - Standard Message](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Standard_Message) + * @author Jeongho Nam + */ + interface IEntityGroup extends IEntity, std.base.Container { + /** + * Construct data of the Entity from an XML object. + * + * Constructs the EntityArray's own member variables only from the input XML object. + * + * Do not consider about constructing children Entity objects' data in EntityArray::construct(). + * Those children Entity objects' data will constructed by their own construct() method. Even insertion + * of XML objects representing children are done by abstract method of EntityArray::toXML(). + * + * Constructs only data of EntityArray's own. + */ + construct(xml: library.XML): void; + /** + * Factory method of a child Entity. + * + * EntityArray::createChild() is a factory method creating a new child Entity which is belonged + * to the EntityArray. This method is called by EntityArray::construct(). The children construction + * methods Entity::construct() will be called by abstract method of the EntityArray::construct(). + * + * @return A new child Entity belongs to EntityArray. + */ + createChild(xml: library.XML): T; + /** + * Get iterator to element. + * + * Searches the container for an element with a identifier equivalent to *key* and returns an + * iterator to it if found, otherwise it returns an iterator to {@link end end()}. + * + * Two keys are considered equivalent if the container's comparison object returns false reflexively + * (i.e., no matter the order in which the elements are passed as arguments). + * + * Another member functions, {@link has has()} and {@link count count()}, can be used to just check + * whether a particular *key* exists. + * + * @param key Key to be searched for + * @return An iterator to the element, if an element with specified *key* is found, or + * {@link end end()} otherwise. + */ + /** + * Whether have the item or not. + * + * Indicates whether a map has an item having the specified identifier. + * + * @param key Key value of the element whose mapped value is accessed. + * + * @return Whether the map has an item having the specified identifier. + */ + has(key: any): boolean; + /** + * Count elements with a specific key. + * + * Searches the container for elements whose key is *key* and returns the number of elements found. + * + * @param key Key value to be searched for. + * + * @return The number of elements in the container with a *key*. + */ + count(key: any): number; + /** + * Get an element + * + * Returns a reference to the mapped value of the element identified with *key*. + * + * @param key Key value of the element whose mapped value is accessed. + * + * @throw exception out of range + * + * @return A reference object of the mapped value (_Ty) + */ + get(key: any): T; + /** + * A tag name of children objects. + */ + CHILD_TAG(): string; + /** + * Get an XML object represents the EntityArray. + * + * Archives the EntityArray's own member variables only to the returned XML object. + * + * Do not consider about archiving children Entity objects' data in EntityArray::toXML(). + * Those children Entity objects will converted to XML object by their own toXML() method. The + * insertion of XML objects representing children are done by abstract method of + * EntityArray::toXML(). + * + * Archives only data of EntityArray's own. + */ + toXML(): library.XML; + } + /** + * @hidden + */ + namespace IEntityGroup { + /** + * @hidden + */ + function construct(entityGroup: IEntityGroup, xml: library.XML, ...prohibited_names: string[]): void; + /** + * @hidden + */ + function toXML(group: IEntityGroup, ...prohibited_names: string[]): library.XML; + function has(entityGroup: IEntityGroup, key: any): boolean; + function count(entityGroup: IEntityGroup, key: any): number; + function get(entityGroup: IEntityGroup, key: any): T; + } +} +declare namespace samchon.protocol { + /** + * @inheritdoc + */ + abstract class EntityArray extends std.Vector implements IEntityGroup { + /** + * @inheritdoc + */ + construct(xml: library.XML): void; + /** + * @inheritdoc + */ + abstract createChild(xml: library.XML): T; + /** + * @inheritdoc + */ + key(): any; + /** + * @inheritdoc + */ + has(key: any): boolean; + /** + * @inheritdoc + */ + count(key: any): number; + /** + * @inheritdoc + */ + get(key: any): T; + /** + * @inheritdoc + */ + abstract TAG(): string; + /** + * @inheritdoc + */ + abstract CHILD_TAG(): string; + /** + * @inheritdoc + */ + toXML(): library.XML; + } +} +declare namespace samchon.protocol { + /** + * @inheritdoc + */ + abstract class EntityList extends std.List implements IEntityGroup { + /** + * @inheritdoc + */ + construct(xml: library.XML): void; + /** + * @inheritdoc + */ + abstract createChild(xml: library.XML): T; + /** + * @inheritdoc + */ + key(): any; + /** + * @inheritdoc + */ + has(key: any): boolean; + /** + * @inheritdoc + */ + count(key: any): number; + /** + * @inheritdoc + */ + get(key: any): T; + /** + * @inheritdoc + */ + abstract TAG(): string; + /** + * @inheritdoc + */ + abstract CHILD_TAG(): string; + /** + * @inheritdoc + */ + toXML(): library.XML; + } +} +declare namespace samchon.protocol { + /** + * @inheritdoc + */ + abstract class EntityDeque extends std.Deque implements IEntityGroup { + /** + * @inheritdoc + */ + construct(xml: library.XML): void; + /** + * @inheritdoc + */ + abstract createChild(xml: library.XML): T; + /** + * @inheritdoc + */ + key(): any; + /** + * @inheritdoc + */ + has(key: any): boolean; + /** + * @inheritdoc + */ + count(key: any): number; + /** + * @inheritdoc + */ + get(key: any): T; + /** + * @inheritdoc + */ + abstract TAG(): string; + /** + * @inheritdoc + */ + abstract CHILD_TAG(): string; + /** + * @inheritdoc + */ + toXML(): library.XML; + } +} +declare namespace samchon.protocol { + /** + * Standard message of network I/O. + * + * {@link Invoke} is a class used in network I/O in protocol package of Samchon Framework. + * + * The Invoke message has an XML structure like the result screen of provided example in below. + * We can enjoy lots of benefits by the normalized and standardized message structure used in + * network I/O. + * + * The greatest advantage is that we can make any type of network system, even how the system + * is enourmously complicated. As network communication message is standardized, we only need to + * concentrate on logical relationships between network systems. We can handle each network system + * like a object (class) in OOD. And those relationships can be easily designed by using design + * pattern. + * + * In Samchon Framework, you can make any type of network system with basic componenets + * (IProtocol, IServer and ICommunicator) by implemens or inherits them, like designing + * classes of S/W architecture. + * + * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_message_protocol.png) + * + * @see {@link IProtocol} + * @author Jeongho Nam + */ + class Invoke extends EntityArray { + /** + * Listener, represent function's name. + */ + private listener; + /** + * Default Constructor. + */ + constructor(); + constructor(listener: string); + /** + * Copy Constructor. + * + * @param invoke + */ + constructor(invoke: Invoke); + /** + * Construct from listener and parametric values. + * + * @param listener + * @param parameters + */ + constructor(listener: string, ...parameters: Array); + /** + * @inheritdoc + */ + createChild(xml: library.XML): InvokeParameter; + /** + * Get listener. + */ + getListener(): string; + /** + * Get arguments for Function.apply(). + * + * @return An array containing values of the contained parameters. + */ + getArguments(): Array; + /** + * Apply to a matched function. + * + * @param obj Target object to find matched function. + * @return Whether succeded to find matched function. + */ + apply(obj: Object): boolean; + /** + * Apply to a function. + * + * @param thisArg Owner of the function. + * @param func Function to call. + */ + apply(thisArg: Object, func: Function): void; + /** + * @inheritdoc + */ + TAG(): string; + /** + * @inheritdoc + */ + CHILD_TAG(): string; + } +} +declare namespace samchon.protocol { + /** + * A parameter belongs to an Invoke. + * + * ![Class Diagram](http://samchon.github.io/framework/images/design/ts_class_diagram/protocol_message_protocol.png) + * + * @author Jeongho Nam + */ + class InvokeParameter extends Entity { + /** + * Name of the parameter. + * + * @details Optional property, can be omitted. + */ + protected name: string; + /** + * Type of the parameter. + */ + protected type: string; + /** + * Value of the parameter. + */ + protected value: boolean | number | string | library.XML | Uint8Array; + /** + * Default Constructor. + */ + constructor(); + constructor(val: boolean); + constructor(val: number); + constructor(val: string); + constructor(val: library.XML); + constructor(val: Uint8Array); + /** + * Construct from variable name and number value. + * + * @param name + * @param val + */ + constructor(name: string, val: boolean); + constructor(name: string, val: number); + constructor(name: string, val: string); + constructor(name: string, val: library.XML); + constructor(name: string, val: Uint8Array); + /** + * @inheritdoc + */ + construct(xml: library.XML): void; + setValue(value: boolean): void; + setValue(value: number): void; + setValue(value: string): void; + setValue(value: library.XML): void; + setValue(value: Uint8Array): void; + /** + * @inheritdoc + */ + key(): any; + /** + * Get name. + */ + getName(): string; + /** + * Get type. + */ + getType(): string; + /** + * Get value. + */ + getValue(): any; + /** + * @inheritdoc + */ + TAG(): string; + /** + * @inheritdoc + */ + toXML(): library.XML; + } +} +declare namespace samchon.protocol { + /** + * An interface for {@link Invoke} message chain. + * + * {@link IProtocol} is an interface for {@link Invoke} message, which is standard message of network I/O in + * *Samchon Framework*, chain. The {@link IProtocol} interface is used to network drivers and some classes which are + * in a relationship of *Chain of Responsibility Pattern* with those network drivers. + * + * Implements {@link IProtocol} if the class sends and handles {@link Invoke} messages. Looking around source codes of + * the *Samchon Framework*, especially *Templates*, you can find out that all the classes and modules handling + * {@link Invoke} messages are always implementing this {@link IProtocol}. + * + * + * + * + * + * @see {@link Invoke} + * @handbook https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iprotocol + * @author Jeongho Nam + */ + interface IProtocol { + /** + * Sending message. + * + * Sends message to related system or shifts the responsibility to chain. + * + * @param invoke Invoke message to send + */ + replyData(invoke: Invoke): void; + /** + * Handling replied message. + * + * Handles replied message or shifts the responsibility to chain. + * + * @param invoke An {@link Invoke} message has received. + */ + sendData(invoke: Invoke): void; + } +} +declare namespace samchon.protocol { + /** + * A DeidcatedWorker server. + * + * The {@link DedicatedWorkerServer} is an abstract class is realized to open a DedicatedWorker server and accept + * web-browser client (master). Extends this {@link DedicatedWorkerServer} class and overrides + * {@link addClient addClient()} method to define what to do with a newly connected + * {@link DedicatedWorkerClientDriver remote client}. + * + * #### Why DedicatedWorker be a server? + * In JavaScript environment, there's no way to implement multi-threading function. Instead, JavaScript supports the + * **Worker**, creating a new process. However, the **Worker** does not shares memory addresses. To integrate the + * **Worker** with its master, only communication with string or binary data is allowed. Doesn't it seem like a network + * communication? Furthermore, there's not any difference between the worker communication and network communication. + * It's the reason why Samchon Framework considers the **Worker** as a network node. + * + * The class {@link DedicatedWorkerCommunicator} is designed make such relationship. From now on, DedicatedWorker is a + * {@link DedicatedWorkerServer server} and {@link DedicatedWorkerServerConnector browser} is a client. Integrate the + * server and clients with this {@link DedicatedWorkerCommunicator}. + * + * #### [Inherited] {@link IServer} + * @copydoc IServer + */ + abstract class DedicatedWorkerServer implements IServer { + /** + * @inheritdoc + */ + abstract addClient(driver: DedicatedWorkerClientDriver): void; + /** + * @inheritdoc + */ + open(): void; + /** + * @inheritdoc + */ + close(): void; + } +} +declare namespace samchon.protocol { + /** + * A substitute {@link DedicatedWorkerServer}. + * + * The {@link DedicatedWorkerServerBase} is a substitute class who subrogates {@link DedicatedWorkerServer}'s + * responsibility. + * + * #### [Inherited] {@link IServerBase} + * @copydoc IServerBase + */ + class DedicatedWorkerServerBase extends DedicatedWorkerServer implements IServerBase { + /** + * @hidden + */ + private hooker_; + /** + * Construct from a *hooker*. + * + * @param hooker A hooker throwing responsibility of server's role. + */ + constructor(hooker: IServer); + /** + * @inheritdoc + */ + addClient(driver: IClientDriver): void; + } +} +declare namespace samchon.protocol { + /** + * An interface for substitute server classes. + * + * {@link IServerBase} is an interface for substitue server classes who subrogate server's role. + * + * The easiest way to defining a server class is to extending one of them below, who implemented the {@link IServer}. + * However, it is impossible (that is, if the class is already extending another class), you can instead implement + * the {@link IServer} interface, create an {@link IServerBase} member, and write simple hooks to route calls into + * the aggregated {@link IServerBase}. + * + * Protocol | {@link IServer} | {@link IServerBase} | {@link IClientDriver} + * ------------------------|-------------------------------|-----------------------------------|------------------------------------- + * Samchon Framework's own | {@link Server} | {@link ServerBase} | {@link ClientDriver} + * Web-socket protocol | {@link WebServer} | {@link WebServerBase} | {@link WebClientDriver} + * DedicatedWorker | {@link DedicatedWorkerServer} | {@link DedicatedWorkerServerBase} | {@link DedicatedWorkerClientDriver} + * SharedWorker | {@link SharedWorkerServer} | {@link SharedWorkerServerBase} | {@link SharedWorkerClientDriver} + * + * After the hooking to aggregated {@link IServerBase} object, overrides {@link addClient addClient()} method who + * accepts a newly connected client as an {@link IClientDriver} object. At last, call {@link open open()} method with + * specified port number. + * + * ```typescript + * class MyServer extends Something implements IServer + * { + * private server_base_: IServerBase = new WebServerBase(this); + * + * public addClient(driver: IClientDriver): void + * { + * // WHAT TO DO WHEN A CLIENT HAS CONNECTED + * } + * + * public open(port: number): void + * { + * this.server_base_.open(); + * } + * public close(): void + * { + * this.server_base_.close(); + * } + * } + * ``` + * + * + * + * + * + * @see {@link IServer}, {@link IClientDriver} + * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserverbase) + * @author Jeongho Nam + */ + interface IServerBase extends IServer { + } +} +declare namespace samchon.protocol { + /** + * A server. + * + * The {@link Server} is an abstract class designed to open a server and accept clients who are following Samchon + * Framework's own protocol. Extends this {@link Server} class and overrides {@link addClient addClient()} method to + * define what to do with newly connected {@link ClientDriver remote clients}. + * + * #### [Inherited] {@link IServer} + * @copydoc Server + */ + abstract class Server implements IServer { + /** + * @hidden + */ + private net_driver_; + /** + * @inheritdoc + */ + abstract addClient(driver: ClientDriver): void; + /** + * @inheritdoc + */ + open(port: number): void; + /** + * @inheritdoc + */ + close(): void; + /** + * @hidden + */ + private _Handle_connect(socket); + } +} +declare namespace samchon.protocol { + /** + * A substitute {@link Server}. + * + * The {@link ServerBase} is a substitute class who subrogates {@link Server}'s responsibility. + * + * #### [Inherited] {@link IServerBase} + * @copydoc IServerBase + */ + class ServerBase extends Server implements IServerBase { + /** + * @hidden + */ + private hooker_; + /** + * Construct from a *hooker*. + * + * @param hooker A hooker throwing responsibility of server's role. + */ + constructor(hooker: IServer); + /** + * @inheritdoc + */ + addClient(driver: IClientDriver): void; + } +} +declare namespace samchon.protocol { + /** + * A SharedWorker server. + * + * The {@link SharedWorker} is an abstract class is realized to open a SharedWorker server and accept web-browser + * clients. Extends this {@link SharedWorkerServer} class and overrides {@link addClient addClient()} method to + * define what to do with newly connected {@link SharedWorkerClientDriver remote clients}. + * + * #### Why SharedWorker be a server? + * SharedWorker, it allows only an instance (process) to be created whether the SharedWorker is declared in a browser + * or multiple browsers. To integrate them, messages are being sent and received. Doesn't it seem like a relationship + * between a server and clients? Thus, Samchon Framework consider the SharedWorker as a server and browsers as + * clients. + * + * The class {@link SharedWorkerCommunicator} is designed make such relationship. From now on, SharedWorker is a + * {@link SharedWorkerServer server} and {@link SharedWorkerServerConnector browsers} are clients. Integrate the + * server and clients with this {@link SharedWorkerCommunicator}. + * + * #### [Inherited] {@link IServer} + * @copydoc IServer + */ + abstract class SharedWorkerServer implements IServer { + /** + * @inheritdoc + */ + abstract addClient(driver: SharedWorkerClientDriver): void; + /** + * @inheritdoc + */ + open(): void; + /** + * @inheritdoc + */ + close(): void; + /** + * @hidden + */ + private _Handle_connect(event); + } +} +declare namespace samchon.protocol { + /** + * A substitute {@link SharedWorkerServer}. + * + * The {@link SharedWorkerServerBase} is a substitute class who subrogates {@link SharedWorkerServer}'s + * responsibility. + * + * #### [Inherited] {@link IServerBase} + * @copydoc IServerBase + */ + class SharedWorkerServerBase extends SharedWorkerServer implements IServerBase { + /** + * @hidden + */ + private hooker_; + /** + * Construct from a *hooker*. + * + * @param hooker A hooker throwing responsibility of server's role. + */ + constructor(hooker: IServer); + /** + * @inheritdoc + */ + addClient(driver: IClientDriver): void; + } +} +declare namespace samchon.protocol { + /** + * A web server. + * + * The {@link WebServer} is an abstract class designed to open a server and accept clients who are following + * web-socket protocol. Extends this {@link WebServer} class and overrides {@link addClient addClient()} method to + * define what to do with newly connected {@link WebClientDriver remote clients}. + * + * #### [Inherited] {@link IServer} + * @copydoc IServer + */ + abstract class WebServer implements IServer { + /** + * @hidden + */ + private http_server_; + /** + * @hidden + */ + private sequence_; + /** + * @hidden + */ + private my_port_; + /** + * Default Constructor. + */ + constructor(); + /** + * @inheritdoc + */ + abstract addClient(driver: WebClientDriver): void; + /** + * @inheritdoc + */ + open(port: number): void; + /** + * @inheritdoc + */ + close(): void; + /** + * @hidden + */ + private _Handle_request(request); + /** + * @hidden + */ + private _Fetch_session_id(cookies); + /** + * @hidden + */ + private _Issue_session_id(); + } +} +declare namespace samchon.protocol { + /** + * A substitute {@link WebServer}. + * + * The {@link WebServerBase} is a substitute class who subrogates {@link WebServer}'s responsibility. + * + * #### [Inherited] {@link IServerBase} + * @copydoc IServerBase + */ + class WebServerBase extends WebServer implements IServerBase { + /** + * @hidden + */ + private hooker_; + /** + * Construct from a *hooker*. + * + * @param hooker A hooker throwing responsibility of server's role. + */ + constructor(hooker: IServer); + /** + * @inheritdoc + */ + addClient(driver: IClientDriver): void; + } +} +declare namespace samchon.protocol { + /** + * An interface for a server. + * + * {@link IServer} is an interfaec for server classes who are providing methods for {@link open opening a server} and + * {@link IClientDriver accepting clients}. + * + * To open a server, extends one of derived class under below considedring which protocol to follow first. At next, + * overrides {@link addClient addClient()} method who accepts a newly connected client as an {@link IClientDriver} + * object. Then at last, call {@link open open()} method with specified port number. + * + * Protocol | Derived Type | Related {@link IClientDriver} + * ------------------------|-------------------------------|------------------------------------- + * Samchon Framework's own | {@link Server} | {@link ClientDriver} + * Web-socket protocol | {@link WebServer} | {@link WebClientDriver} + * DedicatedWorker | {@link DedicatedWorkerServer} | {@link DedicatedWorkerClientDriver} + * SharedWorker | {@link SharedWorkerServer} | {@link SharedWorkerClientDriver} + * + * Below codes and classes will be good examples for comprehending how to open a server and handle remote clients. + * - https://github.com/samchon/framework-examples/blob/master/calculator/calculator-server.ts + * - https://github.com/samchon/framework-examples/blob/master/chat-server/server.ts + * - {@link service.Server} + * - {@link external.ExternalClientArray} + * - {@link slave.SlaveServer} + * + * If you're embarrased because your class already extended another one, then use {@link IServerBase}. + * + * + * + * + * + * @see {@link IClientDriver}, {@link IServerBase} + * @handbook [Protocol - Basic Components](https://github.com/samchon/framework/wiki/TypeScript-Protocol-Basic_Components#iserver) + * @author Jeongho Nam + */ + interface IServer { + /** + * Open server. + * + * @param port Port number to open. + */ + open(port: number): void; + /** + * Close server. + * + * Close opened server. All remote clients, have connected with this server, are also closed and their call back + * functions, for closed connection, {@link IClientDriver.onClose} are also called. + */ + close(): void; + /** + * Add a newly connected remote client. + * + * The {@link addClient addClient()} is an abstract method being called when a remote client is newly connected + * with {@link IClientDriver} object who communicates with the remote system. Overrides this method and defines + * what to do with the *driver*, a newly connected remote client. + * + * Below methods and example codes may be good for comprehending how to utilize this {@link addClient} method. + * + * - https://github.com/samchon/framework-examples/blob/master/calculator/calculator-server.ts + * - https://github.com/samchon/framework-examples/blob/master/chat-server/server.ts + * - {@link service.Server.addClient} + * - {@link external.ExternalClientArray.addClient} + * - {@link slave.SlaveServer.addClient} + * + * @param driver A {@link ICommunicator communicator} with (newly connected) remote client. + */ + addClient(driver: IClientDriver): void; + } +} +declare namespace samchon.templates.distributed { + /** + * Master of Distributed Processing System, a server accepting slave clients. + * + * The {@link DistributedClientArray} is an abstract class, derived from the {@link DistributedSystemArray} class, + * opening a server accepting {@link DistributedSystem distributed clients}. + * + * Extends this {@link DistributedClientArray}, overrides {@link createServerBase createServerBase()} to determine + * which protocol to follow and {@link createExternalClient createExternalClient()} creating child + * {@link DistributedSystem} object. After the extending and overridings, open this server using the + * {@link open open()} method. + * + * #### [Inherited] {@link DistributedSystemArray} + * @copydoc DistributedSystemArray + */ + abstract class DistributedClientArray extends DistributedSystemArray implements external.IExternalClientArray { + /** + * @hidden + */ + private server_base_; + /** + * Default Constructor. + */ + constructor(); + /** + * Factory method creating {@link IServerBase} object. + * + * This method {@link createServerBase createServerBase()} determines which protocol is used in this server, + * {@link ExternalClientArray}. If the protocol is determined, then {@link ExternalSystem external clients} who + * may connect to {@link ExternalClientArray this server} must follow the specified protocol. + * + * Overrides the {@link createServerBase createServerBase()} method to create and return one of them: + * + * - {@link ServerBase} + * - {@link WebServerBase} + * - {@link SharedWorkerServerBase} + * + * @return A new {@link IServerBase} object. + */ + protected abstract createServerBase(): protocol.IServerBase; + /** + * Add a newly connected remote client. + * + * When a {@link IClientDriver remote client} connects to this *master server of parallel processing system*, + * then this {@link ParallelClientArray} creates a child {@link ParallelSystem parallel client} object through + * the {@link createExternalClient createExternalClient()} method and {@link insert inserts} it. + * + * @param driver A communicator for external client. + */ + addClient(driver: protocol.IClientDriver): void; + /** + * (Deprecated) Factory method creating child object. + * + * The method {@link createChild createChild()} is deprecated. Don't use and override this. + * + * Note that, the {@link ParallelClientArray} is a server accepting {@link ParallelSystem parallel clients}. + * There's no way to creating the {@link ParallelSystem parallel clients} in advance before opening the server. + * + * @param xml An {@link XML} object represents the child {@link ParallelSystem} object. + * @return ```null``` + */ + createChild(xml: library.XML): System; + /** + * Factory method creating {@link DistributedSystem} object. + * + * The method {@link createExternalClient createExternalClient()} is a factory method creating a child + * {@link ParallelSystem} object, that is called whenever a parallel client has connected, by + * {@link addClient addClient()}. + * + * Overrides this {@link createExternalClient} method and creates a type of {@link DistributedSystem} object with + * the *driver* that communicates with the parallel client. After the creation, returns the object. Then whenever + * a parallel client has connected, matched {@link DistributedSystem} object will be constructed and + * {@link insert inserted} into this {@link DistributedSystemArray} object. + * + * @param driver A communicator with the parallel client. + * @return A newly created {@link ParallelSystem} object. + */ + protected abstract createExternalClient(driver: protocol.IClientDriver): System; + /** + * @inheritdoc + */ + open(port: number): void; + /** + * @inheritdoc + */ + close(): void; + } +} +declare namespace samchon.templates.distributed { + /** + * Mediator of Distributed Processing System, a server accepting slave clients. + * + * The {@link DistributedClientArrayMediator} is an abstract class, derived from {@link DistributedSystemArrayMediator} + * class, opening a server accepting {@link DistributedSystem distributed clients} as a **master**. + * + * Extends this {@link DistributedClientArrayMediator}, overrides {@link createServerBase createServerBase()} to + * determine which protocol to follow and {@link createExternalClient createExternalClient()} creating child + * {@link DistributedSystem} object. After the extending and overridings, open this server using the + * {@link open open()} method. + * + * #### [Inherited] {@link DistributedSystemArrayMediator} + * @copydoc DistributedSystemArrayMediator + */ + abstract class DistributedClientArrayMediator extends DistributedSystemArrayMediator implements external.IExternalClientArray { + /** + * A subrogator of {@link IServer server}'s role instead of this {@link ExternalClientArray}. + */ + private server_base_; + /** + * Default Constructor. + */ + constructor(); + /** + * Factory method creating {@link IServerBase} object. + * + * This method {@link createServerBase createServerBase()} determines which protocol is used in this + * {@link DistributedClientArrayMediator} object as a **master**. If the protocol is determined, then + * {@link DistributedSystem distributed clients} who may connect to {@link DistributedClientArrayMediator this + * server} must follow the specified protocol. + * + * Overrides the {@link createServerBase createServerBase()} method to create and return one of them: + * + * - {@link ServerBase} + * - {@link WebServerBase} + * - {@link SharedWorkerServerBase} + * + * @return A new {@link IServerBase} object. + */ + protected abstract createServerBase(): protocol.IServerBase; + /** + * Add a newly connected remote client. + * + * When a {@link IClientDriver remote client} connects to this *master server of distributed processing system*, + * then this {@link DistributedClientArrayMediator} creates a child {@link Distributed distributed client} object + * through the {@link createExternalClient createExternalClient()} method. + * + * @param driver A communicator for external client. + */ + addClient(driver: protocol.IClientDriver): void; + /** + * (Deprecated) Factory method creating child object. + * + * The method {@link createChild createChild()} is deprecated. Don't use and override this. + * + * Note that, the {@link DistributedClientArrayMediator} is a server accepting {@link DistributedSystem distributed + * clients} as a master. There's no way to creating the {@link DistributedSystem distributed clients} in advance + * before opening the server. + * + * @param xml An {@link XML} object represents the child {@link DistributedSystem} object. + * @return null + */ + createChild(xml: library.XML): System; + /** + * Factory method creating {@link DistributedSystem} object. + * + * The method {@link createExternalClient createExternalClient()} is a factory method creating a child + * {@link DistributedSystem} object, that is called whenever a distributed client has connected, by + * {@link addClient addClient()}. + * + * Overrides this {@link createExternalClient} method and creates a type of {@link DistributedSystem} object with + * the *driver* that communicates with the distributed client. After the creation, returns the object. Then whenever + * a distributed client has connected, matched {@link DistributedSystem} object will be constructed and + * {@link insert inserted} into this {@link DistributedClientArrayMediator} object. + * + * @param driver A communicator with the distributed client. + * @return A newly created {@link DistributedSystem} object. + */ + protected abstract createExternalClient(driver: protocol.IClientDriver): System; + /** + * @inheritdoc + */ + open(port: number): void; + /** + * @inheritdoc + */ + close(): void; + } +} +declare namespace samchon.templates.external { + /** + * An external system driver. + * + * The {@link ExternalSystem} class represents an external system, connected and interact with this system. + * {@link ExternalSystem} takes full charge of network communication with the remote, external system have connected. + * Replied {@link Invoke} messages from the external system is shifted to and processed in, children elements of this + * class, {@link ExternalSystemRole} objects. + * + * + * + * + * + * #### Bridge & Proxy Pattern + * The {@link ExternalSystem} class can be a *bridge* for *logical proxy*. In framework within user, + * which {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not + * important. Only interested in user's perspective is *which can be done*. + * + * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged + * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. + * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. + * + *
    + *
  • + * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring + * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. + *
  • + *
  • + * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call + * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the + * external system. + *
  • + *
  • Those strategy is called *Bridge Pattern* and *Proxy Pattern*.
  • + *
+ * + * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) + * @author Jeongho Nam + */ + abstract class ExternalSystem extends protocol.EntityDequeCollection implements protocol.IProtocol { + /** + * The name represents external system have connected. + */ + protected name: string; + /** + * @hidden + */ + private system_array_; + /** + * @hidden + */ + private communicator_; + /** + * Construct from parent {@link ExternalSystemArray}. + * + * @param systemArray The parent {@link ExternalSystemArray} object. + */ + constructor(systemArray: ExternalSystemArray); + /** + * Constrct from parent {@link ExternalSystemArray} and communicator. + * + * @param systemArray The parent {@link ExternalSystemArray} object. + * @param communicator Communicator with the remote, external system. + */ + constructor(systemArray: ExternalSystemArray, communicator: protocol.IClientDriver); + /** + * Default Destructor. + * + * This {@link destructor destructor()} method is called when the {@link ExternalSystem} object is destructed and + * the {@link ExternalSystem} object is destructed when connection with the remote system is closed or this + * {@link ExternalSystem} object is {@link ExternalSystemArray.erase erased} from its parent + * {@link ExternalSystemArray} object. + * + * Note that, don't call this {@link destructor destructor()} method by yourself. It must be called automatically + * by those *destruction* cases. Also, if your derived {@link ExternalSystem} class has something to do on the + * *destruction*, then overrides this {@link destructor destructor()} method and defines the something to do. + * Overriding this {@link destructor destructor()}, don't forget to calling ```super.destructor();``` on tail. + * + * ```typescript + * class SomeSystem extends templates.external.ExternalSystem + * { + * protected destructor(): void + * { + * // DO SOMETHING + * this.do_something(); + * + * // CALL SUPER.DESTRUCTOR() ON TAIL. DON'T FORGET THIS + * super.destructor(); + * } + * } + * ``` + */ + protected destructor(): void; + /** + * @hidden + */ + private _Handle_close(); + /** + * Get parent {@link ExternalSystemArray} object. + */ + getSystemArray(): ExternalSystemArray; + /** + * Get parent {@link ExternalSystemArray} object. + */ + getSystemArray>(): SystemArray; + /** + * Identifier of {@link ExternalSystem} is its {@link name}. + * + * @return name. + */ + key(): string; + /** + * Get {@link name}. + */ + getName(): string; + /** + * @hidden + */ + /** + * @hidden + */ + protected communicator: protocol.ICommunicator; + /** + * Close connection. + */ + close(): void; + /** + * Send {@link Invoke} message to external system. + * + * @param invoke An {@link Invoke} message to send. + */ + sendData(invoke: protocol.Invoke): void; + /** + * Handle an {@Invoke} message has received. + * + * @param invoke An {@link Invoke} message have received. + */ + replyData(invoke: protocol.Invoke): void; + /** + * Tag name of the {@link ExternalSystem} in {@link XML}. + * + * @return *system*. + */ + TAG(): string; + /** + * Tag name of {@link ExternalSystemRole children elements} belonged to the {@link ExternalSystem} in {@link XML}. + * + * @return *role*. + */ + CHILD_TAG(): string; + } +} +declare namespace samchon.templates.parallel { + /** + * A driver for a parallel slave system. + * + * The {@link ParallelSystem} is an abstract class represents a **slave** system in *Parallel Processing System*, + * connected with this **master** system. This {@link ParallelSystem} takes full charge of network communication with + * the remote, parallel **slave** system has connected. + * + * When a *parallel process* is requested (by {@link ParallelSystemArray.sendSegmentData} or + * {@link ParallelSystemArray.sendPieceData}), the number of pieces to be allocated to a {@link ParallelSystem} is + * turn on its {@link getPerformance performance index}. Higher {@link getPerformance performance index}, then + * more pieces are requested. The {@link getPerformance performance index} is revaluated whenever a *parallel process* + * has completed, basic on the execution time and number of pieces. You can sugguest or enforce the + * {@link getPerformance performance index} with {@link setPerformance} or {@link enforcePerformance}. + * + * + * + * + * + * #### Bridge & Proxy Pattern + * This class {@link ParallelSystem} is derived from the {@link ExternalSystem} class. Thus, you can take advantage + * of the *Bridge & Proxy Pattern* in this {@link ParallelSystem} class. If a process to request is not the + * *parallel process* (to be distrubted to all slaves), but the **exclusive process** handled in a system, then it + * may better to utilizing the *Bridge & Proxy Pattern*: + * + * The {@link ExternalSystem} class can be a *bridge* for *logical proxy*. In framework within user, + * which {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not + * important. Only interested in user's perspective is *which can be done*. + * + * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged + * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. + * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. + * + *
    + *
  • + * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring + * from {@link ExternalSystem}, with {@link ExternalSystemArray.getRole}. + *
  • + *
  • + * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call + * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the + * external system. + *
  • + *
  • Those strategy is called *Bridge Pattern* and *Proxy Pattern*.
  • + *
+ * + * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) + * @author Jeongho Nam + */ + abstract class ParallelSystem extends external.ExternalSystem { + /** + * @hidden + */ + private progress_list_; + /** + * @hidden + */ + private history_list_; + /** + * @hidden + */ + private exclude_; + /** + * @hidden + */ + private performance; + /** + * @hidden + */ + private enforced_; + /** + * Construct from parent {@link ParallelSystemArray}. + * + * @param systemArray The parent {@link ParallelSystemArray} object. + */ + constructor(systemArray: ParallelSystemArray); + /** + * Construct from parent {@link ParallelSystemArray} and communicator. + * + * @param systemArray The parent {@link ParallelSystemArray} object. + * @param communicator A communicator communicates with remote, the external system. + */ + constructor(systemArray: ParallelSystemArray, communicator: protocol.IClientDriver); + /** + * Default Destructor. + * + * This {@link destructor destructor()} method is called when the {@link ParallelSystem} object is destructed and + * the {@link ParallelSystem} object is destructed when connection with the remote system is closed or this + * {@link ParallelSystem} object is {@link ParallelSystemArray.erase erased} from its parent + * {@link ParallelSystemArray} object. + * + * You may think if there're some *parallel processes* have requested but not completed yet, then it would be a + * critical problem because the *parallel processes* will not complete forever. Do not worry. The critical problem + * does not happen. After the destruction, the remained *parallel processes* will be shifted to and proceeded in + * other {@link ParallelSystem} objects. + * + * Note that, don't call this {@link destructor destructor()} method by yourself. It must be called automatically + * by those *destruction* cases. Also, if your derived {@link ParallelSystem} class has something to do on the + * *destruction*, then overrides this {@link destructor destructor()} method and defines the something to do. + * Overriding this {@link destructor destructor()}, don't forget to calling ```super.destructor();``` on tail. + * + * ```typescript + * class SomeSystem extends protocol.external.ExternalSystem + * { + * protected destructor(): void + * { + * // DO SOMETHING + * this.do_something(); + * + * // CALL SUPER.DESTRUCTOR() ON TAIL. DON'T FORGET THIS + * super.destructor(); + * } + * } + * ``` + */ + protected destructor(): void; + /** + * Get manager of this object. + * + * @return The parent {@link ParallelSystemArray} object. + */ + getSystemArray(): ParallelSystemArray; + /** + * Get manager of this object. + * + * @return The parent {@link ParallelSystemArray} object. + */ + getSystemArray>(): SystemArray; + /** + * Get performance index. + * + * Get *performance index* that indicates how much fast the remote system is. + * + * If this {@link ParallelSystem parallel system} does not have any {@link Invoke} message had handled, then the + * *performance index* will be ```1.0```, which means default and average value between all {@link ParallelSystem} + * instances (that are belonged to a same {@link ParallelSystemArray} object). + * + * You can specify this *performance index* by yourself but notice that, if the *performance index* is higher + * than other {@link ParallelSystem} objects, then this {@link ParallelSystem parallel system} will be ordered to + * handle more processes than other {@link ParallelSystem} objects. Otherwise, the *performance index* is lower + * than others, of course, less processes will be delivered. + * + * - {@link setPerformance setPerformance()} + * - {@link enforcePerformance enforcePerformance()} + * + * Unless {@link enforcePerformance enforcePerformance()} is called, This *performance index* is **revaluated** + * whenever user calls one of them below. + * + * - {@link ParallelSystemArray.sendSegmentData ParallelSystemArray.sendSegmentData()} + * - {@link ParallelSystemArray.sendPieceData ParallelSystemArray.sendPieceData()} + * - {@link DistributedProcess.sendData DistributedProcess.sendData()}. + * + * @return Performance index. + */ + getPerformance(): number; + /** + * Set performance index. + * + * Set *performance index* that indicates how much fast the remote system is. This *performance index* can be + * **revaulated**. + * + * Note that, initial and average *performance index* of {@link ParallelSystem} objects are ```1.0```. If the + * *performance index* is higher than other {@link ParallelSystem} objects, then this {@link ParallelSystem} will + * be ordered to handle more processes than other {@link ParallelSystem} objects. Otherwise, the + * *performance index* is lower than others, of course, less processes will be delivered. + * + * Unlike {@link enforcePerformance}, configuring *performance index* by this {@link setPerformance} allows + * **revaluation**. This **revaluation** prevents wrong valuation from user. For example, you *mis-valuated* the + * *performance index*. The remote system is much faster than any other, but you estimated it to the slowest one. + * It looks like a terrible case that causes {@link ParallelSystemArray entire parallel systems} to be slower, + * however, don't mind. The system will direct to the *propriate performance index* eventually with the + * **revaluation** by following methods. + * + * - {@link ParallelSystemArray.sendSegmentData ParallelSystemArray.sendSegmentData()} + * - {@link ParallelSystemArray.sendPieceData ParallelSystemArray.sendPieceData()} + * - {@link DistributedProcess.sendData DistributedProcess.sendData()}. + * + * @param val New performance index, but can be revaluated. + */ + setPerformance(val: number): void; + /** + * Enforce performance index. + * + * Enforce *performance index* that indicates how much fast the remote system is. The *performance index* will be + * fixed, never be **revaluated**. + * + * Note that, initial and average *performance index* of {@link ParallelSystem} objects are ```1.0```. If the + * *performance index* is higher than other {@link ParallelSystem} objects, then this {@link ParallelSystem} will + * be ordered to handle more processes than other {@link ParallelSystem} objects. Otherwise, the + * *performance index* is lower than others, of course, less processes will be delivered. + * + * The difference between {@link setPerformance} and this {@link enforcePerformance} is allowing **revaluation** + * or not. This {@link enforcePerformance} does not allow the **revaluation**. The *performance index* is clearly + * fixed and never be changed by the **revaluation**. But you've to keep in mind that, you can't avoid the + * **mis-valuation** with this {@link enforcePerformance}. + * + * For example, there's a remote system much faster than any other, but you **mis-estimated** it to the slowest. + * In that case, there's no way. The {@link ParallelSystemArray entire parallel systems} will be slower by the + * **mis-valuation**. By the reason, using {@link enforcePerformance}, it's recommended only when you can clearly + * certain the *performance index*. If you can't certain the *performance index* but want to recommend, then use + * {@link setPerformance} instead. + * + * @param val New performance index to be fixed. + */ + enforcePerformance(val: number): void; + /** + * @hidden + */ + private _Send_piece_data(invoke, first, last); + /** + * @hidden + */ + private _Reply_data(invoke); + /** + * @hidden + */ + protected _Report_history(xml: library.XML): void; + /** + * @hidden + */ + protected _Send_back_history(invoke: protocol.Invoke, history: slave.InvokeHistory): void; + } +} +declare namespace samchon.templates.distributed { + /** + * A driver for a distributed slave system. + * + * The {@link DistributedSystem} is an abstract class represents a **slave** system in *Distributed Processing System*, + * connected with this **master** system. This {@link DistributedSystem} takes full charge of network communication + * with the remote, distributed **slave** system has connected. + * + * This {@link DistributedSystem} has a {@link getPerformance performance index} that indicates how much the **slave** + * system is fast. The {@link getPerformance performance index} is referenced and revaluated whenever those methods + * are called: + * + * - Requesting a *parallel process* + * - {@link DistributedSystemArray.sendSegmentData} + * - {@link DistributedSystemArray.sendPieceData} + * - Requesting a *distributed process*: {@link DistributedProcess.sendData} + * + * Note that, this {@link DistributedSystem} class derived from the {@link ExternalSystem} class. Thus, this + * {@link DistributedSystem} can also have children {@link ExternalSystemRole} objects exclusively. However, the + * children {@link ExternalSystemRole roles} objects are different with the {@link DistributedProcess}. The + * domestic {@link ExternalSystemRole roles} are belonged to only a specific {@link DistributedSystem} object. + * Otherwise, the {@link DistributedProcess} objects are belonged to a {@link DistributedSystemArray} object. + * Furthermore, the relationship between this {@link DistributedSystem} and {@link DistributedProcess} classes are + * **M: N Associative**. + * + * Articles | {@link DistributedProcess} | {@link ExternalSystemRole} + * -------------|--------------------------------|---------------------------- + * Belonged to | {@link DistributedSystemArray} | {@link DistributedSystem} + * Relationship | M: N Associative | 1: N Composite + * Ownership | References | Exclusive possession + * + * + * + * + * + * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) + * @author Jeongho Nam + */ + abstract class DistributedSystem extends parallel.ParallelSystem { + /** + * Construct from parent {@link DistributedSystemArray}. + * + * @param systemArray The parent {@link DistributedSystemArray} object. + */ + constructor(systemArray: DistributedSystemArray); + /** + * Constrct from parent {@link DistributedSystemArray} and communicator. + * + * @param systemArray The parent {@link DistributedSystemArray} object. + * @param communicator A communicator communicates with remote, the external system. + */ + constructor(systemArray: DistributedSystemArray, communicator: protocol.IClientDriver); + /** + * Factory method creating a {@link ExternalSystemRole child} object. + * + * In {@link distributed} module, the process class {@link DistributedProcess} is not belonged to a specific + * {@link DistributedSystem} object. It only belongs to a {@link DistributedSystemArray} object and has a + * **M: N Associative Relationship** between this {@link DistributedSystem} class. + * + * By that reason, it's the normal case that the {@link DistributedSystem} object does not have any children + * {@link ExternalSystemRole} object. Thus, default {@link createChild} returns ```null```. + * + * However, if you want a {@link DistributedSystem} to have its own domestic {@link ExternalSystemRole} objects + * without reference to the {@link DistributedProcess} objects, it is possible. Creates and returns the + * domestic {@link ExternalSystemRole} object. + * + * @param xml {@link XML} represents the {@link ExternalSystemRole child} object. + * @return A newly created {@link ExternalSystemRole} object or ```null```. + */ + createChild(xml: library.XML): external.ExternalSystemRole; + /** + * Get manager of this object. + * + * @return The parent {@link DistributedSystemArray} object. + */ + getSystemArray(): DistributedSystemArray; + /** + * Get manager of this object. + * + * @return The parent {@link DistributedSystemArray} object. + */ + getSystemArray>(): SystemArray; + /** + * @hidden + */ + private _Compute_average_elapsed_time(); + /** + * @inheritdoc + */ + replyData(invoke: protocol.Invoke): void; + /** + * @hidden + */ + protected _Report_history(xml: library.XML): void; + /** + * @hidden + */ + protected _Send_back_history(invoke: protocol.Invoke, history: slave.InvokeHistory): void; + } +} +declare namespace samchon.templates.distributed { + /** + * A driver for distributed slave server. + * + * The {@link DistributedServer} is an abstract class, derived from the {@link DistributedSystem} class, connecting to + * remote, distributed **slave** server. Extends this {@link DistributedServer} class and overrides the + * {@link createServerConnector createServerConnector()} method following which protocol the **slave** server uses. + * + * #### [Inheritdoc] {@link DistributedSystem} + * @copydoc DistributedSystem + */ + abstract class DistributedServer extends DistributedSystem implements external.IExternalServer { + /** + * IP address of target external system to connect. + */ + protected ip: string; + /** + * Port number of target external system to connect. + */ + protected port: number; + /** + * Construct from parent {@link DistributedSystemArray}. + * + * @param systemArray The parent {@link DistributedSystemArray} object. + */ + constructor(systemArray: DistributedSystemArray); + /** + * Factory method creating {@link IServerConnector} object. + * + * The {@link createServerConnector createServerConnector()} is an abstract method creating + * {@link IServerConnector} object. Overrides and returns one of them, considering which protocol the slave server + * follows: + * + * - {@link ServerConnector} + * - {@link WebServerConnector} + * - {@link DedicatedWorkerServerConnector} + * - {@link SharedWorkerServerConnector} + * + * @return A newly created {@link IServerConnector} object. + */ + protected abstract createServerConnector(): protocol.IServerConnector; + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.templates.distributed { + /** + * Master of Distributed Processing System, a client connecting to slave servers. + * + * The {@link DistributedServerArray} is an abstract class, derived from the {@link DistributedSystemArray} class, + * connecting to {@link IDistributedServer distributed servers}. + * + * Extends this {@link DistributedServerArray} and overrides {@link createChild createChild()} method creating child + * {@link IDistributedServer} object. After the extending and overriding, construct children {@link IDistributedServer} + * objects and call the {@link connect connect()} method. + * + * #### [Inherited] {@link DistributedSystemArray} + * @copydoc DistributedSystemArray + */ + abstract class DistributedServerArray extends DistributedSystemArray implements external.IExternalServerArray { + /** + * Default Constructor. + */ + constructor(); + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.templates.distributed { + /** + * Mediator of Distributed Processing System, a client connecting to slave servers. + * + * The {@link DistributedServerArrayMediator} is an abstract class, derived from {@link DistributedSystemArrayMediator} + * class, connecting to {@link IDistributedServer distributed servers}. + * + * Extends this {@link DistributedServerArrayMediator} and overrides {@link createChild createChild()} method creating + * child {@link IDistributedServer} object. After the extending and overriding, construct children + * {@link IDistributedServer} objects and call the {@link connect connect()} method. + * + * #### [Inherited] {@link DistributedSystemArrayMediator} + * @copydoc DistributedSystemArrayMediator + */ + abstract class DistributedServerArrayMediator extends DistributedSystemArrayMediator implements external.IExternalServerArray { + /** + * Default Constructor. + */ + constructor(); + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.templates.distributed { + /** + * Master of Distributed Processing System, be a server and client at the same time. + * + * The {@link DistributedServerClientArray} is an abstract class, derived from the {@link DistributedSystemArray} + * class, opening a server accepting {@link Distributed distributed clients} and being a client connecting to + * {@link IDistributedServer distributed servers} at the same time. + * + * Extends this {@link DistributedServerClientArray} and overrides below methods. After the overridings, open server + * with {@link open open()} method and connect to {@link IDistributedServer distributed servers} through the + * {@link connect connect()} method. + * + * - {@link createServerBase createServerBase()} + * - {@link createExternalClient createExternalClient()} + * - {@link createExternalServer createExternalServer()} + * + * #### [Inherited] {@link DistributedSystemArray} + * @copydoc DistributedSystemArray + */ + abstract class DistributedServerClientArray extends DistributedClientArray implements external.IExternalServerClientArray { + /** + * Default Constructor. + */ + constructor(); + /** + * Factory method of a child Entity. + * + * This method is migrated to {@link createExternalServer}. Override the {@link createExternalServer} method. + * + * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. + * @return A new child Entity via {@link createExternalServer createExternalServer()}. + */ + createChild(xml: library.XML): System; + /** + * Factory method creating an {@link IDistributedServer} object. + * + * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. + * @return A newly created {@link IDistributedServer} object. + */ + protected abstract createExternalServer(xml: library.XML): System; + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.templates.distributed { + /** + * Mediator of Distributed Processing System, be a server and client at the same time as a **master**. + * + * The {@link DistributedServerClientArrayMediator} is an abstract class, derived from the + * {@link DistributedSystemArrayMediator} class, opening a server accepting {@link DistributedSystem distributed + * clients} and being a client connecting to {@link IDistributedServer distributed servers} at the same time. + * + * Extends this {@link DistributedServerClientArrayMediator} and overrides below methods. After the overridings, open + * server with {@link open open()} method and connect to {@link IDistributedServer distributed servers} through the + * {@link connect connect()} method. + * + * - {@link createServerBase createServerBase()} + * - {@link createExternalClient createExternalClient()} + * - {@link createExternalServer createExternalServer()} + * + * #### [Inherited] {@link DistributedSystemArrayMediator} + * @copydoc DistributedSystemArrayMediator + */ + abstract class DistributedServerClientArrayMediator extends DistributedClientArrayMediator implements external.IExternalServerClientArray { + /** + * Default Constructor. + */ + constructor(); + /** + * Factory method of a child Entity. + * + * This method is migrated to {@link createExternalServer}. Override the {@link createExternalServer} method. + * + * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. + * @return A new child Entity via {@link createExternalServer createExternalServer()}. + */ + createChild(xml: library.XML): System; + /** + * Factory method creating an {@link IDistributedServer} object. + * + * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. + * @return A newly created {@link IDistributedServer} object. + */ + protected abstract createExternalServer(xml: library.XML): System; + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.templates.distributed { + /** + * A process of Distributed Processing System. + * + * The {@link DistributedProcess} is an abstract class who represents a **process**, *SOMETHING TO DISTRIBUTE* in a Distributed + * Processing System. Overrides the {@link DistributedProcess} and defines the *SOMETHING TO DISTRIBUTE*. + * + * Relationship between {@link DistributedSystem} and {@link DistributedProcess} objects are **M: N Associative**. + * Unlike {@link ExternalSystemRole}, the {@link DistributedProcess} objects are not belonged to a specific + * {@link DistributedSystem} object. The {@link DistributedProcess} objects are belonged to the + * {@link DistributedSystemArrayMediator} directly. + * + * When you need the **distributed process**, then call {@link sendData sendData()}. The {@link sendData} will find + * the most idle {@link DistributedSystem slave system} considering not only number of processes on progress, but also + * {@link DistributedSystem.getPerformance performance index} of each {@link DistributedSystem} object and + * {@link getResource resource index} of this {@link DistributedProcess} object. The {@link Invoke} message + * requesting the **distributed process** will be sent to the most idle {@link DistributedSystem slave system}. + * + * Those {@link DistributedSystem.getPerformance performance index} and {@link getResource resource index} are + * revaluated whenever the **distributed process** has completed basis on the execution time. + * + * + * + * + * + * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) + * @author Jeongho Nam + */ + abstract class DistributedProcess extends protocol.Entity implements protocol.IProtocol { + /** + * @hidden + */ + private system_array_; + /** + * A name, represents and identifies this {@link DistributedProcess process}. + * + * This {@link name} is an identifier represents this {@link DistributedProcess process}. This {@link name} is + * used in {@link DistributedSystemArray.getProcess} and {@link DistributedSystemArray.getProcess}, as a key elements. + * Thus, this {@link name} should be unique in its parent {@link DistributedSystemArray} object. + */ + protected name: string; + /** + * @hidden + */ + private progress_list_; + /** + * @hidden + */ + private history_list_; + /** + * @hidden + */ + private resource; + /** + * @hidden + */ + private enforced_; + /** + * Constrct from parent {@link DistributedSystemArray} object. + * + * @param systemArray The parent {@link DistributedSystemArray} object. + */ + constructor(systemArray: DistributedSystemArray); + /** + * Identifier of {@link ParallelProcess} is its {@link name}. + */ + key(): string; + /** + * Get parent {@link DistributedSystemArray} object. + * + * @return The parent {@link DistributedSystemArray} object. + */ + getSystemArray(): DistributedSystemArray; + /** + * Get parent {@link DistributedSystemArray} object. + * + * @return The parent {@link DistributedSystemArray} object. + */ + getSystemArray>(): SystemArray; + /** + * Get name, who represents and identifies this process. + */ + getName(): string; + /** + * Get resource index. + * + * Get *resource index* that indicates how much this {@link DistributedProcess process} is heavy. + * + * If this {@link DistributedProcess process} does not have any {@link Invoke} message had handled, then the + * *resource index* will be ```1.0```, which means default and average value between all + * {@link DistributedProcess} instances (that are belonged to a same {@link DistributedSystemArray} object). + * + * You can specify the *resource index* by yourself, but notice that, if the *resource index* is higher than + * other {@link DistributedProcess} objects, then this {@link DistributedProcess process} will be ordered to + * handle less processes than other {@link DistributedProcess} objects. Otherwise, the *resource index* is + * lower than others, of course, much processes will be requested. + * + * - {@link setResource setResource()} + * - {@link enforceResource enforceResource()} + * + * Unless {@link enforceResource enforceResource()} is called, This *resource index* is **revaluated** whenever + * {@link sendData sendData()} is called. + * + * @return Resource index. + */ + getResource(): number; + /** + * Set resource index. + * + * Set *resource index* that indicates how much this {@link DistributedProcess process} is heavy. This + * *resource index* can be **revaulated**. + * + * Note that, initial and average *resource index* of {@link DistributedProcess} objects are ```1.0```. If the + * *resource index* is higher than other {@link DistributedProcess} objects, then this + * {@link DistributedProcess} will be ordered to handle more processes than other {@link DistributedProcess} + * objects. Otherwise, the *resource index* is lower than others, of course, less processes will be requested. + * + * Unlike {@link enforceResource}, configuring *resource index* by this {@link setResource} allows the + * **revaluation**. This **revaluation** prevents wrong valuation from user. For example, you *mis-valuated* the + * *resource index*. The {@link DistributedProcess process} is much heavier than any other, but you estimated it + * to the lightest one. It looks like a terrible case that causes + * {@link DistributedSystemArray entire distributed processing system} to be slower, however, don't mind. The + * {@link DistributedProcess process} will the direct to the *propriate resource index* eventually with the + * **revaluation**. + * + * - The **revaluation** is caused by the {@link sendData sendData()} method. + * + * @param val New resource index, but can be revaluated. + */ + setResource(val: number): void; + /** + * Enforce resource index. + * + * Enforce *resource index* that indicates how much heavy the {@link DistributedProcess process is}. The + * *resource index* will be fixed, never be **revaluated**. + * + * Note that, initial and average *resource index* of {@link DistributedProcess} objects are ```1.0```. If the + * *resource index* is higher than other {@link DistributedProcess} objects, then this + * {@link DistributedProcess} will be ordered to handle more processes than other {@link DistributedProcess} + * objects. Otherwise, the *resource index* is lower than others, of course, less processes will be requested. + * + * The difference between {@link setResource} and this {@link enforceResource} is allowing **revaluation** or not. + * This {@link enforceResource} does not allow the **revaluation**. The *resource index* is clearly fixed and + * never be changed by the **revaluation**. But you've to keep in mind that, you can't avoid the **mis-valuation** + * with this {@link enforceResource}. + * + * For example, there's a {@link DistributedProcess process} much heavier than any other, but you + * **mis-estimated** it to the lightest. In that case, there's no way. The + * {@link DistributedSystemArray entire distributed processing system} will be slower by the **mis-valuation**. + * By the reason, using {@link enforceResource}, it's recommended only when you can clearly certain the + * *resource index*. If you can't certain the *resource index* but want to recommend, then use {@link setResource} + * instead. + * + * @param val New resource index to be fixed. + */ + enforceResource(val: number): void; + /** + * @hidden + */ + private _Compute_average_elapsed_time(); + /** + * @inheritdoc + */ + abstract replyData(invoke: protocol.Invoke): void; + /** + * Send an {@link Invoke} message. + * + * Sends an {@link Invoke} message requesting a **distributed process**. The {@link Invoke} message will be sent + * to the most idle {@link DistributedSystem} object, which represents a slave system, and the most idle + * {@link DistributedSystem} object will be returned. + * + * When the **distributed process** has completed, then the {@link DistributedSystemArray} object will revaluate + * {@link getResource resource index} and {@link DistributedSystem.getPerformance performance index} of this + * {@link DistributedSystem} and the most idle {@link DistributedSystem} objects basis on the execution time. + * + * @param invoke An {@link Invoke} message requesting distributed process. + * @return The most idle {@link DistributedSystem} object who may send the {@link Invoke} message. + */ + sendData(invoke: protocol.Invoke): DistributedSystem; + /** + * Send an {@link Invoke} message. + * + * Sends an {@link Invoke} message requesting a **distributed process**. The {@link Invoke} message will be sent + * to the most idle {@link DistributedSystem} object, which represents a slave system, and the most idle + * {@link DistributedSystem} object will be returned. + * + * When the **distributed process** has completed, then the {@link DistributedSystemArray} object will revaluate + * {@link getResource resource index} and {@link DistributedSystem.getPerformance performance index} of this + * {@link DistributedSystem} and the most idle {@link DistributedSystem} objects basis on the execution time. + * + * @param invoke An {@link Invoke} message requesting distributed process. + * @param weight Weight of resource which indicates how heavy this {@link Invoke} message is. Default is 1. + * + * @return The most idle {@link DistributedSystem} object who may send the {@link Invoke} message. + */ + sendData(invoke: protocol.Invoke, weight: number): DistributedSystem; + /** + * @hidden + */ + private _Complete_history(history); + /** + * @inheritdoc + */ + TAG(): string; + } +} +declare namespace samchon.templates.slave { + /** + * History of an {@link Invoke} message. + * + * The {@link InvokeHistory} is a class archiving history log of an {@link Invoke} message with elapsed time. This + * {@link InvokeHistory} class is used to report elapsed time of handling a requested process from **slave** to + * **master** system. + * + * The **master** system utilizes derived {@link InvokeHistory} objects to compute performance indices. + * - {@link ParallelSytem.getPerformance} + * - {@link DistributedProcess.getResource} + * + * @author Jeongho Nam + */ + class InvokeHistory extends protocol.Entity { + /** + * @hidden + */ + private uid; + /** + * @hidden + */ + private listener; + /** + * @hidden + */ + private start_time_; + /** + * @hidden + */ + private end_time_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from an {@link Invoke} message. + * + * @param invoke An {@link Invoke} message requesting a *parallel or distributed process*. + */ + constructor(invoke: protocol.Invoke); + /** + * @inheritdoc + */ + construct(xml: library.XML): void; + /** + * Complete the history. + * + * Completes the history and determines the {@link getEndTime end time}. + */ + complete(): void; + key(): number; + /** + * Get unique ID. + */ + getUID(): number; + /** + * Get {@link Invoke.getListener listener} of the {@link Invoke} message. + */ + getListener(): string; + /** + * Get start time. + */ + getStartTime(): Date; + /** + * Get end time. + */ + getEndTime(): Date; + /** + * Compute elapsed time. + * + * @return nanoseconds. + */ + computeElapsedTime(): number; + /** + * @inheritdoc + */ + TAG(): string; + /** + * @inheritdoc + */ + toXML(): library.XML; + /** + * Convert to an {@link Invoke} message. + * + * Creates and returns an {@link Invoke} message that is used to reporting to the **master**. + */ + toInvoke(): protocol.Invoke; + } +} +declare namespace samchon.templates.distributed { + /** + * History of an {@link Invoke} message. + * + * The {@link PRInvokeHistory} is a class archiving history log of an {@link Invoke} message which requests the + * *distributed process*, created whenever {@link DistributedProcess.sendData} is called. + * + * When the *distributed process* has completed, then {@link complete complete()} is called and the *elapsed time* is + * determined. The elapsed time is utilized for computation of {@link DistributedSystem.getPerformance performance index} + * and {@link DistributedProcess.getResource resource index} of related objects. + * + * + * + * + * + * @handbook [Templates - Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) + * @author Jeongho Nam + */ + class DSInvokeHistory extends slave.InvokeHistory { + /** + * @hidden + */ + private system_; + /** + * @hidden + */ + private process_; + /** + * @hidden + */ + private weight_; + /** + * Construct from a DistributedSystem. + * + * @param system The {@link DistributedSystem} object who sent the {@link Invoke} message. + */ + constructor(system: DistributedSystem); + /** + * Initilizer Constructor. + * + * @param system The {@link DistributedSystem} object who sent the {@link Invoke} message. + * @param process The {@link DistributedProcess} object who sent the {@link Invoke} message. + * @param invoke An {@link Invoke} message requesting the *distributed process*. + * @param weight Weight of resource which indicates how heavy this {@link Invoke} message is. + */ + constructor(system: DistributedSystem, process: DistributedProcess, invoke: protocol.Invoke, weight: number); + /** + * @inheritdoc + */ + construct(xml: library.XML): void; + /** + * Get the related {@link DistributedSystem} object. + */ + getSystem(): DistributedSystem; + /** + * Get the related {@link DistributedProcess} object. + */ + getProcess(): DistributedProcess; + /** + * Get weight. + * + * Gets weight of resource which indicates how heavy this {@link Invoke} message is. Default is 1. + */ + getWeight(): number; + /** + * @inheritdoc + */ + toXML(): library.XML; + } +} +declare namespace samchon.templates.distributed { + /** + * An interface for a distributed slave server driver. + * + * The easiest way to defining a driver for distributed **slave** server is extending {@link DistributedServer} class. + * However, if you've to interact with a prallel **slave** system who can be both server and client, them make a class + * (let's name it **BaseSystem**) extending the {@link DistributedServer} class. At next, make a new class (now, I name + * it **BaseServer**) extending the **BaseSystem** and implements this interface {@link IParallelServer}. Define the + * **BaseServer** following those codes on below: + * + * + * + * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) + * @author Jeongho Nam + */ + interface IDistributedServer extends DistributedSystem { + /** + * Connect to external server. + */ + connect(): void; + } +} +declare namespace samchon.templates.external { + /** + * An array and manager of {@link ExternalSystem external clients} as a server. + * + * The {@link ExternalClientArray} is an abstract class, derived from the {@link ExternalSystemArray} class, opening + * a server accepting {@link ExternalSystem external clients}. + * + * Extends this {@link ExternalClientArray}, overrides {@link createServerBase createServerBase()} to determine which + * protocol to follow and {@link createExternalClient createExternalClient()} creating child {@link ExternalSystem} + * object. After the extending and overridings, open this server using the {@link open open()} method. + * + * #### [Inherited] {@link ExternalSystemArray} + * @copydoc ExternalSystemArray + */ + abstract class ExternalClientArray extends ExternalSystemArray implements IExternalClientArray { + /** + * @hidden + */ + private server_base_; + /** + * Default Constructor. + */ + constructor(); + /** + * Factory method creating {@link IServerBase} object. + * + * This method {@link createServerBase createServerBase()} determines which templates is used in this server, + * {@link ExternalClientArray}. If the templates is determined, then {@link ExternalSystem external clients} who + * may connect to {@link ExternalClientArray this server} must follow the specified templates. + * + * Creates and returns one of them: + * + * - {@link ServerBase} + * - {@link WebServerBase} + * - {@link SharedWorkerServerBase} + * + * @return A new {@link IServerBase} object. + */ + protected abstract createServerBase(): protocol.IServerBase; + /** + * Add a newly connected remote client. + * + * When a {@link IClientDriver remote client} connects to this *server* {@link ExternalClientArray} object, + * then this {@link ExternalClientArray} creates a child {@link ExternalSystem external client} object through + * the {@link createExternalClient createExternalClient()} method and {@link insert inserts} it. + * + * @param driver A communicator for external client. + */ + addClient(driver: protocol.IClientDriver): void; + /** + * (Deprecated) Factory method creating child object. + * + * The method {@link createChild createChild()} is deprecated. Don't use and override this. + * + * Note that, the {@link ExternalClientArray} is a server accepting {@link ExternalSystem external clients}. + * There's no way to creating the {@link ExternalSystem external clients} in advance before opening the server. + * + * @param xml An {@link XML} object represents the child {@link ExternalSystem} object. + * @return null + */ + createChild(xml: library.XML): T; + /** + * Factory method creating a child {@link ExternalSystem} object. + * + * @param driver A communicator with connected client. + * @return A newly created {@link ExternalSystem} object. + */ + protected abstract createExternalClient(driver: protocol.IClientDriver): T; + /** + * @inheritdoc + */ + open(port: number): void; + /** + * @inheritdoc + */ + close(): void; + } +} +declare namespace samchon.templates.external { + /** + * An external server driver. + * + * The {@link ExternalServer} is an abstract class, derived from the {@link ExternalSystem} class, connecting to + * remote, external server. Extends this {@link ExternalServer} class and overrides the + * {@link createServerConnector createServerConnector()} method following which protocol the external server uses. + * + * #### [Inherited] {@link ExternalSystem} + * @copydoc ExternalSystem + */ + abstract class ExternalServer extends ExternalSystem implements IExternalServer { + /** + * IP address of target external system to connect. + */ + protected ip: string; + /** + * Port number of target external system to connect. + */ + protected port: number; + /** + * Construct from parent {@link ExternalSystemArray}. + * + * @param systemArray The parent {@link ExternalSystemArray} object. + */ + constructor(systemArray: ExternalSystemArray); + /** + * Factory method creating {@link IServerConnector} object. + * + * The {@link createServerConnector createServerConnector()} is an abstract method creating + * {@link IServerConnector} object. Overrides and returns one of them, considering which templates the external + * system follows: + * + * - {@link ServerConnector} + * - {@link WebServerConnector} + * - {@link DedicatedWorkerServerConnector} + * - {@link SharedWorkerServerConnector} + * + * @return A newly created {@link IServerConnector} object. + */ + protected abstract createServerConnector(): protocol.IServerConnector; + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.templates.external { + /** + * An array and manager of {@link IExternalServer external servers}. + * + * The {@link ExternalServerArray} is an abstract class, derived from the {@link ExternalSystemArray} class, + * connecting to {@link IExternalServer external servers}. + * + * Extends this {@link ExternalServerArray} and overrides {@link createChild createChild()} method creating child + * {@link IExternalServer} object. After the extending and overriding, construct children {@link IExternalServer} + * objects and call the {@link connect connect()} method. + * + * #### [Inherited] {@link ExternalSystemArray} + * @copydoc ExternalSystemArray + */ + abstract class ExternalServerArray extends ExternalSystemArray implements IExternalServerArray { + /** + * Default Constructor. + */ + constructor(); + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.templates.external { + /** + * An array and manager of {@link IExternalServer external servers} and {@link ExternalSystem external clients}. + * + * The {@link ExternalServerClientArray} is an abstract class, derived from the {@link ExternalSystemArray} class, + * opening a server accepting {@link ExternalSystem external clients} and being a client connecting to + * {@link IExternalServer external servers} at the same time. + * + * Extends this {@link ExternalServerClientArray} and overrides below methods. After the overridings, open server + * with {@link open open()} method and connect to {@link IExternalServer external servers} through the + * {@link connect connect()} method. + * + * - {@link createServerBase createServerBase()} + * - {@link createExternalClient createExternalClient()} + * - {@link createExternalServer createExternalServer()} + * + * #### [Inherited] {@link ExternalSystemArray} + * @copydoc ExternalSystemArray + */ + abstract class ExternalServerClientArray extends ExternalClientArray implements IExternalServerClientArray { + /** + * Default Constructor. + */ + constructor(); + /** + * Factory method of a child Entity. + * + * This method is migrated to {@link createExternalServer}. Override the {@link createExternalServer} method. + * + * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. + * @return A new child Entity via {@link createExternalServer createExternalServer()}. + */ + createChild(xml: library.XML): T; + /** + * Factory method creating an {@link IExternalServer} object. + * + * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. + * @return A newly created {@link IExternalServer} object. + */ + protected abstract createExternalServer(xml: library.XML): T; + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.templates.external { + /** + * A role of an external system. + * + * The {@link ExternalSystemRole} class represents a role, *WHAT TO DO*. Extends the {@link ExternalSystemRole} class + * and overrides {@link replyData replyData()} to define the *WHAT TO DO*. And assign this {@link ExternalSystemRole} + * object to related {@link ExternalSystem} object. + * + * + * + * + * + * #### Proxy Pattern + * The {@link ExternalSystemRole} class can be an *logical proxy*. In framework within user, which + * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not + * important. Only interested in user's perspective is *which can be done*. + * + * By using the *logical proxy*, user dont't need to know which {@link ExternalSystemRole role} is belonged + * to which {@link ExternalSystem system}. Just access to a role directly from {@link ExternalSystemArray.getRole}. + * Sends and receives {@link Invoke} message via the {@link ExternalSystemRole role}. + * + *
    + *
  • + * {@link ExternalSystemRole} can be accessed from {@link ExternalSystemArray} directly, without inteferring + * from {@link ExternalSystem} object, via {@link ExternalSystemArray.getRole ExternalSystemArray.getRole()}. + *
  • + *
  • + * When you want to send an {@link Invoke} message to the belonged {@link ExternalSystem system}, just call + * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the + * external system. + *
  • + *
  • Those strategy is called *Proxy Pattern*.
  • + *
+ * + * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) + * @author Jeongho Nam + */ + abstract class ExternalSystemRole extends protocol.Entity implements protocol.IProtocol { + /** + * @hidden + */ + private system; + /** + * A name, represents and identifies this {@link ExternalSystemRole role}. + * + * This {@link name} is an identifier represents this {@link ExternalSystemRole role}. This {@link name} is + * used in {@link ExternalSystemArray.getRole} and {@link ExternalSystem.get}, as a key elements. Thus, this + * {@link name} should be unique in an {@link ExternalSystemArray}. + */ + protected name: string; + /** + * Constructor from a system. + * + * @param system An external system containing this role. + */ + constructor(system: ExternalSystem); + /** + * Identifier of {@link ExternalSystemRole} is its {@link name}. + */ + key(): string; + /** + * Get grandparent {@link ExternalSystemArray}. + * + * Get the grandparent {@link ExternalSystemArray} object through this parent {@link ExternalSystem}, + * {@link ExternalSystem.getSystemArray ExternalSystem.getSystemArray()}. + * + * @return The grandparent {@link ExternalSystemArray} object. + */ + getSystemArray(): ExternalSystemArray; + /** + * Get parent {@link ExternalSystemRole} object. + */ + getSystem(): ExternalSystem; + /** + * Get name, who represents and identifies this role. + */ + getName(): string; + /** + * Send an {@link Invoke} message. + * + * Sends an {@link Invoke} message to remote system through the parent {@link ExternalSystem} object. + * + * @param invoke An {@link Invoke} message to send to the external system. + */ + sendData(invoke: protocol.Invoke): void; + /** + * Handle replied {@link Invoke} message. + * + * {@link ExternalSystemRole.replyData ExternalSystemRole.replyData()} is an abstract method handling a replied + * {@link Invoke message} gotten from remote system via parent {@link ExternalSystem} object. Overrides this + * method and defines the *WHAT TO DO* with the {@link Invoke message}. + * + * @param invoke An {@link Invoke} message received from the {@link ExternalSystem external system}. + */ + abstract replyData(invoke: protocol.Invoke): void; + /** + * Tag name of the {@link ExternalSytemRole} in {@link XML}. + * + * @return *role*. + */ + TAG(): string; + } +} +declare namespace samchon.templates.external { + /** + * An interface for an {@link ExternalSystemArray} accepts {@link ExternalSystem external clients} as a + * {@link IServer server}. + * + * The easiest way to defining an {@link ExternalSystemArray} who opens server and accepts + * {@link ExternalSystem external clients} is to extending one of below, who are derived from this interface + * {@link IExternalClientArray}. However, if you can't specify an {@link ExternalSystemArray} to be whether server or + * client, then make a class (let's name it as **BaseSystemArray**) extending {@link ExternalSystemArray} and make + * a new class (now, I name it **BaseClientArray**) extending **BaseSystemArray** and implementing this + * interface {@link IExternalClientArray}. Define the **BaseClientArray** following those codes on below: + * + * + * + * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) + * @author Jeongho Nam + */ + interface IExternalClientArray extends ExternalSystemArray, protocol.IServer { + } +} +declare namespace samchon.templates.external { + /** + * An interface for an external server driver. + * + * The easiest way to defining an external server driver is to extending one of below, who are derived from this + * interface {@link IExternalServer}. However, if you've to interact with an external system who can be both server + * and client, then make a class (let's name it as **BaseSystem**) extending {@link ExternalSystem} and make a + * new class (now, I name it **BaseServer**) extending **BaseSystem** and implementing this interface + * {@link IExternalServer}. Define the **BaseServer** following those codes on below: + * + * + * + * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) + * @author Jeongho Nam + */ + interface IExternalServer extends ExternalSystem { + /** + * Connect to the external server. + */ + connect(): void; + } +} +declare namespace samchon.templates.external { + /** + * An interface for an {@link ExternalSystemArray} connects to {@link IExternalServer external servers} as a + * **client**. + * + * The easiest way to defining an {@link ExternalSystemArray} who connects to + * {@link IExternalServer external servers} is to extending one of below, who are derived from this interface + * {@link IExternalServerArray}. However, if you can't specify an {@link ExternalSystemArray} to be whether server or + * client, then make a class (let's name it as **BaseSystemArray**) extending {@link ExternalSystemArray} and make + * a new class (now, I name it **BaseServerArray**) extending **BaseSystemArray** and implementing this + * interface {@link IExternalServerArray}. Define the **BaseServerArray** following those codes on below: + * + * + * + * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) + * @author Jeongho Nam + */ + interface IExternalServerArray extends ExternalSystemArray { + /** + * Connect to {@link IExternalServer external servers}. + * + * This method calls children elements' method {@link IExternalServer.connect} gradually. + */ + connect(): void; + } +} +declare namespace samchon.templates.external { + /** + * An interface for an {@link ExternalSystemArray} accepts {@link ExternalSystem external clients} as a + * {@link IServer server} and connects to {@link IExternalServer} as **client**, at the same time. + * + * The easiest way to defining an {@link IExternalServerClientArray} who opens server, accepts + * {@link ExternalSystem external clients} and connects to {@link IExternalServer external servers} is to extending + * one of below, who are derived from this interface {@link IExternalServerClientArray}. However, if you can't + * specify an {@link ExternalSystemArray} to be whether server or client or even can both them, then make a class + * (let's name it as **BaseSystemArray**) extending {@link ExternalSystemArray} and make a new class (now, I name + * it **BaseServerClientArray**) extending **BaseSystemArray** and implementing this interface + * {@link IExternalServerClientArray}. Define the **BaseServerClientArray** following those codes on below: + * + * + * + * @handbook [Templates - External System](https://github.com/samchon/framework/wiki/TypeScript-Templates-External_System) + * @author Jeongho Nam + */ + interface IExternalServerClientArray extends IExternalClientArray { + /** + * Connect to {@link IExternalServer external servers}. + * + * This method calls children elements' method {@link IExternalServer.connect} gradually. + */ + connect(): void; + } +} +declare namespace samchon.templates.slave { + /** + * A slave system. + * + * @author Jeongho Nam + */ + abstract class SlaveSystem implements protocol.IProtocol { + /** + * @hidden + */ + protected communicator_: protocol.ICommunicator; + /** + * Default Constructor. + */ + constructor(); + sendData(invoke: protocol.Invoke): void; + abstract replyData(invoke: protocol.Invoke): void; + /** + * @hidden + */ + protected _Reply_data(invoke: protocol.Invoke): void; + } +} +declare namespace samchon.templates.parallel { + /** + * A mediator, the master driver. + * + * The {@link MediatorSystem} is an abstract class helping {@link ParallelSystemArrayMediator} can be a **slave** + * system. The {@link MediatorSystem} interacts and communicates with the **master** system as a role of **slave**. + * + * This {@link MediatorSystem} object is created in {@link ParallelSystemArrayMediator.createMediator}. Override the + * method and return one of them, which are derived from this {@link MediatorSystem} class, considering which + * type and protocol the **master** system follows: + * + * - A client slave connecting to master server: + * - {@link MediatorClient} + * - {@link MediatorWebClient} + * - {@link MediatorSharedWorkerClient} + * - A server slave accepting master client: + * - {@link MediatorServer} + * - {@link MediatorWebServer} + * - {@link MediatorDedicatedWorkerServer} + * - {@link MediatorSharedWorkerServer} + * + * When the **master** orders a *parallel process* to this **slave**, then the {@link MediatorSystem} delivers the + * *parallel process* to its parent {@link ParallelSystemArrayMediator} object. The + * {@link ParallelSystemArrayMediator} object distributes the *parallel process* to its slaves system, + * {@link ParallelSystem} objects. When the *parallel process* has completed, then {@link MediatorSystem} reports the + * result to its **master**. + * + * + * + * + * + * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System), + * [Distributed System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Distributed_System) + * @author Jeongho Nam + */ + abstract class MediatorSystem extends slave.SlaveSystem { + /** + * @hidden + */ + private system_array_; + /** + * @hidden + */ + private progress_list_; + /** + * Construct from parent {@link ParallelSystemArrayMediator} object. + * + * @param systemArray The parent {@link ParallelSystemArrayMediator} object. + */ + constructor(systemArray: ParallelSystemArrayMediator); + /** + * Construct from parent {@link DistributedSystemArrayMediator} object. + * + * @param systemArray The parent {@link DistributedSystemArrayMediator} object. + */ + constructor(systemArray: distributed.DistributedSystemArrayMediator); + /** + * Start interaction. + * + * The {@link start start()} is an abstract method starting interaction with the **master** system. If the + * **master** is a server, then connects to the **master**. Otherwise, the **master** is client, then this + * {@link MediatorSystem} object wil open a server accepting the **master**. + */ + abstract start(): void; + /** + * Get parent {@link ParallelSystemArrayMediator} or {@link DistributedSystemArrayMediator} object. + */ + getSystemArray(): ParallelSystemArrayMediator | distributed.DistributedSystemArrayMediator; + /** + * Get parent {@link ParallelSystemArrayMediator} object. + */ + getSystemArray>(): SystemArray; + /** + * Get parent {@link DistributedSystemArrayMediator} object. + */ + getSystemArray>(): SystemArray; + /** + * @hidden + */ + private _Complete_history(uid); + /** + * @hidden + */ + protected _Reply_data(invoke: protocol.Invoke): void; + /** + * @inheritdoc + */ + replyData(invoke: protocol.Invoke): void; + } +} +declare namespace samchon.templates.parallel { + /** + * A mediator client, driver for the master server. + * + * The {@link MediatorServer} is a class being a client connecting to the **master** server, following the protocol + * of Samchon Framework's own. + * + * #### [Inherited] {@link MediatorSystem} + * @copydoc MediatorSystem + */ + class MediatorClient extends MediatorSystem implements slave.ISlaveClient { + /** + * @hidden + */ + private ip; + /** + * @hidden + */ + private port; + /** + * Initializer Constructor. + * + * @param systemArray The parent {@link ParallelSystemArrayMediator} object. + * @param ip IP address to connect. + * @param port Port number to connect. + */ + constructor(systemArray: ParallelSystemArrayMediator, ip: string, port: number); + /** + * Initializer Constructor. + * + * @param systemArray The parent {@link DistributedSystemArrayMediator} object. + * @param ip IP address to connect. + * @param port Port number to connect. + */ + constructor(systemArray: distributed.DistributedSystemArrayMediator, ip: string, port: number); + /** + * Factory method creating {@link IServerConnector} object. + * + * The {@link createServerConnector createServerConnector()} is an abstract method creating + * {@link IServerConnector} object. Overrides and returns one of them, considering which protocol the **master** + * server follows: + * + * - {@link ServerConnector} + * - {@link WebServerConnector} + * - {@link SharedWorkerServerConnector} + * + * @return A newly created {@link IServerConnector} object. + */ + protected createServerConnector(): protocol.IServerConnector; + /** + * @inheritdoc + */ + start(): void; + /** + * @inheritdoc + */ + connect(): void; + } + /** + * A mediator client, driver for the master server. + * + * The {@link MediatorWebClient} is a class being a client connecting to the **master** server, following the + * web-socket protocol. + * + * #### [Inherited] {@link MediatorSystem} + * @copydoc MediatorSystem + */ + class MediatorWebClient extends MediatorClient { + /** + * @inheritdoc + */ + protected createServerConnector(): protocol.IServerConnector; + } + /** + * A mediator client, driver for the master server. + * + * The {@link MediatorSharedWorkerClient} is a class being a client connecting to the **master** server, following + * the SharedWorker's protocol. + * + * #### [Inherited] {@link MediatorSystem} + * @copydoc MediatorSystem + */ + class MediatorSharedWorkerClient extends MediatorClient { + /** + * @inheritdoc + */ + protected createServerConnector(): protocol.IServerConnector; + } +} +declare namespace samchon.templates.parallel { + /** + * A mediator server, driver for the master client. + * + * The {@link MediatorServer} is a class opening a server accepting the **master** client, following the protocol of + * Samchon Framework's own. + * + * #### [Inherited] {@link MediatorSystem} + * @copydoc MediatorSystem + */ + class MediatorServer extends MediatorSystem implements slave.ISlaveServer { + /** + * @hidden + */ + private server_base_; + /** + * @hidden + */ + private port; + /** + * Initializer Constructor. + * + * @param systemArray The parent {@link ParallelSystemArrayMediator} object. + * @param port Port number of server to open. + */ + constructor(systemArray: ParallelSystemArrayMediator, port: number); + /** + * Initializer Constructor. + * + * @param systemArray The parent {@link DistributedSystemArrayMediator} object. + * @param port Port number of server to open. + */ + constructor(systemArray: distributed.DistributedSystemArrayMediator, port: number); + /** + * Factory method creating {@link IServerBase} object. + * + * This method {@link createServerBase createServerBase()} determines which protocol is used in this server, + * {@link MediatorServer}. Note that, **slave** (this {@link MediatorServer} object) must follow the **master**'s + * protocol. + * + * Overrides and return one of them considering the which protocol to follow: + * + * - {@link ServerBase} + * - {@link WebServerBase} + * - {@link SharedWorkerServerBase} + */ + protected createServerBase(): protocol.IServerBase; + /** + * Add a newly connected remote client. + * + * {@link MediatorServer} represents a **slave** dedicating to its **master**. In that reason, the + * {@link MediatorServer} does not accept multiple **master** clients. It accepts only one. Thus, *listener* of + * the *communicator* is {@link MediatorSystem} object, itself. + * + * @param driver A communicator with remote client. + */ + addClient(driver: protocol.IClientDriver): void; + /** + * @inheritdoc + */ + start(): void; + /** + * @inheritdoc + */ + open(port: number): void; + /** + * @inheritdoc + */ + close(): void; + } + /** + * A mediator server, driver for the master client. + * + * The {@link MediatorWebServer} is a class opening a server accepting the **master** client, following the + * web-socket protocol. + * + * #### [Inherited] {@link MediatorSystem} + * @copydoc MediatorSystem + */ + class MediatorWebServer extends MediatorServer { + /** + * @inheritdoc + */ + protected createServerBase(): protocol.IServerBase; + } + /** + * A mediator server, driver for the master client. + * + * The {@link MediatorDedicatedWorkerServer} is a class opening a server accepting the **master** client, following + * the DedicatedWorker's protocol. + * + * #### [Inherited] {@link MediatorSystem} + * @copydoc MediatorSystem + */ + class MediatorDedicatedWorkerServer extends MediatorServer { + /** + * @inheritdoc + */ + protected createServerBase(): protocol.IServerBase; + } + /** + * A mediator server, driver for the master client. + * + * The {@link MediatorSharedWorkerServer} is a class opening a server accepting the **master** client, following the + * SharedWorker's protocol. + * + * #### [Inherited] {@link MediatorSystem} + * @copydoc MediatorSystem + */ + class MediatorSharedWorkerServer extends MediatorServer { + /** + * @inheritdoc + */ + protected createServerBase(): protocol.IServerBase; + } +} +declare namespace samchon.templates.parallel { + /** + * Master of Parallel Processing System, a server accepting slave clients. + * + * The {@link ParallelClientArray} is an abstract class, derived from the {@link ParallelSystemArray} class, opening + * a server accepting {@link ParallelSystem parallel clients}. + * + * Extends this {@link ParallelClientArray}, overrides {@link createServerBase createServerBase()} to determine which + * protocol to follow and {@link createExternalClient createExternalClient()} creating child {@link ParallelSystem} + * object. After the extending and overridings, open this server using the {@link open open()} method. + * + * #### [Inherited] {@link ParallelSystemArray} + * @copydoc ParallelSystemArray + */ + abstract class ParallelClientArray extends ParallelSystemArray implements external.IExternalClientArray { + /** + * @hidden + */ + private server_base_; + /** + * Default Constructor. + */ + constructor(); + /** + * Factory method creating {@link IServerBase} object. + * + * This method {@link createServerBase createServerBase()} determines which protocol is used in this server, + * {@link ExternalClientArray}. If the protocol is determined, then {@link ExternalSystem external clients} who + * may connect to {@link ExternalClientArray this server} must follow the specified protocol. + * + * Overrides the {@link createServerBase createServerBase()} method to create and return one of them: + * + * - {@link ServerBase} + * - {@link WebServerBase} + * - {@link SharedWorkerServerBase} + * + * @return A new {@link IServerBase} object. + */ + protected abstract createServerBase(): protocol.IServerBase; + /** + * Add a newly connected remote client. + * + * When a {@link IClientDriver remote client} connects to this *master server of parallel processing system*, + * then this {@link ParallelClientArray} creates a child {@link ParallelSystem parallel client} object through + * the {@link createExternalClient createExternalClient()} method and {@link insert inserts} it. + * + * @param driver A communicator for external client. + */ + addClient(driver: protocol.IClientDriver): void; + /** + * (Deprecated) Factory method creating child object. + * + * The method {@link createChild createChild()} is deprecated. Don't use and override this. + * + * Note that, the {@link ParallelClientArray} is a server accepting {@link ParallelSystem parallel clients}. + * There's no way to creating the {@link ParallelSystem parallel clients} in advance before opening the server. + * + * @param xml An {@link XML} object represents the child {@link ParallelSystem} object. + * @return ```null``` + */ + createChild(xml: library.XML): System; + /** + * Factory method creating {@link ParallelSystem} object. + * + * The method {@link createExternalClient createExternalClient()} is a factory method creating a child + * {@link ParallelSystem} object, that is called whenever a parallel client has connected, by + * {@link addClient addClient()}. + * + * Overrides this {@link createExternalClient} method and creates a type of {@link ParallelSystem} object with + * the *driver* that communicates with the parallel client. After the creation, returns the {@link ParallelSystem} + * object. Then whenever a parallel client has connected, matched {@link ParallelSystem} object will be + * constructed and {@link insert inserted} into this {@link ParallelClientArray} object. + * + * @param driver A communicator with the parallel client. + * @return A newly created {@link ParallelSystem} object. + */ + protected abstract createExternalClient(driver: protocol.IClientDriver): System; + /** + * @inheritdoc + */ + open(port: number): void; + /** + * @inheritdoc + */ + close(): void; + } +} +declare namespace samchon.templates.parallel { + /** + * Mediator of Parallel Processing System. + * + * The {@link ParallelSystemArrayMediator} class be a **master** for its slave systems, and be a **slave** to its + * master system at the same time. This {@link ParallelSystemArrayMediator} be a **master **system, containing and + * managing {@link ParallelSystem} objects, which represent parallel slave systems, by extending + * {@link ParallelSystemArray} class. Also, be a **slave** system through {@link getMediator mediator} object, which is + * derived from the {@link SlaveSystem} class. + * + * As a **master**, you can specify this {@link ParallelSystemArrayMediator} class to be a master server accepting + * slave clients or a master client to connecting slave servers. Even both of them is possible. Extends one + * of them below and overrides abstract factory method(s) creating the child {@link ParallelSystem} object. + * + * - {@link ParallelClientArrayMediator}: A server accepting {@link ParallelSystem parallel clients}. + * - {@link ParallelServerArrayMediator}: A client connecting to {@link ParallelServer parallel servers}. + * - {@link ParallelServerClientArrayMediator}: Both of them. Accepts {@link ParallelSystem parallel clients} and + * connects to {@link ParallelServer parallel servers} at the same time. + * + * As a **slave**, you can specify this {@link ParallelSystemArrayMediator} to be a client slave connecting to + * master server or a server slave accepting master client by overriding the {@link createMediator} method. + * Overrides the {@link createMediator createMediator()} method and return one of them: + * + * - A client slave connecting to master server: + * - {@link MediatorClient} + * - {@link MediatorWebClient} + * - {@link MediatorSharedWorkerClient} + * - A server slave accepting master client: + * - {@link MediatorServer} + * - {@link MediatorWebServer} + * - {@link MediatorDedicatedWorkerServer} + * - {@link MediatorSharedWorkerServer} + * + * #### [Inherited] {@link ParallelSystemArray} + * @copydoc ParallelSystemArray + */ + abstract class ParallelSystemArrayMediator extends ParallelSystemArray { + /** + * @hidden + */ + private mediator_; + /** + * Default Constructor. + */ + constructor(); + /** + * Factory method creating a {@link MediatorSystem} object. + * + * The {@link createMediator createMediator()} is an abstract method creating the {@link MediatorSystem} object. + * + * You know what? this {@link ParallelSystemArrayMediator} class be a **master** for its slave systems, and be a + * **slave** to its master system at the same time. The {@link MediatorSystem} object makes it possible; be a + * **slave** system. This {@link createMediator} determines specific type of the {@link MediatorSystem}. + * + * Overrides the {@link createMediator createMediator()} method to create and return one of them following which + * protocol and which type of remote connection (server or client) will be used: + * + * - A client slave connecting to master server: + * - {@link MediatorClient} + * - {@link MediatorWebClient} + * - {@link MediatorSharedWorkerClient} + * - A server slave accepting master client: + * - {@link MediatorServer} + * - {@link MediatorWebServer} + * - {@link MediatorDedicatedWorkerServer} + * - {@link MediatorSharedWorkerServer} + * + * @return A newly created {@link MediatorSystem} object. + */ + protected abstract createMediator(): MediatorSystem; + /** + * Start mediator. + * + * If the {@link getMediator mediator} is a type of server, then opens the server accepting master client. + * Otherwise, the {@link getMediator mediator} is a type of client, then connects the master server. + */ + protected startMediator(): void; + /** + * Get {@link MediatorSystem} object. + * + * When you need to send an {@link Invoke} message to the master system of this + * {@link ParallelSystemArrayMediator}, then send to the {@link MediatorSystem} through this {@link getMediator}. + * + * ```typescript + * this.getMediator().sendData(...); + * ``` + * + * @return The {@link MediatorSystem} object. + */ + getMediator(): MediatorSystem; + /** + * @hidden + */ + protected _Complete_history(history: slave.InvokeHistory): boolean; + } +} +declare namespace samchon.templates.parallel { + /** + * Mediator of Parallel Processing System, a server accepting slave clients. + * + * The {@link ParallelClientArrayMediator} is an abstract class, derived from the {@link ParallelSystemArrayMediator} + * class, opening a server accepting {@link ParallelSystem parallel clients} as a **master**. + * + * Extends this {@link ParallelClientArrayMediator}, overrides {@link createServerBase createServerBase()} to + * determine which protocol to follow and {@link createExternalClient createExternalClient()} creating child + * {@link ParallelSystem} object. After the extending and overridings, open this server using the + * {@link open open()} method. + * + * #### [Inherited] {@link ParallelSystemArrayMediator} + * @copydoc ParallelSystemArrayMediator + */ + abstract class ParallelClientArrayMediator extends ParallelSystemArrayMediator implements external.IExternalClientArray { + /** + * @hidden + */ + private server_base_; + /** + * Default Constructor. + */ + constructor(); + /** + * Factory method creating {@link IServerBase} object. + * + * This method {@link createServerBase createServerBase()} determines which protocol is used in this server, + * {@link ParallelClientArrayMediator}. If the protocol is determined, then + * {@link ParallelSystem parallel clients} who may connect to {@link ParallelClientArrayMediator this server} + * must follow the specified protocol. + * + * Overrides the {@link createServerBase createServerBase()} method to create and return one of them: + * + * - {@link ServerBase} + * - {@link WebServerBase} + * - {@link SharedWorkerServerBase} + * + * @return A new {@link IServerBase} object. + */ + protected abstract createServerBase(): protocol.IServerBase; + /** + * Add a newly connected remote client. + * + * When a {@link IClientDriver remote client} connects to this *master server of parallel processing system*, + * then this {@link ParallelClientArrayMediator} creates a child {@link ParallelSystem parallel client} object + * through the {@link createExternalClient createExternalClient()} method and {@link insert inserts} it. + * + * @param driver A communicator for parallel client. + */ + addClient(driver: protocol.IClientDriver): void; + /** + * (Deprecated) Factory method creating child object. + * + * The method {@link createChild createChild()} is deprecated. Don't use and override this. + * + * Note that, the {@link ParallelClientArrayMediator} is a server accepting {@link ParallelSystem parallel + * clients} as a master. There's no way to creating the {@link ParallelSystem parallel clients} in advance before + * opening the server. + * + * @param xml An {@link XML} object represents the child {@link ParallelSystem} object. + * @return null + */ + createChild(xml: library.XML): System; + /** + * Factory method creating {@link ParallelSystem} object. + * + * The method {@link createExternalClient createExternalClient()} is a factory method creating a child + * {@link ParallelSystem} object, that is called whenever a parallel client has connected, by + * {@link addClient addClient()}. + * + * Overrides this {@link createExternalClient} method and creates a type of {@link ParallelSystem} object with + * the *driver* that communicates with the parallel client. After the creation, returns the {@link ParallelSystem} + * object. Then whenever a parallel client has connected, matched {@link ParallelSystem} object will be + * constructed and {@link insert inserted} into this {@link ParallelClientArrayMediator} object. + * + * @param driver A communicator with the parallel client. + * @return A newly created {@link ParallelSystem} object. + */ + protected abstract createExternalClient(driver: protocol.IClientDriver): System; + /** + * @inheritdoc + */ + open(port: number): void; + /** + * @inheritdoc + */ + close(): void; + } +} +declare namespace samchon.templates.parallel { + /** + * A driver for parallel slave server. + * + * The {@link ParallelServer} is an abstract class, derived from the {@link ParallelSystem} class, connecting to + * remote, parallel **slave** server. Extends this {@link ParallelServer} class and overrides the + * {@link createServerConnector createServerConnector()} method following which protocol the **slave** server uses. + * + * #### [Inherited] {@link ParallelSystem} + * @copydoc ParallelSystem + */ + abstract class ParallelServer extends ParallelSystem implements IParallelServer { + /** + * IP address of target external system to connect. + */ + protected ip: string; + /** + * Port number of target external system to connect. + */ + protected port: number; + /** + * Construct from parent {@link ParallelSystemArray}. + * + * @param systemArray The parent {@link ParallelSystemArray} object. + */ + constructor(systemArray: ParallelSystemArray); + /** + * Factory method creating {@link IServerConnector} object. + * + * The {@link createServerConnector createServerConnector()} is an abstract method creating + * {@link IServerConnector} object. Overrides and returns one of them, considering which protocol the slave server + * follows: + * + * - {@link ServerConnector} + * - {@link WebServerConnector} + * - {@link DedicatedWorkerServerConnector} + * - {@link SharedWorkerServerConnector} + * + * @return A newly created {@link IServerConnector} object. + */ + protected abstract createServerConnector(): protocol.IServerConnector; + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.templates.parallel { + /** + * Master of Parallel Processing System, a client connecting to slave servers. + * + * The {@link ParallelServerArray} is an abstract class, derived from the {@link ParallelSystemArray} class, + * connecting to {@link IParallelServer parallel servers}. + * + * Extends this {@link ParallelServerArray} and overrides {@link createChild createChild()} method creating child + * {@link IParallelServer} object. After the extending and overriding, construct children {@link IParallelServer} + * objects and call the {@link connect connect()} method. + * + * #### [Inherited] {@link ParallelSystemArray} + * @copydoc ParallelSystemArray + */ + abstract class ParallelServerArray extends ParallelSystemArray implements external.IExternalServerArray { + /** + * Default Constructor. + */ + constructor(); + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.templates.parallel { + /** + * Mediator of Parallel Processing System, a client connecting to slave servers. + * + * The {@link ParallelServerArrayMediator} is an abstract class, derived from the {@link ParallelSystemArrayMediator} + * class, connecting to {@link IParallelServer parallel servers}. + * + * Extends this {@link ParallelServerArrayMediator} and overrides {@link createChild createChild()} method creating + * child {@link IParallelServer} object. After the extending and overriding, construct children + * {@link IParallelServer} objects and call the {@link connect connect()} method. + * + * #### [Inherited] {@link ParallelSystemArrayMediator} + * @copydoc ParallelSystemArrayMediator + */ + abstract class ParallelServerArrayMediator extends ParallelSystemArrayMediator implements external.IExternalServerArray { + /** + * Default Constructor. + */ + constructor(); + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.templates.parallel { + /** + * Master of Parallel Processing System, be a server and client at the same time. + * + * The {@link ParallelServerClientArray} is an abstract class, derived from the {@link ParallelSystemArray} class, + * opening a server accepting {@link ParallelSystem parallel clients} and being a client connecting to + * {@link IParallelServer parallel servers} at the same time. + * + * Extends this {@link ParallelServerClientArray} and overrides below methods. After the overridings, open server + * with {@link open open()} method and connect to {@link IParallelServer parallel servers} through the + * {@link connect connect()} method. + * + * - {@link createServerBase createServerBase()} + * - {@link createExternalClient createExternalClient()} + * - {@link createExternalServer createExternalServer()} + * + * #### [Inherited] {@link ParallelSystemArray} + * @copydoc ParallelClientArray + */ + abstract class ParallelServerClientArray extends ParallelClientArray implements external.IExternalServerClientArray { + /** + * Default Constructor. + */ + constructor(); + /** + * Factory method of a child Entity. + * + * This method is migrated to {@link createExternalServer}. Override the {@link createExternalServer} method. + * + * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. + * @return A new child Entity via {@link createExternalServer createExternalServer()}. + */ + createChild(xml: library.XML): System; + /** + * Factory method creating an {@link IParallelServer} object. + * + * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. + * @return A newly created {@link IParallelServer} object. + */ + protected abstract createExternalServer(xml: library.XML): System; + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.templates.parallel { + /** + * Mediator of Parallel Processing System, be a server and client at the same time as a **master**. + * + * The {@link ParallelServerClientArrayMediator} is an abstract class, derived from the + * {@link ParallelSystemArrayMediator} class, opening a server accepting {@link ParallelSystem parallel clients} and + * being a client connecting to {@link IParallelServer parallel servers} at the same time. + * + * Extends this {@link ParallelServerClientArrayMediator} and overrides below methods. After the overridings, open + * server with {@link open open()} method and connect to {@link IParallelServer parallel servers} through the + * {@link connect connect()} method. + * + * - {@link createServerBase createServerBase()} + * - {@link createExternalClient createExternalClient()} + * - {@link createExternalServer createExternalServer()} + * + * #### [Inherited] {@link ParallelSystemArrayMediator} + * @copydoc ParallelClientArrayMediator + */ + abstract class ParallelServerClientArrayMediator extends ParallelClientArrayMediator implements external.IExternalServerClientArray { + /** + * Default Constructor. + */ + constructor(); + /** + * Factory method of a child Entity. + * + * This method is migrated to {@link createExternalServer}. Override the {@link createExternalServer} method. + * + * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. + * @return A new child Entity via {@link createExternalServer createExternalServer()}. + */ + createChild(xml: library.XML): System; + /** + * Factory method creating an {@link IParallelServer} object. + * + * @param xml An {@link XML} object represents child element, so that can identify the type of child to create. + * @return A newly created {@link IParallelServer} object. + */ + protected abstract createExternalServer(xml: library.XML): System; + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.templates.parallel { + /** + * An interface for a parallel slave server driver. + * + * The easiest way to defining a driver for parallel **slave** server is extending {@link ParallelServer} class. + * However, if you've to interact with a prallel **slave** system who can be both server and client, them make a class + * (let's name it **BaseSystem**) extending the {@link ParallelSystem} class. At next, make a new class (now, I name it + * **BaseServer**) extending the **BaseSystem** and implements this interface {@link IParallelServer}. Define the + * **BaseServer** following those codes on below: + * + * + * + * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) + * @author Jeongho Nam + */ + interface IParallelServer extends ParallelSystem { + /** + * Connect to slave server. + */ + connect(): void; + } +} +declare namespace samchon.templates.parallel { + /** + * History of an {@link Invoke} message. + * + * The {@link PRInvokeHistory} is a class archiving history log of an {@link Invoke} message which requests the + * *parallel process*, created whenever {@link ParallelSystemArray.sendSegmentData} or + * {@link ParallelSystemArray.sendSegmentData} is called. + * + * When the *parallel process* has completed, then {@link complete complete()} is called and the *elapsed time* is + * determined. The elapsed time is utilized for computation of {@link ParallelSystem.getPerformance performance index} + * of each {@link ParallelSystem parallel slave system}. + * + * + * + * + * + * @handbook [Templates - Parallel System](https://github.com/samchon/framework/wiki/TypeScript-Templates-Parallel_System) + * @author Jeongho Nam + */ + class PRInvokeHistory extends slave.InvokeHistory { + /** + * @hidden + */ + private first; + /** + * @hidden + */ + private last; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from an {@link Invoke} message. + * + * @param invoke An {@link Invoke} message requesting a *parallel process*. + */ + constructor(invoke: protocol.Invoke); + /** + * Get initial piece's index. + * + * Returns initial piece's index in the section of requested *parallel process*. + * + * @return The initial index. + */ + getFirst(): number; + /** + * Get final piece's index. + * + * Returns initial piece's index in the section of requested *parallel process*. The range used is + * [*first*, *last*), which contains all the pieces' indices between *first* and *last*, including the piece + * pointed by index *first*, but not the piece pointed by the index *last*. + * + * @return The final index. + */ + getLast(): number; + /** + * Compute number of allocated pieces. + */ + computeSize(): number; + } +} +declare namespace samchon.templates.service { + /** + * A driver of remote client. + * + * The {@link Client} is an abstract class representing and interacting with a remote client. It deals the network + * communication with the remote client and shifts {@link Invoke} message to related {@link User} and {@link Service} + * objects. + * + * Extends this {@link Client} class and override the {@link createService} method, a factory method creating a child + * {@link Service} object. Note that, {@link Client} represents a remote client, not *an user*, a specific *web page* + * or *service*. Do not define logics about user or account information. It must be declared in the parent + * {@link User} class. Also, don't define processes of a specific a web page or service. Defines them in the child + * {@link Service} class. + * + * + * + * + * + * @handbook [Templates - Cloud Service](https://github.com/samchon/framework/wiki/TypeScript-Templates-Cloud_Service) + * @author Jeongho Nam + */ + abstract class Client implements protocol.IProtocol { + /** + * @hidden + */ + private user_; + /** + * @hidden + */ + private no_; + /** + * @hidden + */ + private communicator_; + /** + * @hidden + */ + private service_; + /** + * Construct from parent {@link User} and communicator. + * + * @param user Parent {@link User} object. + * @param driver Communicator with remote client. + */ + constructor(user: User, driver: protocol.WebClientDriver); + /** + * Default Destructor. + * + * This {@link destructor destructor()} method is called when the {@link Client} object is destructed and this + * {@link Client} object is destructed when connection with the remote client is closed or this {@link Client} + * object is {@link User.erase erased} from its parent {@link User} object. + * + * Note that, don't call this {@link destructor destructor()} method by yourself. It must be called automatically + * by those *destruction* cases. Also, if your derived {@link Client} class has something to do on the + * *destruction*, then overrides this {@link destructor destructor()} method and defines the something to do. + * Overriding this {@link destructor destructor()}, don't forget to calling ```super.destructor();``` on tail. + * + * ```typescript + * class MyUser extends protocol.service.Client + * { + * protected destructor(): void + * { + * // DO SOMETHING + * this.do_something(); + * + * // CALL SUPER.DESTRUCTOR() ON TAIL. DON'T FORGET THIS + * super.destructor(); + * } + * } + * ``` + */ + protected destructor(): void; + /** + * Factory method creating {@link Service} object. + * + * @param path Requested path. + * @return A newly created {@link Service} object or ```null```. + */ + protected abstract createService(path: string): Service; + /** + * Close connection. + */ + close(): void; + /** + * Get parent {@link User} object. + * + * Get the parent {@link User} object, who is groupping {@link Client} objects with same session id. + * + * @return The parent {@link User} object. + */ + getUser(): User; + /** + * Get child {@link Service} object. + * + * @return The child {@link Service} object. + */ + getService(): Service; + /** + * Get sequence number. + * + * Get sequence number of this {@link Client} object in the parent {@link User} object. This sequence number also + * be a *key* in the parent {@link User} object, who extended the ```std.HashMap```. + * + * @return Sequence number. + */ + getNo(): number; + /** + * Change related {@link Service} object. + * + * @param path Requested, identifier path. + */ + protected changeService(path: string): void; + /** + * Change {@link Service} to another. + * + * @param service {@link service} object to newly assigned. + */ + protected changeService(service: Service): void; + /** + * Send an {@link Invoke} message. + * + * Sends an {@link Invoke} message to remote client. + * + * @param invoke An {@link Invoke} messgae to send to remote client. + */ + sendData(invoke: protocol.Invoke): void; + /** + * Handle a replied {@link Invoke} message. + * + * The default {@link Client.replyData Client.replyData()} shifts chain to its parent {@link User} and belonged + * {@link Service} objects, by calling the the {@link User.replyData User.replyData()} and + * {@link Service.replyData Service.replyData()} methods. + * + * Note that, {@link Client} represents a remote client, not *an user*, a specific *web page* or *service*. Do not + * define logics about user or account information. It must be declared in the parent {@link User} class. Also, + * don't define processes of a specific a web page or service. Defines them in the child {@link Service} class. + * + * ```typescript + * class protocol.service.Client + * { + * public replyData(invoke: protocol.Invoke): void + * { + * // SHIFT TO PARENT USER + * // THE PARENT USER ALSO MAY SHIFT TO ITS PARENT SERVER + * this.getUser().replyData(invoke); + * + * // SHIFT TO BELOGED SERVICE + * if (this.getService() != null) + * this.getService().replyData(invoke); + * } + * } + * + * class MyClient extends protocol.service.Client + * { + * public replyData(invoke: protocol.Invoke): void + * { + * if (invoke.getListener() == "do_something_in_client_level") + * this.do_something_in_client_level(); + * else + * super.replyData(invoke); + * } + * } + * ``` + * + * @param invoke An {@link Invoke invoke} message to be handled in {@link Client} level. + */ + replyData(invoke: protocol.Invoke): void; + } +} +/** + * A system template for Cloud Service. + * + * @handbook [Templates - Cloud Service](https://github.com/samchon/framework/wiki/TypeScript-Templates-Cloud_Service) + * @author Jeongho Nam + */ +declare namespace samchon.templates.service { + /** + * A cloud server. + * + * The {@link Server} is an abstract server class, who can build a real-time cloud server, that is following the + * web-socket protocol. Extends this {@link Server} and related classes and overrides abstract methods under below. + * After the overridings, open this {@link Server cloud server} using the {@link open open()} method. + * + * - Objects in composite relationship and their factory methods + * - {@link User}: {@link Server.createUser Server.createUser()} + * - {@link Client}: {@link User.createClient User.createClient()} + * - {@link Service}: {@link Client.createService Client.createService()} + * - {@link Invoke} message chains; {@link IProtocol.replyData replyData} + * - {@link Server.replyData} + * - {@link User.replyData} + * - {@link Client.replyData} + * - {@link Service.replyData} + * + * + * + * + * + * @handbook [Templates - Cloud Service](https://github.com/samchon/framework/wiki/TypeScript-Templates-Cloud_Service) + * @author Jeongho Nam + */ + abstract class Server extends protocol.WebServer implements protocol.IProtocol { + /** + * @hidden + */ + private session_map_; + /** + * @hidden + */ + private account_map_; + /** + * Default Constructor. + */ + constructor(); + /** + * Factory method creating {@link User} object. + * + * @return A newly created {@link User} object. + */ + protected abstract createUser(): User; + /** + * Test wheter an {@link User} exists with the *accountID*. + * + * @param accountID Account id of {@link User} to find. + * @return Exists or not. + */ + has(accountID: string): boolean; + /** + * Get an {@link User} object by its *accountID*. + * + * @param accountID Account id of {@link User} to get. + * @return An {@link User} object. + */ + get(accountID: string): User; + /** + * Send an {@link Invoke} message. + * + * Sends an {@link Invoke} message to all remote clients through the belonged {@link User} and {@link Client} + * objects. Sending the {@link Invoke} message to all remote clients, it's came true by passing through + * {@link User.sendData User.sendData()}. And the {@link User.sendData} also pass through the + * {@link Client.sendData Client.sendData()}. + * + * ```typescript + * class protocol.service.Server + * { + * public sendData(invoke: Invoke): void + * { + * for (user: User in this) + * for (client: Client in user) + * client.sendData(invoke); + * } + * } + * ``` + * + * @param invoke {@link Invoke} message to send to all remote clients. + */ + sendData(invoke: protocol.Invoke): void; + /** + * Handle a replied {@link Invoke} message. + * + * The {@link Server.replyData Server.replyData()} is an abstract method that handling {@link Invoke} message + * that should be handled in the {@link Server} level. Overrides this {@link replyData replyData()} method and + * defines what to do with the {@link Invoke} message in this {@link Server} level. + * + * @param invoke An {@link Invoke invoke} message to be handled in {@link Server} level. + */ + abstract replyData(invoke: protocol.Invoke): void; + /** + * Add a newly connected remote client. + * + * When a {@link WebClientDriver remote client} connects to this cloud server, then {@link Server} queries the + * {WebClientDriver.getSessionID session id} of the {@link WebClientDriver remote client}. If the + * {WebClientDriver.getSessionID session id} is new one, then creates a new {@link User} object. + * + * At next, creates a {@link Client} object who represents the newly connected remote client and insert the + * {@link Client} object to the matched {@link User} object which is new or ordinary one following the + * {WebClientDriver.getSessionID session id}. At last, a {@link Service} object can be created with referencing + * the {@link WebClientDriver.getPath path}. + * + * List of objects can be created by this method. + * - {@link User} by {@link createUser createUser()}. + * - {@link Client} by {@link User.createClient User.createClient()}. + * - {@link Service} by {@link Client.createService Client.createService()}. + * + * @param driver A web communicator for remote client. + */ + addClient(driver: protocol.WebClientDriver): void; + /** + * @hidden + */ + private _Erase_user(user); + } +} +declare namespace samchon.templates.service { + /** + * A service. + * + * The {@link Service} is an abstract class who represents a service, that is providing functions a specific page. + * + * Extends the {@link Service} class and defines its own service, which to be provided for the specific weg page, + * by overriding the {@link replyData replyData()} method. Note that, the service, functions for the specific page + * should be defined in this {@link Service} class, not its parent {@link Client} class who represents a remote client + * and takes communication responsibility. + * + * + * + * + * + * @handbook [Templates - Cloud Service](https://github.com/samchon/framework/wiki/TypeScript-Templates-Cloud_Service) + * @author Jeongho Nam + */ + abstract class Service implements protocol.IProtocol { + /** + * @hidden + */ + private client_; + /** + * @hidden + */ + private path_; + /** + * Construct from parent {@link Client} and requested path. + * + * @param client Driver of remote client. + * @param path Requested path that identifies this {@link Service}. + */ + constructor(client: Client, path: string); + /** + * Default Destructor. + * + * This {@link destructor destructor()} method is call when the {@link Service} object is destructed and the + * {@link Service} object is destructed when its parent {@link Client} object has + * {@link Client.destructor destructed} or the {@link Client} object {@link Client.changeService changed} its + * child {@link Service service} object to another one. + * + * Note that, don't call this {@link destructor destructor()} method by yourself. It must be called automatically + * by those *destruction* cases. Also, if your derived {@link Service} class has something to do on the + * *destruction*, then overrides this {@link destructor destructor()} method and defines the something to do. + */ + protected destructor(): void; + /** + * Get client. + */ + getClient(): Client; + /** + * Get requested path. + */ + getPath(): string; + /** + * Send an {@link Invoke} message. + * + * Sends an {@link Invoke} message to remote system through parent {@link Client} object ({@link Client.sendData}). + * + * @param invoke An {@link Invoke} message to send to the remte system. + */ + sendData(invoke: protocol.Invoke): void; + /** + * @inheritdoc + */ + abstract replyData(invoke: protocol.Invoke): void; + } +} +declare namespace samchon.templates.service { + /** + * An user. + * + * The {@link User} is an abstract class groupping {@link Client} objects, who communicates with remote client, with + * same *session id*. This {@link User} represents a *remote user* literally. Within framework of remote system, + * an {@link User} corresponds to a web-browser and a {@link Client} represents a window in the web-browser. + * + * Extends this {@link User} class and override the {@link createClient} method, a factory method creating a child + * {@link Client} object. I repeat, the {@link User} class represents a *remote user*, groupping {@link Client} + * objects with same *session id*. If your cloud server has some processes to be handled in the **user level**, then + * defines method in this {@link User} class. Methods managing **account** under below are some of them: + * + * - {@link setAccount setAccount()} + * - {@link getAccountID getAccountID()} + * - {@link getAuthority getAuthority()} + * + * The children {@link Client} objects, they're contained with their key, the {@link Client.getNo sequence number}. + * If you {@link User.erase erase} the children {@link Client} object by yourself, then their connection with the + * remote clients will be {@link Client.close closed} and their {@link Client.destructor destruction method} will be + * called. If you remove {@link clear all children}, then this {@link User} object will be also + * {@link destructor destructed} and erased from the parent {@link Server} object. + * + * + * + * + * + * @handbook [Templates - Cloud Service](https://github.com/samchon/framework/wiki/TypeScript-Templates-Cloud_Service) + * @author Jeongho Nam + */ + abstract class User extends collections.HashMapCollection implements protocol.IProtocol { + /** + * @hidden + */ + private server_; + /** + * @hidden + */ + private session_id_; + /** + * @hidden + */ + private sequence_; + /** + * @hidden + */ + private account_id_; + /** + * @hidden + */ + private authority_; + /** + * Construct from its parent {@link Server}. + * + * @param server The parent {@link Server} object. + */ + constructor(server: Server); + /** + * Default Destructor. + * + * This {@link destructor destructor()} method is called when the {@link User} object is destructed. The + * {@link User} object is destructed when connections with the remote clients are all closed, that is all the + * children {@link Client} objects are all removed, and 30 seconds has left. If some remote client connects + * within the 30 seconds, then the {@link User} object doesn't be destructed. + * + * Note that, don't call this {@link destructor destructor()} method by yourself. It must be called automatically + * by those *destruction* cases. Also, if your derived {@link User} class has something to do on the + * *destruction*, then overrides this {@link destructor destructor()} method and defines the something to do. + * Overriding this {@link destructor destructor()}, don't forget to calling ```super.destructor();``` on tail. + * + * ```typescript + * class MyUser extends protocol.service.User + * { + * protected destructor(): void + * { + * // DO SOMETHING + * this.do_something(); + * + * // CALL SUPER.DESTRUCTOR() ON TAIL. DON'T FORGET THIS + * super.destructor(); + * } + * } + * ``` + */ + protected destructor(): void; + /** + * Factory method creating a {@link Client} object. + * + * @param driver A web communicator for remote client. + * @return A newly created {@link Client} object. + */ + protected abstract createClient(driver: protocol.WebClientDriver): Client; + /** + * @hidden + */ + private _Handle_erase_client(event); + /** + * Get parent {@lin Server} object. + * + * @return Parent {@link Server} object. + */ + getServer(): Server; + /** + * Get account id. + * + * @return Account ID. + */ + getAccountID(): string; + /** + * Get authority. + * + * @return Authority + */ + getAuthority(): number; + /** + * Set *account id* and *authority*. + * + * The {@link setAccount setAccount()} is a method configuring *account id* and *authority* of this {@link User}. + * + * After the configuring, the {@link getAccountID account id} is enrolled into the parent {@link Server} as a + * **key** for this {@link User} object. You can test existence and access this {@link User} object from + * {@link Server.has Server.has()} and {@link Server.get Server.get()} with the {@link getAccountID account id}. + * Of course, if ordinary {@link getAccountID account id} had existed, then the ordinary **key** will be + * replaced. + * + * As you suggest, this {@link setAccount setAccount()} is something like a **log-in** function. If what you want + * is not **logging-in**, but **logging-out**, then configure the *account id* to empty string ``""```` or call + * the {@link lgout logout()} method. + * + * @param id To be account id. + * @param authority To be authority. + */ + setAccount(id: string, authority: number): void; + /** + * Log-out. + * + * This {@link logout logout()} method configures {@link getAccountID account id} to empty string and + * {@link getAuthority authority} to zero. + * + * The ordinary {@link getAccountID account id} will be also erased from the parent {@link Server} object. You + * can't access this {@link User} object from {@link Server.has Server.has()} and {@link Server.get Server.get()} + * with the ordinary {@link getAccountID account id} more. + */ + logout(): void; + /** + * Send an {@link Invoke} message. + * + * Sends an {@link Invoke} message to all remote clients through the belonged {@link Client} objects. Sending the + * {@link Invoke} message to all remote clients, it's came true by passing through the + * {@link Client.sendData Client.sendData()} methods. + * + * ```typescript + * class protocol.service.User + * { + * public sendData(invoke: Invoke): void + * { + * for (let it = this.begin(); !it.equals(this.end()); it = it.next()) + * it.second.sendData(invoke); + * } + * } + * ``` + * + * @param invoke {@link Invoke} message to send to all remote clients. + */ + sendData(invoke: protocol.Invoke): void; + /** + * Handle a replied {@link Invoke} message. + * + * The default {@link User.replyData User.replyData()} shifts chain to its parent {@link Server} object, by + * calling the {@link Server.replyData Server.replyData()} method. If there're some {@link Invoke} message to be + * handled in this {@link User} level, then override this method and defines what to do with the {@link Invoke} + * message in this {@link User} level. + * + * ```typescript + * class protocol.service.User + * { + * public replyData(invoke: protocol.Invoke): void + * { + * this.getServer().replyData(invoke); + * } + * } + * + * class MyUser extends protocol.service.User + * { + * public replyData(invoke: protocol.Invoke): void + * { + * if (invoke.apply(this) == false) // IS TARGET TO BE HANDLED IN THIS USER LEVEL + * super.replyData(invoke); // SHIFT TO SERVER + * } + * } + * ``` + * + * @param invoke An {@link Invoke invoke} message to be handled in {@link User} level. + */ + replyData(invoke: protocol.Invoke): void; + } +} +declare namespace samchon.templates.slave { + /** + * An {@link Invoke} message which represents a **process**. + * + * + * + * #### [Inherited] {@link Invoke} + * @copydoc Invoke + */ + class PInvoke extends protocol.Invoke { + /** + * @hidden + */ + private history_; + /** + * @hidden + */ + private slave_system_; + /** + * @hidden + */ + private hold_; + /** + * Initializer Constructor. + * + * @param invoke Original {@link Invoke} message. + * @param history {@link InvokeHistory} object archiving execution time. + * @param slaveSystem Related {@link SlaveSystem} object who gets those processes from its master. + */ + constructor(invoke: protocol.Invoke, history: InvokeHistory, slaveSystem: SlaveSystem); + /** + * Get history object. + * + * Get {@link InvokeHistory} object who is archiving execution time of this process. + */ + getHistory(): InvokeHistory; + /** + * Is the reporting hold? + */ + isHold(): boolean; + /** + * Hold reporting completion to master. + */ + hold(): void; + /** + * Report completion. + */ + complete(): void; + } +} +declare namespace samchon.templates.slave { + interface ISlaveClient extends SlaveSystem { + connect(ip: string, port: number): void; + } + abstract class SlaveClient extends SlaveSystem implements ISlaveClient { + /** + * Default Constructor. + */ + constructor(); + /** + * @inheritdoc + */ + protected abstract createServerConnector(): protocol.IServerConnector; + /** + * @inheritdoc + */ + connect(ip: string, port: number): void; + } +} +declare namespace samchon.templates.slave { + interface ISlaveServer extends SlaveSystem, protocol.IServer { + } + abstract class SlaveServer extends SlaveSystem implements ISlaveServer { + /** + * @hidden + */ + private server_base_; + /** + * Default Constructor. + */ + constructor(); + /** + * @inheritdoc + */ + protected abstract createServerBase(): protocol.IServerBase; + /** + * @inheritdoc + */ + open(port: number): void; + /** + * @inheritdoc + */ + close(): void; + /** + * @inheritdoc + */ + addClient(driver: protocol.IClientDriver): void; + } +} diff --git a/samchon/samchon-tests.ts b/samchon/samchon-tests.ts new file mode 100644 index 0000000000..3c805025ac --- /dev/null +++ b/samchon/samchon-tests.ts @@ -0,0 +1,2 @@ +import samchon = require("samchon"); +console.log(samchon); \ No newline at end of file diff --git a/samchon/tsconfig.json b/samchon/tsconfig.json new file mode 100644 index 0000000000..ec6c511b01 --- /dev/null +++ b/samchon/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": false, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "samchon-tests.ts" + ] +} \ No newline at end of file diff --git a/selenium-webdriver/chrome.d.ts b/selenium-webdriver/chrome.d.ts index ce26566f02..2604b99e89 100644 --- a/selenium-webdriver/chrome.d.ts +++ b/selenium-webdriver/chrome.d.ts @@ -1,5 +1,6 @@ import * as webdriver from './index'; import * as remote from './remote'; +import * as http from './http'; /** * Creates a new WebDriver client for Chrome. @@ -8,15 +9,19 @@ import * as remote from './remote'; */ export class Driver extends webdriver.WebDriver { /** - * @param {(webdriver.Capabilities|Options)=} opt_config The configuration - * options. - * @param {remote.DriverService=} opt_service The session to use; will use - * the {@link getDefaultService default service} by default. - * @param {webdriver.promise.ControlFlow=} opt_flow The control flow to use, or - * {@code null} to use the currently active flow. - * @constructor + * Creates a new session with the ChromeDriver. + * + * @param {(Capabilities|Options)=} opt_config The configuration options. + * @param {(remote.DriverService|http.Executor)=} opt_serviceExecutor Either + * a DriverService to use for the remote end, or a preconfigured executor + * for an externally managed endpoint. If neither is provided, the + * {@linkplain ##getDefaultService default service} will be used by + * default. + * @param {promise.ControlFlow=} opt_flow The control flow to use, or `null` + * to use the currently active flow. + * @return {!Driver} A new driver instance. */ - constructor(opt_config?: Options | webdriver.Capabilities, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); + static createSession(opt_config?: Options | webdriver.CreateSessionCapabilities, opt_service?: remote.DriverService | http.Executor, opt_flow?: webdriver.promise.ControlFlow): Driver; } interface IOptionsValues { @@ -304,7 +309,7 @@ export class Options { * Creates {@link remote.DriverService} instances that manage a ChromeDriver * server. */ -export class ServiceBuilder { +export class ServiceBuilder extends remote.DriverService.Builder { /** * @param {string=} opt_exe Path to the server executable to use. If omitted, * the builder will attempt to locate the chromedriver on the current @@ -315,15 +320,6 @@ export class ServiceBuilder { */ constructor(opt_exe?: string); - /** - * Sets the port to start the ChromeDriver on. - * @param {number} port The port to use, or 0 for any free port. - * @return {!ServiceBuilder} A self reference. - * @throws {Error} If the port is invalid. - */ - usingPort(port: number): ServiceBuilder; - - /** * Sets which port adb is listening to. _The ChromeDriver will connect to adb * if an {@linkplain Options#androidPackage Android session} is requested, but @@ -332,7 +328,7 @@ export class ServiceBuilder { * @param {number} port Which port adb is running on. * @return {!ServiceBuilder} A self reference. */ - setAdbPort(port: number): ServiceBuilder; + setAdbPort(port: number): this; /** @@ -341,14 +337,14 @@ export class ServiceBuilder { * @param {string} path Path of the log file to use. * @return {!ServiceBuilder} A self reference. */ - loggingTo(path: string): ServiceBuilder; + loggingTo(path: string): this; /** * Enables verbose logging. * @return {!ServiceBuilder} A self reference. */ - enableVerboseLogging(): ServiceBuilder; + enableVerboseLogging(): this; /** @@ -357,45 +353,7 @@ export class ServiceBuilder { * @param {number} n The number of threads to use. * @return {!ServiceBuilder} A self reference. */ - setNumHttpThreads(n: number): ServiceBuilder; - - - /** - * Sets the base path for WebDriver REST commands (e.g. '/wd/hub'). - * By default, the driver will accept commands relative to '/'. - * @param {string} path The base path to use. - * @return {!ServiceBuilder} A self reference. - */ - setUrlBasePath(path: string): ServiceBuilder; - - - /** - * Defines the stdio configuration for the driver service. See - * {@code child_process.spawn} for more information. - * @param {(string|!Array.)} config The - * configuration to use. - * @return {!ServiceBuilder} A self reference. - */ - setStdio(config: string | Array): ServiceBuilder; - - - /** - * Defines the environment to start the server under. This settings will be - * inherited by every browser session started by the server. - * @param {!Object.} env The environment to use. - * @return {!ServiceBuilder} A self reference. - */ - withEnvironment(env: { [key: string]: string }): ServiceBuilder; - - - /** - * Creates a new DriverService using this instance's current configuration. - * @return {remote.DriverService} A new driver service using this instance's - * current configuration. - * @throws {Error} If the driver exectuable was not specified and a default - * could not be found on the current PATH. - */ - build(): remote.DriverService; + setNumHttpThreads(n: number): this; } /** diff --git a/selenium-webdriver/edge.d.ts b/selenium-webdriver/edge.d.ts index b18a959700..3fb3408b1f 100644 --- a/selenium-webdriver/edge.d.ts +++ b/selenium-webdriver/edge.d.ts @@ -3,14 +3,17 @@ import * as remote from './remote'; export class Driver extends webdriver.WebDriver { /** + * Creates a new browser session for Microsoft's Edge browser. + * * @param {(capabilities.Capabilities|Options)=} opt_config The configuration * options. * @param {remote.DriverService=} opt_service The session to use; will use * the {@linkplain #getDefaultService default service} by default. * @param {promise.ControlFlow=} opt_flow The control flow to use, or * {@code null} to use the currently active flow. + * @return {!Driver} A new driver instance. */ - constructor(opt_config?: webdriver.Capabilities | Options, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); + static createSession(opt_config?: webdriver.CreateSessionCapabilities, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow): Driver; /** * This function is a no-op as file detectors are not supported by this @@ -56,14 +59,14 @@ export class Options { * merge these options into, if any. * @return {!capabilities.Capabilities} The capabilities. */ - toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; + toCapabilities(opt_capabilities?: webdriver.Capabilities): webdriver.Capabilities; } /** * Creates {@link remote.DriverService} instances that manage a * MicrosoftEdgeDriver server in a child process. */ -export class ServiceBuilder { +export class ServiceBuilder extends remote.DriverService.Builder { /** * @param {string=} opt_exe Path to the server executable to use. If omitted, * the builder will attempt to locate the MicrosoftEdgeDriver on the current @@ -72,40 +75,6 @@ export class ServiceBuilder { * MicrosoftEdgeDriver cannot be found on the PATH. */ constructor(opt_exe?: string); - - /** - * Defines the stdio configuration for the driver service. See - * {@code child_process.spawn} for more information. - * @param {(string|!Array.)} - * config The configuration to use. - * @return {!ServiceBuilder} A self reference. - */ - setStdio(config: string | Array): ServiceBuilder; - - /** - * Sets the port to start the MicrosoftEdgeDriver on. - * @param {number} port The port to use, or 0 for any free port. - * @return {!ServiceBuilder} A self reference. - * @throws {Error} If the port is invalid. - */ - usingPort(port: number): ServiceBuilder; - - /** - * Defines the environment to start the server under. This settings will be - * inherited by every browser session started by the server. - * @param {!Object.} env The environment to use. - * @return {!ServiceBuilder} A self reference. - */ - withEnvironment(env: Object): ServiceBuilder; - - /** - * Creates a new DriverService using this instance's current configuration. - * @return {!remote.DriverService} A new driver service using this instance's - * current configuration. - * @throws {Error} If the driver exectuable was not specified and a default - * could not be found on the current PATH. - */ - build(): remote.DriverService; } /** diff --git a/selenium-webdriver/firefox.d.ts b/selenium-webdriver/firefox.d.ts index 7678c404ce..6746c3c683 100644 --- a/selenium-webdriver/firefox.d.ts +++ b/selenium-webdriver/firefox.d.ts @@ -1,5 +1,6 @@ import * as webdriver from './index'; import * as remote from './remote'; +import * as http from './http'; /** * Manages a Firefox subprocess configured for use with WebDriver. @@ -197,11 +198,13 @@ export class Options { setProxy(proxy: webdriver.ProxyConfig): Options; /** - * Sets whether to use Mozilla's Marionette to drive the browser. + * Sets whether to use Mozilla's geckodriver to drive the browser. This option + * is enabled by default and required for Firefox 47+. * - * @see https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver + * @param {boolean} enable Whether to enable the geckodriver. + * @see https://github.com/mozilla/geckodriver */ - useMarionette(marionette: any): Options; + useGeckoDriver(enable: boolean): Options; /** * Converts these options to a {@link capabilities.Capabilities} instance. @@ -235,14 +238,32 @@ export function prepareProfile(profile: string | any, port: number): any; */ export class Driver extends webdriver.WebDriver { /** + * Creates a new Firefox session. + * * @param {(Options|capabilities.Capabilities|Object)=} opt_config The * configuration options for this driver, specified as either an * {@link Options} or {@link capabilities.Capabilities}, or as a raw hash * object. + * @param {(http.Executor|remote.DriverService)=} opt_executor Either a + * pre-configured command executor to use for communicating with an + * externally managed remote end (which is assumed to already be running), + * or the `DriverService` to use to start the geckodriver in a child + * process. + * + * If an executor is provided, care should e taken not to use reuse it with + * other clients as its internal command mappings will be updated to support + * Firefox-specific commands. + * + * _This parameter may only be used with Mozilla's GeckoDriver._ + * * @param {promise.ControlFlow=} opt_flow The flow to * schedule commands through. Defaults to the active flow object. + * @throws {Error} If a custom command executor is provided and the driver is + * configured to use the legacy FirefoxDriver from the Selenium project. + * @return {!Driver} A new driver instance. */ - constructor(opt_config?: Options | webdriver.Capabilities | Object, opt_flow?: webdriver.promise.ControlFlow); + static createSession(opt_config?: Options | webdriver.Capabilities, opt_executor?: http.Executor | remote.DriverService, opt_flow?: webdriver.promise.ControlFlow): Driver; + /** * This function is a no-op as file detectors are not supported by this @@ -251,3 +272,37 @@ export class Driver extends webdriver.WebDriver { */ setFileDetector(): void; } + +/** + * Creates {@link selenium-webdriver/remote.DriverService} instances that manage + * a [geckodriver](https://github.com/mozilla/geckodriver) server in a child + * process. + */ +export class ServiceBuilder extends remote.DriverService.Builder { + /** + * @param {string=} opt_exe Path to the server executable to use. If omitted, + * the builder will attempt to locate the geckodriver on the system PATH. + */ + constructor(opt_exe?: string); + + /** + * Enables verbose logging. + * + * @param {boolean=} opt_trace Whether to enable trace-level logging. By + * default, only debug logging is enabled. + * @return {!ServiceBuilder} A self reference. + */ + enableVerboseLogging(opt_trace?: boolean): this; + + /** + * Sets the path to the executable Firefox binary that the geckodriver should + * use. If this method is not called, this builder will attempt to locate + * Firefox in the default installation location for the current platform. + * + * @param {(string|!Binary)} binary Path to the executable Firefox binary to use. + * @return {!ServiceBuilder} A self reference. + * @see Binary#locate() + */ + setFirefoxBinary(binary: string | Binary): this; +} + diff --git a/selenium-webdriver/http.d.ts b/selenium-webdriver/http.d.ts index a0a25a7955..4fc12afb19 100644 --- a/selenium-webdriver/http.d.ts +++ b/selenium-webdriver/http.d.ts @@ -13,7 +13,7 @@ export function headersToString(headers: any): string; * responsibility to build the full URL for the final request. * @final */ -export class HttpRequest { +export class Request { /** * @param {string} method The HTTP method to use for the request. * @param {string} path The path on the server to send the request to. @@ -29,7 +29,7 @@ export class HttpRequest { * Represents a HTTP response message. * @final */ -export class HttpResponse { +export class Response { /** * @param {number} status The response code. * @param {!Object} headers The response headers. All header names @@ -70,7 +70,7 @@ export class HttpClient { * @return {!promise.Promise} A promise that will be fulfilled * with the server's response. */ - send(httpRequest: HttpRequest): webdriver.promise.Promise; + send(httpRequest: Request): webdriver.promise.Promise; } /** @@ -99,10 +99,11 @@ export function sendRequest(options: Object, onOk: any, onError: any, opt_data?: */ export class Executor { /** - * @param {!HttpClient} client The client to use for sending requests to the - * server. + * @param {!(HttpClient|IThenable)} client The client to use for sending + * requests to the server, or a promise-like object that will resolve to + * to the client. */ - constructor(client: HttpClient); + constructor(client: HttpClient | webdriver.promise.IThenable); /** * Defines a new command for use with this executor. When a command is sent, @@ -138,7 +139,7 @@ export function tryParse(str: string): any; * @return {{value: ?}} The parsed response. * @throws {WebDriverError} If the HTTP response is an error. */ -export function parseHttpResponse(httpResponse: HttpResponse, w3c: boolean): any; +export function parseHttpResponse(httpResponse: Response, w3c: boolean): any; /** * Builds a fully qualified path using the given set of command parameters. Each diff --git a/selenium-webdriver/ie.d.ts b/selenium-webdriver/ie.d.ts index 9e8cab2457..bf3932450e 100644 --- a/selenium-webdriver/ie.d.ts +++ b/selenium-webdriver/ie.d.ts @@ -5,12 +5,15 @@ import * as webdriver from './index'; */ export class Driver extends webdriver.WebDriver { /** + * Creates a new session for Microsoft's Internet Explorer. + * * @param {(capabilities.Capabilities|Options)=} opt_config The configuration * options. * @param {promise.ControlFlow=} opt_flow The control flow to use, * or {@code null} to use the currently active flow. + * @return {!Driver} A new driver instance. */ - constructor(opt_config?: webdriver.Capabilities | Options, opt_flow?: webdriver.promise.ControlFlow); + static createSession(opt_config?: webdriver.Capabilities | Options, opt_flow?: webdriver.promise.ControlFlow): Driver; /** * This function is a no-op as file detectors are not supported by this @@ -201,5 +204,5 @@ export class Options { * merge these options into, if any. * @return {!capabilities.Capabilities} The capabilities. */ - toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; + toCapabilities(opt_capabilities?: webdriver.Capabilities): webdriver.Capabilities; } diff --git a/selenium-webdriver/index.d.ts b/selenium-webdriver/index.d.ts index 39d56d7d5b..bfd583302e 100644 --- a/selenium-webdriver/index.d.ts +++ b/selenium-webdriver/index.d.ts @@ -1,7 +1,11 @@ -// Type definitions for Selenium WebDriverJS 2.53 +// Type definitions for Selenium WebDriverJS 3.0 // Project: https://github.com/SeleniumHQ/selenium/tree/master/javascript/node/selenium-webdriver -// Definitions by: Bill Armstrong , Yuki Kokubun , Craig Nishina +// Definitions by: Bill Armstrong , +// Yuki Kokubun , +// Craig Nishina , +// Simon Gellis // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 import * as chrome from './chrome'; import * as edge from './edge'; @@ -13,8 +17,6 @@ import * as safari from './safari'; export namespace error { class IError extends Error { constructor(opt_error?: string); - - code(): number; } /** @@ -656,7 +658,8 @@ export namespace promise { /** * Creates a promise that has been resolved with the given value. * @param {T=} opt_value The resolved value. - * @return {!ManagedPromise} The resolved promise. + * @return {!Promise} The resolved promise. + * @deprecated Use {@link Promise#resolve Promise.resolve(value)}. * @template T */ function fulfilled(opt_value?: T): Promise; @@ -689,8 +692,8 @@ export namespace promise { * Creates a promise that has been rejected with the given reason. * @param {*=} opt_reason The rejection reason; may be any value, but is * usually an Error or a string. - * @return {!ManagedPromise} The rejected promise. - * @template T + * @return {!Promise} The rejected promise. + * @deprecated Use {@link Promise#reject Promise.Promise(reason)}. */ function rejected(opt_reason?: any): Promise; @@ -802,19 +805,6 @@ export namespace promise { } interface IThenable { - /** - * Cancels the computation of this promise's value, rejecting the promise in - * the process. This method is a no-op if the promise has already been - * resolved. - * - * @param {(string|Error)=} opt_reason The reason this promise is being - * cancelled. This value will be wrapped in a {@link CancellationError}. - */ - cancel(opt_reason?: string | Error): void; - - /** @return {boolean} Whether this promise's value is still being computed. */ - isPending(): boolean; - /** * Registers listeners for when this instance is resolved. * @@ -864,19 +854,6 @@ export namespace promise { * @template T */ class Thenable implements IThenable { - /** - * Cancels the computation of this promise's value, rejecting the promise in - * the process. This method is a no-op if the promise has already been - * resolved. - * - * @param {(string|Error)=} opt_reason The reason this promise is being - * cancelled. This value will be wrapped in a {@link CancellationError}. - */ - cancel(opt_reason?: string | Error): void; - - /** @return {boolean} Whether this promise's value is still being computed. */ - isPending(): boolean; - /** * Registers listeners for when this instance is resolved. * @@ -1007,60 +984,43 @@ export namespace promise { */ constructor(resolver: (resolve: IFulfilledCallback, reject: IRejectedCallback) => void, opt_flow?: ControlFlow); + //region Static Methods + + /** + * Creates a promise that is immediately resolved with the given value. + * + * @param {T=} opt_value The value to resolve. + * @return {!ManagedPromise} A promise resolved with the given value. + * @template T + */ + static resolve(opt_value?: T): Promise; + + /** + * Creates a promise that is immediately rejected with the given reason. + * + * @param {*=} opt_reason The rejection reason. + * @return {!ManagedPromise} A new rejected promise. + */ + static reject(opt_reason?: any): Promise; + + //endregion + // region Methods /** - * Cancels the computation of this promise's value, rejecting the promise in the - * process. - * @param {*} reason The reason this promise is being cancelled. If not an - * {@code Error}, one will be created using the value's string - * representation. - */ - cancel(opt_reason?: string | Error): void; - - /** @return {boolean} Whether this promise's value is still being computed. */ - isPending(): boolean; - - /** - * Registers listeners for when this instance is resolved. This function most - * overridden by subtypes. + * Registers listeners for when this instance is resolved. * - * @param opt_callback The function to call if this promise is - * successfully resolved. The function should expect a single argument: the - * promise's resolved value. - * @param opt_errback The function to call if this promise is - * rejected. The function should expect a single argument: the rejection - * reason. - * @return A new promise which will be resolved - * with the result of the invoked callback. - */ - then(opt_callback?: (value: T) => IThenable | R, opt_errback?: (error: any) => any): Promise; - - /** - * Registers a listener for when this promise is rejected. This is synonymous - * with the {@code catch} clause in a synchronous API: - *

-     *   // Synchronous API:
-     *   try {
-     *     doSynchronousWork();
-     *   } catch (ex) {
-     *     console.error(ex);
-     *   }
-     *
-     *   // Asynchronous promise API:
-     *   doAsynchronousWork().thenCatch(function(ex) {
-     *     console.error(ex);
-     *   });
-     * 
- * - * @param {function(*): (R|promise.Promise.)} errback The function - * to call if this promise is rejected. The function should expect a single - * argument: the rejection reason. - * @return {!promise.Promise.} A new promise which will be - * resolved with the result of the invoked callback. + * @param {?(function(T): (R|IThenable))=} opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param {?(function(*): (R|IThenable))=} opt_errback + * The function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!Thenable} A new promise which will be resolved with the result + * of the invoked callback. * @template R */ - thenCatch(errback: (error: any) => any): Promise; + then(opt_callback?: (value: T) => IThenable | R, opt_errback?: (error: any) => any): Promise; /** * Registers a listener for when this promise is rejected. This is synonymous @@ -1085,50 +1045,9 @@ export namespace promise { * resolved with the result of the invoked callback. * @template R */ - catch(errback: Function): Promise; + catch(errback: (err: any) => R | IThenable): Promise; - /** - * Registers a listener to invoke when this promise is resolved, regardless - * of whether the promise's value was successfully computed. This function - * is synonymous with the {@code finally} clause in a synchronous API: - *

-     *   // Synchronous API:
-     *   try {
-     *     doSynchronousWork();
-     *   } finally {
-     *     cleanUp();
-     *   }
-     *
-     *   // Asynchronous promise API:
-     *   doAsynchronousWork().thenFinally(cleanUp);
-     * 
- * - * Note: similar to the {@code finally} clause, if the registered - * callback returns a rejected promise or throws an error, it will silently - * replace the rejection error (if any) from this promise: - *

-     *   try {
-     *     throw Error('one');
-     *   } finally {
-     *     throw Error('two');  // Hides Error: one
-     *   }
-     *
-     *   promise.rejected(Error('one'))
-     *       .thenFinally(function() {
-     *         throw Error('two');  // Hides Error: one
-     *       });
-     * 
- * - * - * @param {function(): (R|promise.Promise.)} callback The function - * to call when this promise is resolved. - * @return {!promise.Promise.} A promise that will be fulfilled - * with the callback result. - * @template R - */ - thenFinally(callback: Function): Promise; - // endregion } @@ -1143,13 +1062,8 @@ export namespace promise { * the next turn of the event loop, the rejection will be passed to the * {@link promise.ControlFlow} as an unhandled failure. * - *

If this Deferred is cancelled, the cancellation reason will be forward to - * the Deferred's canceller function (if provided). The canceller may return a - * truth-y value to override the reason provided for rejection. - * - * @extends {promise.Promise} */ - class Deferred extends Promise { + class Deferred { // region Constructors /** @@ -1368,28 +1282,40 @@ export namespace promise { } } -export namespace until { +/** + * Defines a condition for use with WebDriver's WebDriver#wait wait command. + */ +export class Condition { /** - * Defines a condition to + * @param {string} message A descriptive error message. Should complete the + * sentence 'Waiting [...]' + * @param {function(!WebDriver): OUT} fn The condition function to + * evaluate on each iteration of the wait loop. + * @constructor */ - class Condition { + constructor(message: string, fn: (webdriver: WebDriver) => any); + + /** @return {string} A description of this condition. */ + description(): string; + + /** @type {function(!WebDriver): OUT} */ + fn(webdriver: WebDriver): any; +} + +/** + * Defines a condition that will result in a {@link WebElement}. + * + * @extends {Condition)>} + */ +export class WebElementCondition extends Condition { + // add an unused private member so the compiler treats this + // class distinct from other Conditions + private _nominal: undefined; +} + +export namespace until { + /** - * @param {string} message A descriptive error message. Should complete the - * sentence 'Waiting [...]' - * @param {function(!WebDriver): OUT} fn The condition function to - * evaluate on each iteration of the wait loop. - * @constructor - */ - constructor(message: string, fn: (webdriver: WebDriver) => any); - - /** @return {string} A description of this condition. */ - description(): string; - - /** @type {function(!WebDriver): OUT} */ - fn(webdriver: WebDriver): any; - } - - /** * Creates a condition that will wait until the input driver is able to switch * to the designated frame. The target frame may be specified as * @@ -1409,7 +1335,7 @@ export namespace until { * The frame identifier. * @return {!Condition} A new condition. */ - function ableToSwitchToFrame(frame: number | WebElement | By | ((webdriver: WebDriver) => WebElement)): Condition; + function ableToSwitchToFrame(frame: number | WebElement | By | ((webdriver: WebDriver) => WebElement) | ByHash): Condition; /** * Creates a condition that waits for an alert to be opened. Upon success, the @@ -1423,64 +1349,64 @@ export namespace until { * Creates a condition that will wait for the given element to be disabled. * * @param {!WebElement} element The element to test. - * @return {!until.Condition.} The new condition. + * @return {!WebElementCondition} The new condition. * @see WebDriver#isEnabled */ - function elementIsDisabled(element: WebElement): Condition; + function elementIsDisabled(element: WebElement): WebElementCondition; /** * Creates a condition that will wait for the given element to be enabled. * * @param {!WebElement} element The element to test. - * @return {!until.Condition.} The new condition. + * @return {!WebElementCondition} The new condition. * @see WebDriver#isEnabled */ - function elementIsEnabled(element: WebElement): Condition; + function elementIsEnabled(element: WebElement): WebElementCondition; /** * Creates a condition that will wait for the given element to be deselected. * * @param {!WebElement} element The element to test. - * @return {!until.Condition.} The new condition. + * @return {!WebElementCondition} The new condition. * @see WebDriver#isSelected */ - function elementIsNotSelected(element: WebElement): Condition; + function elementIsNotSelected(element: WebElement): WebElementCondition; /** * Creates a condition that will wait for the given element to be in the DOM, * yet not visible to the user. * * @param {!WebElement} element The element to test. - * @return {!until.Condition.} The new condition. + * @return {!WebElementCondition} The new condition. * @see WebDriver#isDisplayed */ - function elementIsNotVisible(element: WebElement): Condition; + function elementIsNotVisible(element: WebElement): WebElementCondition; /** * Creates a condition that will wait for the given element to be selected. * @param {!WebElement} element The element to test. - * @return {!until.Condition.} The new condition. + * @return {!WebElementCondition} The new condition. * @see WebDriver#isSelected */ - function elementIsSelected(element: WebElement): Condition; + function elementIsSelected(element: WebElement): WebElementCondition; /** * Creates a condition that will wait for the given element to become visible. * * @param {!WebElement} element The element to test. - * @return {!until.Condition.} The new condition. + * @return {!WebElementCondition} The new condition. * @see WebDriver#isDisplayed */ - function elementIsVisible(element: WebElement): Condition; + function elementIsVisible(element: WebElement): WebElementCondition; /** * Creates a condition that will loop until an element is * {@link ./WebDriver#findElement found} with the given locator. * * @param {!(By|Function)} locator The locator to use. - * @return {!until.Condition.} The new condition. + * @return {!WebElementCondition} The new condition. */ - function elementLocated(locator: By | Function): Condition; + function elementLocated(locator: Locator): WebElementCondition; /** * Creates a condition that will wait for the given element's @@ -1489,10 +1415,10 @@ export namespace until { * * @param {!WebElement} element The element to test. * @param {string} substr The substring to search for. - * @return {!until.Condition.} The new condition. + * @return {!WebElementCondition} The new condition. * @see WebDriver#getText */ - function elementTextContains(element: WebElement, substr: string): Condition; + function elementTextContains(element: WebElement, substr: string): WebElementCondition; /** * Creates a condition that will wait for the given element's @@ -1501,10 +1427,10 @@ export namespace until { * * @param {!WebElement} element The element to test. * @param {string} text The expected text. - * @return {!until.Condition.} The new condition. + * @return {!WebElementCondition} The new condition. * @see WebDriver#getText */ - function elementTextIs(element: WebElement, text: string): Condition; + function elementTextIs(element: WebElement, text: string): WebElementCondition; /** * Creates a condition that will wait for the given element's @@ -1513,10 +1439,10 @@ export namespace until { * * @param {!WebElement} element The element to test. * @param {!RegExp} regex The regular expression to test against. - * @return {!until.Condition} The new condition. + * @return {!WebElementCondition} The new condition. * @see WebDriver#getText */ - function elementTextMatches(element: WebElement, regex: RegExp): Condition; + function elementTextMatches(element: WebElement, regex: RegExp): WebElementCondition; /** * Creates a condition that will loop until at least one element is @@ -1524,10 +1450,10 @@ export namespace until { * * @param {!(Locator|By.Hash|Function)} locator The locator * to use. - * @return {!until.Condition.>} The new + * @return {!Condition.>} The new * condition. */ - function elementsLocated(locator: By | Function): Condition; + function elementsLocated(locator: Locator): Condition; /** * Creates a condition that will wait for the given element to become stale. An @@ -1535,7 +1461,7 @@ export namespace until { * has loaded. * * @param {!WebElement} element The element that should become stale. - * @return {!until.Condition} The new condition. + * @return {!Condition} The new condition. */ function stalenessOf(element: WebElement): Condition; @@ -1545,7 +1471,7 @@ export namespace until { * * @param {string} substr The substring that should be present in the page * title. - * @return {!until.Condition.} The new condition. + * @return {!Condition.} The new condition. */ function titleContains(substr: string): Condition; @@ -1554,7 +1480,7 @@ export namespace until { * given value. * * @param {string} title The expected page title. - * @return {!until.Condition} The new condition. + * @return {!Condition} The new condition. */ function titleIs(title: string): Condition; @@ -1563,9 +1489,37 @@ export namespace until { * given regular expression. * * @param {!RegExp} regex The regular expression to test against. - * @return {!until.Condition.} The new condition. + * @return {!Condition.} The new condition. */ function titleMatches(regex: RegExp): Condition; + + /** + * Creates a condition that will wait for the current page's url to contain + * the given substring. + * + * @param {string} substrUrl The substring that should be present in the current + * URL. + * @return {!Condition} The new condition. + */ + function urlContains(substrUrl: string): Condition; + + /** + * Creates a condition that will wait for the current page's url to match the + * given value. + * + * @param {string} url The expected page url. + * @return {!Condition} The new condition. + */ + function urlIs(url: string): Condition; + + /** + * Creates a condition that will wait for the current page's url to match the + * given regular expression. + * + * @param {!RegExp} regex The regular expression to test against. + * @return {!Condition} The new condition. + */ + function urlMatches(regex: RegExp): Condition; } interface ILocation { @@ -2093,18 +2047,6 @@ export class AlertPromise extends Alert implements promise.IThenable { // region Methods - /** - * Cancels the computation of this promise's value, rejecting the promise in the - * process. - * @param {*} reason The reason this promise is being cancelled. If not an - * {@code Error}, one will be created using the value's string - * representation. - */ - cancel(opt_reason?: string | Error): void; - - /** @return {boolean} Whether this promise's value is still being computed. */ - isPending(): boolean; - /** * Registers listeners for when this instance is resolved. This function most * overridden by subtypes. @@ -2120,32 +2062,6 @@ export class AlertPromise extends Alert implements promise.IThenable { */ then(opt_callback?: Function, opt_errback?: Function): promise.Promise; - /** - * Registers a listener for when this promise is rejected. This is synonymous - * with the {@code catch} clause in a synchronous API: - *


-   *   // Synchronous API:
-   *   try {
-   *     doSynchronousWork();
-   *   } catch (ex) {
-   *     console.error(ex);
-   *   }
-   *
-   *   // Asynchronous promise API:
-   *   doAsynchronousWork().thenCatch(function(ex) {
-   *     console.error(ex);
-   *   });
-   * 
- * - * @param {function(*): (R|promise.Promise.)} errback The function - * to call if this promise is rejected. The function should expect a single - * argument: the rejection reason. - * @return {!promise.Promise.} A new promise which will be - * resolved with the result of the invoked callback. - * @template R - */ - thenCatch(errback: (error: any) => any): promise.Promise; - /** * Registers a listener for when this promise is rejected. This is synonymous * with the {@code catch} clause in a synchronous API: @@ -2170,52 +2086,6 @@ export class AlertPromise extends Alert implements promise.IThenable { * @template R */ catch(errback: Function): promise.Promise; - - - /** - * Registers a listener to invoke when this promise is resolved, regardless - * of whether the promise's value was successfully computed. This function - * is synonymous with the {@code finally} clause in a synchronous API: - *

-   *   // Synchronous API:
-   *   try {
-   *     doSynchronousWork();
-   *   } finally {
-   *     cleanUp();
-   *   }
-   *
-   *   // Asynchronous promise API:
-   *   doAsynchronousWork().thenFinally(cleanUp);
-   * 
- * - * Note: similar to the {@code finally} clause, if the registered - * callback returns a rejected promise or throws an error, it will silently - * replace the rejection error (if any) from this promise: - *

-   *   try {
-   *     throw Error('one');
-   *   } finally {
-   *     throw Error('two');  // Hides Error: one
-   *   }
-   *
-   *   promise.rejected(Error('one'))
-   *       .thenFinally(function() {
-   *         throw Error('two');  // Hides Error: one
-   *       });
-   * 
- * - * - * @param {function(): (R|promise.Promise.)} callback The function - * to call when this promise is resolved. - * @return {!promise.Promise.} A promise that will be fulfilled - * with the callback result. - * @template R - */ - thenFinally(callback: Function): promise.Promise; -} - -/** @deprecated Use {@link error.UnexpectedAlertOpenError} instead. */ -export class UnhandledAlertError extends error.UnexpectedAlertOpenError { } /** @@ -2246,6 +2116,9 @@ interface ProxyConfig { httpProxy?: string; sslProxy?: string; noProxy?: string; + socksProxy?: string, + socksUsername?: string, + socksPassword?: string } /** @@ -2312,32 +2185,16 @@ export class Builder { * Creates a new WebDriver client based on this builder's current * configuration. * - * While this method will immediately return a new WebDriver instance, any - * commands issued against it will be deferred until the associated browser - * has been fully initialized. Users may call {@link #buildAsync()} to obtain - * a promise that will not be fulfilled until the browser has been created - * (the difference is purely in style). + * This method will return a {@linkplain ThenableWebDriver} instance, allowing + * users to issue commands directly without calling `then()`. The returned + * thenable wraps a promise that will resolve to a concrete + * {@linkplain webdriver.WebDriver WebDriver} instance. The promise will be + * rejected if the remote end fails to create a new session. * - * @return {!WebDriver} A new WebDriver instance. + * @return {!ThenableWebDriver} A new WebDriver instance. * @throws {Error} If the current configuration is invalid. - * @see #buildAsync() */ - build(): WebDriver; - - /** - * Creates a new WebDriver client based on this builder's current - * configuration. This method returns a promise that will not be fulfilled - * until the new browser session has been fully initialized. - * - * __Note:__ this method is purely a convenience wrapper around - * {@link #build()}. - * - * @return {!promise.Promise} A promise that will be - * fulfilled with the newly created WebDriver instance once the browser - * has been fully initialized. - * @see #build() - */ - buildAsync(): promise.Promise; + build(): ThenableWebDriver; /** * Configures the target browser for clients created by this instance. @@ -2493,6 +2350,15 @@ export class Builder { */ setScrollBehavior(behavior: number): Builder; + /** + * Sets the http agent to use for each request. + * If this method is not called, the Builder will use http.globalAgent by default. + * + * @param {http.Agent} agent The agent to use for each request. + * @return {!Builder} A self reference. + */ + usingHttpAgent(agent: any): Builder; + /** * Sets the URL of a remote WebDriver server to use. Once a remote URL has been * specified, the builder direct all new clients to that server. If this method @@ -2666,6 +2532,8 @@ type ByHash = { className: string } | { tagName: string } | { xpath: string }; + export type Locator = By | Function | ByHash; + /** * Common webdriver capability keys. * @enum {string} @@ -3121,19 +2989,6 @@ export class Executor { execute(command: Command): promise.Promise } -/** - * Wraps a promised {@link Executor}, ensuring no commands are executed until - * the wrapped executor has been fully resolved. - * @implements {Executor} - */ -export class DeferredExecutor { - /** - * @param {!promise.Promise} delegate The promised delegate, which - * may be provided by any promise-like thenable object. - */ - constructor(delegate: promise.Promise); -} - /** * Describes an event listener registered on an {@linkplain EventEmitter}. */ @@ -3286,12 +3141,65 @@ export class Navigation { } interface IWebDriverOptionsCookie { + + /** + * The name of the cookie. + */ name: string; + + /** + * The cookie value. + */ value: string; + + /** + * The cookie path. Defaults to "/" when adding a cookie. + */ path?: string; + + /** + * The domain the cookie is visible to. Defaults to the current browsing + * context's document's URL when adding a cookie. + */ domain?: string; + + /** + * Whether the cookie is a secure cookie. Defaults to false when adding a new + * cookie. + */ secure?: boolean; - expiry?: number; + + /** + * Whether the cookie is an HTTP only cookie. Defaults to false when adding a + * new cookie. + */ + httpOnly?: boolean; + + /** + * When the cookie expires. + * + * When {@linkplain Options#addCookie() adding a cookie}, this may be specified + * in _seconds_ since Unix epoch (January 1, 1970). The expiry will default to + * 20 years in the future if omitted. + * + * The expiry is always returned in seconds since epoch when + * {@linkplain Options#getCookies() retrieving cookies} from the browser. + * + * @type {(!Date|number|undefined)} + */ + expiry?: number | Date; + } + + interface IWebDriverCookie extends IWebDriverOptionsCookie { + /** + * When the cookie expires. + * + * The expiry is always returned in seconds since epoch when + * {@linkplain Options#getCookies() retrieving cookies} from the browser. + * + * @type {(!number|undefined)} + */ + expiry?: number } /** @@ -3312,18 +3220,14 @@ export class Options { /** * Schedules a command to add a cookie. - * @param {string} name The cookie name. - * @param {string} value The cookie value. - * @param {string=} opt_path The cookie path. - * @param {string=} opt_domain The cookie domain. - * @param {boolean=} opt_isSecure Whether the cookie is secure. - * @param {(number|!Date)=} opt_expiry When the cookie expires. If specified - * as a number, should be in milliseconds since midnight, - * January 1, 1970 UTC. + * @param {IWebDriverOptionsCookie} spec Defines the cookie to add. * @return {!promise.Promise} A promise that will be resolved * when the cookie has been added to the page. + * @throws {error.InvalidArgumentError} if any of the cookie parameters are + * invalid. + * @throws {TypeError} if `spec` is not a cookie object. */ - addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: number | Date): promise.Promise; + addCookie(spec: IWebDriverOptionsCookie): promise.Promise; /** * Schedules a command to delete all cookies visible to the current page. @@ -3669,6 +3573,11 @@ export class FileDetector { handleFile(driver: WebDriver, path: string): promise.Promise; } + type CreateSessionCapabilities = Capabilities | { + desired?: Capabilities, + required?: Capabilities + } + /** * Creates a new WebDriver client, which provides control over a browser. * @@ -3719,17 +3628,63 @@ export class WebDriver { /** * Creates a new WebDriver session. + * + * By default, the requested session `capabilities` are merely "desired" and + * the remote end will still create a new session even if it cannot satisfy + * all of the requested capabilities. You can query which capabilities a + * session actually has using the + * {@linkplain #getCapabilities() getCapabilities()} method on the returned + * WebDriver instance. + * + * To define _required capabilities_, provide the `capabilities` as an object + * literal with `required` and `desired` keys. The `desired` key may be + * omitted if all capabilities are required, and vice versa. If the server + * cannot create a session with all of the required capabilities, it will + * return an {@linkplain error.SessionNotCreatedError}. + * + * let required = new Capabilities().set('browserName', 'firefox'); + * let desired = new Capabilities().set('version', '45'); + * let driver = WebDriver.createSession(executor, {required, desired}); + * + * This function will always return a WebDriver instance. If there is an error + * creating the session, such as the aforementioned SessionNotCreatedError, + * the driver will have a rejected {@linkplain #getSession session} promise. + * It is recommended that this promise is left _unhandled_ so it will + * propagate through the {@linkplain promise.ControlFlow control flow} and + * cause subsequent commands to fail. + * + * let required = Capabilities.firefox(); + * let driver = WebDriver.createSession(executor, {required}); + * + * // If the createSession operation failed, then this command will also + * // also fail, propagating the creation failure. + * driver.get('http://www.google.com').catch(e => console.log(e)); + * * @param {!command.Executor} executor The executor to create the new session * with. - * @param {!./capabilities.Capabilities} desiredCapabilities The desired + * @param {(!Capabilities| + * {desired: (Capabilities|undefined), + * required: (Capabilities|undefined)})} capabilities The desired * capabilities for the new session. * @param {promise.ControlFlow=} opt_flow The control flow all driver * commands should execute under, including the initial session creation. * Defaults to the {@link promise.controlFlow() currently active} * control flow. + * @param {(function(new: WebDriver, + * !IThenable, + * !command.Executor, + * promise.ControlFlow=))=} opt_ctor + * A reference to the constructor of the specific type of WebDriver client + * to instantiate. Will create a vanilla {@linkplain WebDriver} instance + * if a constructor is not provided. + * @param {(function(this: void): ?)=} opt_onQuit A callback to invoke when + * the newly created session is terminated. This should be used to clean + * up any resources associated with the session. * @return {!WebDriver} The driver for the newly created session. */ - static createSession(executor: Executor, desiredCapabilities: Capabilities, opt_flow?: promise.ControlFlow): WebDriver; + // This method's arguments are untyped so that its overloads can have correct types. + // Typescript doesn't allow static methods to be overridden with incompatible signatures. + static createSession(...var_args: any[]): WebDriver; // endregion @@ -3947,10 +3902,10 @@ export class WebDriver { /** * Schedules a command to wait for a condition to hold. The condition may be - * specified by a {@link until.Condition}, as a custom function, or + * specified by a {@link Condition}, as a custom function, or * as a {@link promise.Promise}. * - * For a {@link until.Condition} or function, the wait will repeatedly + * For a {@link Condition} or function, the wait will repeatedly * evaluate the condition until it returns a truthy value. If any errors occur * while evaluating the condition, they will be allowed to propagate. In the * event a condition returns a {@link promise.Promise promise}, the @@ -3958,6 +3913,10 @@ export class WebDriver { * whether the condition has been satisified. Note the resolution time for * a promise is factored into whether a wait has timed out. * + * Note, if the provided condition is a {@link WebElementCondition}, then + * the wait will return a {@link WebElementPromise} that will resolve to the + * element that satisified the condition. + * * *Example:* waiting up to 10 seconds for an element to be present and visible * on the page. * @@ -3978,8 +3937,58 @@ export class WebDriver { * driver.wait(started, 5 * 1000, 'Server should start within 5 seconds'); * driver.get(getServerUrl()); * + * @param {!WebElementCondition} condition The condition to + * wait on, defined as a promise, condition object, or a function to + * evaluate as a condition. + * @param {number=} opt_timeout How long to wait for the condition to be true. + * @param {string=} opt_message An optional message to use if the wait times + * out. + * @return {!WebElementPromise} A promise that will be fulfilled + * with the first truthy value returned by the condition function, or + * rejected if the condition times out. + * @template T + */ + wait(condition: WebElementCondition, opt_timeout?: number, opt_message?: string): WebElementPromise; + + /** + * Schedules a command to wait for a condition to hold. The condition may be + * specified by a {@link webdriver.Condition}, as a custom function, or + * as a {@link webdriver.promise.Promise}. + * + * For a {@link webdriver.Condition} or function, the wait will repeatedly + * evaluate the condition until it returns a truthy value. If any errors occur + * while evaluating the condition, they will be allowed to propagate. In the + * event a condition returns a {@link webdriver.promise.Promise promise}, the + * polling loop will wait for it to be resolved and use the resolved value for + * whether the condition has been satisified. Note the resolution time for + * a promise is factored into whether a wait has timed out. + * + * Note, if the provided condition is a {@link WebElementCondition}, then + * the wait will return a {@link WebElementPromise} that will resolve to the + * element that satisified the condition. + * + * *Example:* waiting up to 10 seconds for an element to be present and visible + * on the page. + * + * var button = driver.wait(until.elementLocated(By.id('foo'), 10000); + * button.click(); + * + * This function may also be used to block the command flow on the resolution + * of a {@link webdriver.promise.Promise promise}. When given a promise, the + * command will simply wait for its resolution before completing. A timeout may + * be provided to fail the command if the promise does not resolve before the + * timeout expires. + * + * *Example:* Suppose you have a function, `startTestServer`, that returns a + * promise for when a server is ready for requests. You can block a `WebDriver` + * client on this promise with: + * + * var started = startTestServer(); + * driver.wait(started, 5 * 1000, 'Server should start within 5 seconds'); + * driver.get(getServerUrl()); + * * @param {!(promise.Promise| - * until.Condition| + * Condition| * function(!WebDriver): T)} condition The condition to * wait on, defined as a promise, condition object, or a function to * evaluate as a condition. @@ -3991,7 +4000,7 @@ export class WebDriver { * rejected if the condition times out. * @template T */ - wait(condition: promise.Promise | until.Condition | ((driver: WebDriver) => T) | Function, timeout?: number, opt_message?: string): promise.Promise; + wait(condition: PromiseLike | Condition | ((driver: WebDriver) => T | PromiseLike) | Function, opt_timeout?: number, opt_message?: string): promise.Promise; /** * Schedules a command to make the driver sleep for the given amount of time. @@ -4060,7 +4069,7 @@ export class WebDriver { * by the driver. Unlike other commands, this error cannot be suppressed. In * other words, scheduling a command to find an element doubles as an assert * that the element is present on the page. To test whether an element is - * present on the page, use {@link #isElementPresent} instead. + * present on the page, use {@link #findElements}. * * The search criteria for an element may be defined using one of the * factories in the {@link By} namespace, or as a short-hand @@ -4090,25 +4099,7 @@ export class WebDriver { * commands against the located element. If the element is not found, the * element will be invalidated and all scheduled commands aborted. */ - findElement(locator: By | Function): WebElementPromise; - - /** - * Schedules a command to test if an element is present on the page. - * - * If given a DOM element, this function will check if it belongs to the - * document the driver is currently focused on. Otherwise, the function will - * test if at least one element can be found with the given search criteria. - * - * @param {!(by.By|Function)} locator The locator to use. - * @return {!promise.Promise} A promise that will resolve - * with whether the element is present on the page. - * @deprecated This method will be removed in Selenium 3.0 for consistency - * with the other Selenium language bindings. This method is equivalent - * to - * - * driver.findElements(locator).then(e => !!e.length); - */ - isElementPresent(locatorOrElement: By | Function): promise.Promise; + findElement(locator: Locator): WebElementPromise; /** * Schedule a command to search for multiple elements on the page. @@ -4117,7 +4108,7 @@ export class WebDriver { * @return {!promise.Promise.>} A * promise that will resolve to an array of WebElements. */ - findElements(locator: By | Function): promise.Promise; + findElements(locator: Locator): promise.Promise; /** * Schedule a command to take a screenshot. The driver makes a best effort to @@ -4154,6 +4145,24 @@ export class WebDriver { // endregion } + /** + * A thenable wrapper around a {@linkplain webdriver.IWebDriver IWebDriver} + * instance that allows commands to be issued directly instead of having to + * repeatedly call `then`: + * + * let driver = new Builder().build(); + * driver.then(d => d.get(url)); // You can do this... + * driver.get(url); // ...or this + * + * If the driver instance fails to resolve (e.g. the session cannot be created), + * every issued command will fail. + * + * @extends {webdriver.IWebDriver} + * @extends {promise.IThenable} + * @interface + */ + interface ThenableWebDriver extends WebDriver, promise.IThenable { } + interface IWebElementId { [ELEMENT: string]: string; } @@ -4365,13 +4374,6 @@ interface IWebElement { */ isDisplayed(): promise.Promise; - /** - * Schedules a command to retrieve the outer HTML of this element. - * @return {!promise.Promise} A promise that will be resolved with - * the element's outer HTML. - */ - getOuterHtml(): promise.Promise; - /** * @return {!promise.Promise.} A promise * that resolves to this element's JSON representation as defined by the @@ -4380,13 +4382,6 @@ interface IWebElement { */ getId(): promise.Promise; - /** - * Schedules a command to retrieve the inner HTML of this element. - * @return {!promise.Promise} A promise that will be resolved with the - * element's inner HTML. - */ - getInnerHtml(): promise.Promise; - // endregion } @@ -4397,7 +4392,7 @@ interface IWebElementFinders { * be returned by the driver. Unlike other commands, this error cannot be * suppressed. In other words, scheduling a command to find an element doubles * as an assert that the element is present on the page. To test whether an - * element is present on the page, use {@code #isElementPresent} instead. + * element is present on the page, use {@code #findElements}. * *

The search criteria for an element may be defined using one of the * factories in the {@link By} namespace, or as a short-hand @@ -4431,18 +4426,7 @@ interface IWebElementFinders { * commands against the located element. If the element is not found, the * element will be invalidated and all scheduled commands aborted. */ - findElement(locator: By | Function): WebElementPromise; - - /** - * Schedules a command to test if there is at least one descendant of this - * element that matches the given search criteria. - * - * @param {!(Locator|By.Hash|Function)} locator The - * locator strategy to use when searching for the element. - * @return {!promise.Promise.} A promise that will be - * resolved with whether an element could be located on the page. - */ - isElementPresent(locator: By | Function): promise.Promise; + findElement(locator: Locator): WebElementPromise; /** * Schedules a command to find all of the descendants of this element that @@ -4453,7 +4437,7 @@ interface IWebElementFinders { * @return {!promise.Promise.>} A * promise that will resolve to an array of WebElements. */ - findElements(locator: By | Function): promise.Promise; + findElements(locator: Locator): promise.Promise; } /** @@ -4550,18 +4534,13 @@ export class WebElement implements Serializable { */ getId(): promise.Promise; - /** - * @deprecated Use {@link #getId()} instead. - */ - getRawId(): any; - /** * Schedule a command to find a descendant of this element. If the element * cannot be found, a {@link bot.ErrorCode.NO_SUCH_ELEMENT} result will * be returned by the driver. Unlike other commands, this error cannot be * suppressed. In other words, scheduling a command to find an element doubles * as an assert that the element is present on the page. To test whether an - * element is present on the page, use {@link #isElementPresent} instead. + * element is present on the page, use {@link #findElements}. * * The search criteria for an element may be defined using one of the * factories in the {@link By} namespace, or as a short-hand @@ -4593,23 +4572,7 @@ export class WebElement implements Serializable { * commands against the located element. If the element is not found, the * element will be invalidated and all scheduled commands aborted. */ - findElement(locator: By | Function): WebElementPromise; - - /** - * Schedules a command to test if there is at least one descendant of this - * element that matches the given search criteria. - * - * @param {!(by.By|Function)} locator The locator strategy to use when - * searching for the element. - * @return {!promise.Promise} A promise that will be - * resolved with whether an element could be located on the page. - * @deprecated This method will be removed in Selenium 3.0 for consistency - * with the other Selenium language bindings. This method is equivalent - * to - * - * element.findElements(locator).then(e => !!e.length); - */ - isElementPresent(locator: By | Function): promise.Promise; + findElement(locator: Locator): WebElementPromise; /** * Schedules a command to find all of the descendants of this element that @@ -4620,7 +4583,7 @@ export class WebElement implements Serializable { * @return {!promise.Promise>} A * promise that will resolve to an array of WebElements. */ - findElements(locator: By | Function): promise.Promise; + findElements(locator: Locator): promise.Promise; /** * Schedules a command to click on this element. @@ -4816,20 +4779,6 @@ export class WebElement implements Serializable { */ takeScreenshot(opt_scroll?: boolean): promise.Promise; - /** - * Schedules a command to retrieve the outer HTML of this element. - * @return {!promise.Promise.} A promise that will be - * resolved with the element's outer HTML. - */ - getOuterHtml(): promise.Promise; - - /** - * Schedules a command to retrieve the inner HTML of this element. - * @return {!promise.Promise} A promise that will be resolved with the - * element's inner HTML. - */ - getInnerHtml(): promise.Promise; - /** @override */ serialize(): promise.Promise; } @@ -4865,19 +4814,6 @@ export class WebElementPromise extends WebElement implements promise.IThenable); - /** - * Cancels the computation of this promise's value, rejecting the promise in the - * process. This method is a no-op if the promise has alreayd been resolved. - * - * @param {string=} opt_reason The reason this promise is being cancelled. - */ - cancel(opt_reason?: string): void; - - - /** @return {boolean} Whether this promise's value is still being computed. */ - isPending(): boolean; - - /** * Registers listeners for when this instance is resolved. * @@ -4907,74 +4843,6 @@ export class WebElementPromise extends WebElement implements promise.IThenable(opt_callback?: (value: WebElement) => R, opt_errback?: (error: any) => any): promise.Promise; - /** - * Registers a listener for when this promise is rejected. This is synonymous - * with the {@code catch} clause in a synchronous API: - *


-   *   // Synchronous API:
-   *   try {
-   *     doSynchronousWork();
-   *   } catch (ex) {
-   *     console.error(ex);
-   *   }
-   *
-   *   // Asynchronous promise API:
-   *   doAsynchronousWork().thenCatch(function(ex) {
-   *     console.error(ex);
-   *   });
-   * 
- * - * @param {function(*): (R|promise.Promise.)} errback The function - * to call if this promise is rejected. The function should expect a single - * argument: the rejection reason. - * @return {!promise.Promise.} A new promise which will be - * resolved with the result of the invoked callback. - * @template R - */ - thenCatch(errback: (error: any) => any): promise.Promise; - - - /** - * Registers a listener to invoke when this promise is resolved, regardless - * of whether the promise's value was successfully computed. This function - * is synonymous with the {@code finally} clause in a synchronous API: - *

-   *   // Synchronous API:
-   *   try {
-   *     doSynchronousWork();
-   *   } finally {
-   *     cleanUp();
-   *   }
-   *
-   *   // Asynchronous promise API:
-   *   doAsynchronousWork().thenFinally(cleanUp);
-   * 
- * - * Note: similar to the {@code finally} clause, if the registered - * callback returns a rejected promise or throws an error, it will silently - * replace the rejection error (if any) from this promise: - *

-   *   try {
-   *     throw Error('one');
-   *   } finally {
-   *     throw Error('two');  // Hides Error: one
-   *   }
-   *
-   *   promise.rejected(Error('one'))
-   *       .thenFinally(function() {
-   *         throw Error('two');  // Hides Error: one
-   *       });
-   * 
- * - * - * @param {function(): (R|promise.Promise.)} callback The function - * to call when this promise is resolved. - * @return {!promise.Promise.} A promise that will be fulfilled - * with the callback result. - * @template R - */ - thenFinally(callback: () => any): promise.Promise; - /** * Registers a listener for when this promise is rejected. This is synonymous * with the {@code catch} clause in a synchronous API: diff --git a/selenium-webdriver/opera.d.ts b/selenium-webdriver/opera.d.ts index cd02889527..b4d118f6a7 100644 --- a/selenium-webdriver/opera.d.ts +++ b/selenium-webdriver/opera.d.ts @@ -155,14 +155,17 @@ export class Options { export class Driver extends webdriver.WebDriver { /** + * Creates a new session for Opera. + * * @param {(capabilities.Capabilities|Options)=} opt_config The configuration * options. * @param {remote.DriverService=} opt_service The session to use; will use * the {@link getDefaultService default service} by default. * @param {promise.ControlFlow=} opt_flow The control flow to use, * or {@code null} to use the currently active flow. + * @return {!Driver} A new driver instance. */ - constructor(opt_config?: webdriver.Capabilities | Options, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); + static createSession(opt_config?: webdriver.Capabilities | Options, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow): Driver; /** * This function is a no-op as file detectors are not supported by this diff --git a/selenium-webdriver/remote.d.ts b/selenium-webdriver/remote.d.ts index ae4f156ba7..15303a6d7f 100644 --- a/selenium-webdriver/remote.d.ts +++ b/selenium-webdriver/remote.d.ts @@ -65,3 +65,135 @@ export class DriverService { */ stop(): webdriver.promise.Promise; } + +export module DriverService { + + /** + * Creates {@link DriverService} objects that manage a WebDriver server in a + * child process. + */ + export class Builder { + /** + * @param {string} exe Path to the executable to use. This executable must + * accept the `--port` flag for defining the port to start the server on. + * @throws {Error} If the provided executable path does not exist. + */ + constructor(exe: string); + + /** + * Define additional command line arguments to use when starting the server. + * + * @param {...CommandLineFlag} var_args The arguments to include. + * @return {!THIS} A self reference. + * @this {THIS} + * @template THIS + */ + addArguments(...var_args: string[]): this; + + + /** + * Sets the host name to access the server on. If specified, the + * {@linkplain #setLoopback() loopback} setting will be ignored. + * + * @param {string} hostname + * @return {!DriverService.Builder} A self reference. + */ + setHostname(hostname: string): this; + + /** + * Sets whether the service should be accessed at this host's loopback + * address. + * + * @param {boolean} loopback + * @return {!DriverService.Builder} A self reference. + */ + setLoopback(loopback: boolean): this; + + /** + * Sets the base path for WebDriver REST commands (e.g. "/wd/hub"). + * By default, the driver will accept commands relative to "/". + * + * @param {?string} basePath The base path to use, or `null` to use the + * default. + * @return {!DriverService.Builder} A self reference. + */ + setPath(basePath: string | null): this; + + + /** + * Sets the port to start the server on. + * + * @param {number} port The port to use, or 0 for any free port. + * @return {!DriverService.Builder} A self reference. + * @throws {Error} If an invalid port is specified. + */ + setPort(port: number): this; + + /** + * Defines the environment to start the server under. This setting will be + * inherited by every browser session started by the server. By default, the + * server will inherit the enviroment of the current process. + * + * @param {(Map|Object|null)} env The desired + * environment to use, or `null` if the server should inherit the + * current environment. + * @return {!DriverService.Builder} A self reference. + */ + setEnvironment(env: Map | {[name: string]: string} | null): this; + + /** + * IO configuration for the spawned server process. For more information, + * refer to the documentation of `child_process.spawn`. + * + * @param {StdIoOptions} config The desired IO configuration. + * @return {!DriverService.Builder} A self reference. + * @see https://nodejs.org/dist/latest-v4.x/docs/api/child_process.html#child_process_options_stdio + */ + setStdio(config: any): this; + + /** + * Creates a new DriverService using this instance's current configuration. + * + * @return {!DriverService} A new driver service. + */ + build(): DriverService; + } +} + +/** + * A {@link webdriver.FileDetector} that may be used when running + * against a remote + * [Selenium server](http://selenium-release.storage.googleapis.com/index.html). + * + * When a file path on the local machine running this script is entered with + * {@link webdriver.WebElement#sendKeys WebElement#sendKeys}, this file detector + * will transfer the specified file to the Selenium server's host; the sendKeys + * command will be updated to use the transfered file's path. + * + * __Note:__ This class depends on a non-standard command supported on the + * Java Selenium server. The file detector will fail if used with a server that + * only supports standard WebDriver commands (such as the ChromeDriver). + * + * @final + */ +export class FileDetector extends webdriver.FileDetector { + /** + * @constructor + **/ + constructor(); + + /** + * Prepares a `file` for use with the remote browser. If the provided path + * does not reference a normal file (i.e. it does not exist or is a + * directory), then the promise returned by this method will be resolved with + * the original file path. Otherwise, this method will upload the file to the + * remote server, which will return the file's path on the remote system so + * it may be referenced in subsequent commands. + * + * @param {!webdriver.WebDriver} driver The driver for the current browser. + * @param {string} file The path of the file to process. + * @return {!webdriver.promise.Promise} A promise for the processed + * file path. + */ + handleFile(driver: webdriver.WebDriver, file: string): webdriver.promise.Promise; +} diff --git a/selenium-webdriver/safari.d.ts b/selenium-webdriver/safari.d.ts index 7a6f1701c4..bbeb887410 100644 --- a/selenium-webdriver/safari.d.ts +++ b/selenium-webdriver/safari.d.ts @@ -65,7 +65,7 @@ export class Options { * merge these options into, if any. * @return {!Capabilities} The capabilities. */ - toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; + toCapabilities(opt_capabilities?: webdriver.Capabilities): webdriver.Capabilities; } /** @@ -79,11 +79,13 @@ export class Options { */ export class Driver extends webdriver.WebDriver { /** + * Creates a new Safari session. + * * @param {(Options|Capabilities)=} opt_config The configuration * options for the new session. * @param {promise.ControlFlow=} opt_flow The control flow to create * the driver under. + * @return {!Driver} A new driver instance. */ - constructor(opt_config?: Options | webdriver.Capabilities, opt_flow?: webdriver.promise.ControlFlow); - + static createSession(opt_config?: Options | webdriver.Capabilities, opt_flow?: webdriver.promise.ControlFlow): Driver; } diff --git a/selenium-webdriver/test/chrome.ts b/selenium-webdriver/test/chrome.ts index de358656bc..b26c43c2d6 100644 --- a/selenium-webdriver/test/chrome.ts +++ b/selenium-webdriver/test/chrome.ts @@ -3,9 +3,9 @@ import * as remote from 'selenium-webdriver/remote'; import * as webdriver from 'selenium-webdriver'; function TestChromeDriver() { - var driver: chrome.Driver = new chrome.Driver(); - driver = new chrome.Driver(webdriver.Capabilities.chrome()); - driver = new chrome.Driver(webdriver.Capabilities.chrome(), + var driver: chrome.Driver = chrome.Driver.createSession(); + driver = chrome.Driver.createSession(webdriver.Capabilities.chrome()); + driver = chrome.Driver.createSession(webdriver.Capabilities.chrome(), new remote.DriverService('executable', new chrome.Options()), new webdriver.promise.ControlFlow()); @@ -44,15 +44,15 @@ function TestServiceBuilder() { builder = new chrome.ServiceBuilder('exe'); var anything: any = builder.build(); - builder = builder.usingPort(8080); + builder = builder.setPort(8080); builder = builder.setAdbPort(5037); builder = builder.loggingTo('path'); builder = builder.enableVerboseLogging(); builder = builder.setNumHttpThreads(5); - builder = builder.setUrlBasePath('path'); + builder = builder.setPath('path'); builder = builder.setStdio('config'); builder = builder.setStdio(['A', 'B']); - builder = builder.withEnvironment({ A: 'a', B: 'b' }); + builder = builder.setEnvironment({ 'A': 'a', 'B': 'b' }); } function TestChromeModule() { diff --git a/selenium-webdriver/test/firefox.ts b/selenium-webdriver/test/firefox.ts index 8b329c8e73..38a3c3634e 100644 --- a/selenium-webdriver/test/firefox.ts +++ b/selenium-webdriver/test/firefox.ts @@ -1,6 +1,7 @@ import * as firefox from 'selenium-webdriver/firefox'; import * as remote from 'selenium-webdriver/remote'; import * as webdriver from 'selenium-webdriver'; +import * as http from 'selenium-webdriver/http'; function TestBinary() { var binary: firefox.Binary = new firefox.Binary(); @@ -12,9 +13,11 @@ function TestBinary() { } function TestFirefoxDriver() { - var driver: firefox.Driver = new firefox.Driver(); - driver = new firefox.Driver(webdriver.Capabilities.firefox()); - driver = new firefox.Driver(webdriver.Capabilities.firefox(), new webdriver.promise.ControlFlow()); + var driver: firefox.Driver = firefox.Driver.createSession(); + driver = firefox.Driver.createSession(webdriver.Capabilities.firefox()); + driver = firefox.Driver.createSession(webdriver.Capabilities.firefox(), new http.Executor(new http.HttpClient('http://someurl'))); + driver = firefox.Driver.createSession(webdriver.Capabilities.firefox(), new remote.DriverService('/dev/null', {})); + driver = firefox.Driver.createSession(webdriver.Capabilities.firefox(), new remote.DriverService('/dev/null', {}), new webdriver.promise.ControlFlow()); var baseDriver: webdriver.WebDriver = driver; } @@ -52,3 +55,20 @@ function TestFirefoxProfile() { var stringPromise: webdriver.promise.Promise = profile.writeToDisk(); stringPromise = profile.writeToDisk(true); } + + +function TestServiceBuilder() { + var builder: firefox.ServiceBuilder = new firefox.ServiceBuilder(); + builder = new firefox.ServiceBuilder('exe'); + + var anything: any = builder.build(); + builder = builder.setPort(8080); + builder = builder.enableVerboseLogging(); + builder = builder.enableVerboseLogging(true); + builder = builder.setFirefoxBinary('exe'); + builder = builder.setFirefoxBinary(new firefox.Binary()); + builder = builder.setPath('path'); + builder = builder.setStdio('config'); + builder = builder.setStdio(['A', 'B']); + builder = builder.setEnvironment({ 'A': 'a', 'B': 'b' }); +} diff --git a/selenium-webdriver/test/index.ts b/selenium-webdriver/test/index.ts index 5d32724b15..2556e7e2a8 100644 --- a/selenium-webdriver/test/index.ts +++ b/selenium-webdriver/test/index.ts @@ -1,16 +1,10 @@ import * as webdriver from 'selenium-webdriver'; import * as chrome from 'selenium-webdriver/chrome'; import * as firefox from 'selenium-webdriver/firefox'; +import * as http from 'selenium-webdriver/http'; import * as remote from 'selenium-webdriver/remote'; -import * as executors from 'selenium-webdriver/executors'; import * as testing from 'selenium-webdriver/testing'; -function TestExecutors() { - var exec: webdriver.Executor = executors.createExecutor('url'); - var promise: webdriver.promise.Promise; - exec = executors.createExecutor(promise); -} - function TestBuilder() { var builder: webdriver.Builder = new webdriver.Builder(); @@ -219,11 +213,6 @@ function TestCommand() { command = command.setParameters({ param: 123 }); } -function TestDeferredExecutor() { - var promise: webdriver.promise.Promise; - var executor: webdriver.DeferredExecutor = new webdriver.DeferredExecutor(promise); -} - function TestCommandName() { var command: string; @@ -469,14 +458,6 @@ function TestSession() { var data: string = session.toJSON(); } -function TestUnhandledAlertError() { - var someFunc = (error: webdriver.UnhandledAlertError) => { - var baseError: Error = error; - var str: string = error.getAlertText(); - str = error.toString(); - }; -} - function TestWebDriverFileDetector() { var driver: webdriver.WebDriver = new webdriver.Builder(). withCapabilities(webdriver.Capabilities.chrome()). @@ -519,18 +500,28 @@ function TestWebDriverOptions() { var options: webdriver.Options = new webdriver.Options(driver); var promise: webdriver.promise.Promise; + var name: string = 'name'; + var value: string = 'value'; + var path: string = 'path'; + var domain: string = 'domain'; + var secure: boolean = true; + var httpOnly: boolean = true; + // Add Cookie - promise = options.addCookie('name', 'value'); - promise = options.addCookie('name', 'value', 'path'); - promise = options.addCookie('name', 'value', 'path', 'domain'); - promise = options.addCookie('name', 'value', 'path', 'domain', true); - promise = options.addCookie('name', 'value', 'path', 'domain', true, 123); - promise = options.addCookie('name', 'value', 'path', 'domain', true, Date.now()); + promise = options.addCookie({ name, value }); + promise = options.addCookie({ name, value, path }); + promise = options.addCookie({ name, value, path, domain }); + promise = options.addCookie({ name, value, path, domain, secure }); + promise = options.addCookie({ name, value, path, domain, secure, httpOnly }); + promise = options.addCookie({ name, value, path, domain, secure, httpOnly, expiry: 123 }); + promise = options.addCookie({ name, value, path, domain, secure, httpOnly, expiry: Date.now() }); promise = options.deleteAllCookies(); promise = options.deleteCookie('name'); - options.getCookie('name').then((cookies: webdriver.IWebDriverOptionsCookie) => {}); - options.getCookies().then((cookies: webdriver.IWebDriverOptionsCookie[]) => {}); + options.getCookie('name').then((cookie: webdriver.IWebDriverCookie) => { + var expiry: number = cookie.expiry; + }); + options.getCookies().then((cookies: webdriver.IWebDriverCookie[]) => { }); var logs: webdriver.Logs = options.logs(); var timeouts: webdriver.Timeouts = options.timeouts(); @@ -585,7 +576,8 @@ function TestWebDriverWindow() { function TestWebDriver() { var session: webdriver.Session = new webdriver.Session('ABC', webdriver.Capabilities.android()); var sessionPromise: webdriver.promise.Promise; - var executor: webdriver.Executor = executors.createExecutor('http://someserver'); + var httpClient: http.HttpClient = new http.HttpClient('http://someserver'); + var executor: http.Executor = new http.Executor(httpClient); var flow: webdriver.promise.ControlFlow = new webdriver.promise.ControlFlow(); var driver: webdriver.WebDriver = new webdriver.WebDriver(session, executor); driver = new webdriver.WebDriver(session, executor, flow); @@ -595,6 +587,7 @@ function TestWebDriver() { var voidPromise: webdriver.promise.Promise; var stringPromise: webdriver.promise.Promise; var booleanPromise: webdriver.promise.Promise; + var webElementPromise: webdriver.WebElementPromise; var actions: webdriver.ActionSequence = driver.actions(); var touchActions: webdriver.TouchSequence = driver.touchActions(); @@ -638,9 +631,6 @@ function TestWebDriver() { stringPromise = driver.getTitle(); stringPromise = driver.getWindowHandle(); - booleanPromise = driver.isElementPresent(webdriver.By.className('ABC')); - booleanPromise = driver.isElementPresent(webdriver.By.js('function(){}')); - var options: webdriver.Options = driver.manage(); var navigation: webdriver.Navigation = driver.navigate(); var locator: webdriver.TargetLocator = driver.switchTo(); @@ -653,14 +643,17 @@ function TestWebDriver() { voidPromise = driver.sleep(123); stringPromise = driver.takeScreenshot(); - var booleanCondition: webdriver.until.Condition; + var booleanCondition: webdriver.Condition; booleanPromise = driver.wait(booleanPromise); booleanPromise = driver.wait(booleanCondition); booleanPromise = driver.wait((driver: webdriver.WebDriver) => true); - let conditionFunction: Function; // tslint:disable-line:prefer-const - booleanPromise = driver.wait(conditionFunction); + booleanPromise = driver.wait((driver: webdriver.WebDriver) => Promise.resolve(true)); + booleanPromise = driver.wait((driver: webdriver.WebDriver) => webdriver.promise.Promise.resolve(true)); booleanPromise = driver.wait(booleanPromise, 123); booleanPromise = driver.wait(booleanPromise, 123, 'Message'); + let webElementCondition: webdriver.WebElementCondition; + webElementPromise = driver.wait(webElementCondition); + voidPromise = driver.wait(webElementCondition).click(); driver = webdriver.WebDriver.attachToSession(executor, 'ABC'); driver = webdriver.WebDriver.createSession(executor, webdriver.Capabilities.android()); @@ -690,15 +683,13 @@ function TestWebElement() { voidPromise = element.click(); element = element.findElement(webdriver.By.id('ABC')); - element.findElements(webdriver.By.className('ABC')).then((elements: webdriver.WebElement[]) => {}); - booleanPromise = element.isElementPresent(webdriver.By.className('ABC')); + element = element.findElement({id: 'ABC'}); + element.findElements({className: 'ABC'}).then((elements: webdriver.WebElement[]) => { }); stringPromise = element.getAttribute('class'); stringPromise = element.getCssValue('display'); driver = element.getDriver(); - stringPromise = element.getInnerHtml(); element.getLocation().then((location: webdriver.ILocation) => {}); - stringPromise = element.getOuterHtml(); element.getSize().then((size: webdriver.ISize) => {}); stringPromise = element.getTagName(); stringPromise = element.getText(); @@ -712,7 +703,6 @@ function TestWebElement() { voidPromise = element.sendKeys('A', 1, webdriver.Key.BACK_SPACE, stringPromise); voidPromise = element.submit(); element.getId().then((id: string) => {}); - element.getRawId().then((id: string) => {}); element.serialize().then((id: webdriver.IWebElementId) => {}); booleanPromise = webdriver.WebElement.equals(element, new webdriver.WebElement(driver, 'elementId')); @@ -725,19 +715,10 @@ function TestWebElementPromise() { var elementPromise: webdriver.WebElementPromise = driver.findElement(webdriver.By.id('id')); - elementPromise.cancel(); - elementPromise.cancel('reason'); - - var bool: boolean = elementPromise.isPending(); - elementPromise.then(); elementPromise.then((element: webdriver.WebElement) => {}); elementPromise.then((element: webdriver.WebElement) => {}, (error: any) => {}); elementPromise.then((element: webdriver.WebElement) => 'foo', (error: any) => {}).then((result: string) => {}); - - elementPromise.thenCatch((error: any) => {}).then((value: any) => {}); - - elementPromise.thenFinally(() => {}); } function TestLogging() { @@ -871,29 +852,32 @@ function TestUntilModule() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var conditionB: webdriver.until.Condition = new webdriver.until.Condition('message', (driver: webdriver.WebDriver) => true); - var conditionBBase: webdriver.until.Condition = conditionB; - var conditionWebElement: webdriver.until.Condition; - var conditionWebElements: webdriver.until.Condition; + var conditionB: webdriver.Condition = new webdriver.Condition('message', (driver: webdriver.WebDriver) => true); + var conditionBBase: webdriver.Condition = conditionB; + var conditionWebElement: webdriver.WebElementCondition; + var conditionWebElements: webdriver.Condition; conditionB = webdriver.until.ableToSwitchToFrame(5); - var conditionAlert: webdriver.until.Condition = webdriver.until.alertIsPresent(); + var conditionAlert: webdriver.Condition = webdriver.until.alertIsPresent(); var el: webdriver.WebElement = driver.findElement(webdriver.By.id('id')); - conditionB = webdriver.until.elementIsDisabled(el); - conditionB = webdriver.until.elementIsEnabled(el); - conditionB = webdriver.until.elementIsNotSelected(el); - conditionB = webdriver.until.elementIsNotVisible(el); - conditionB = webdriver.until.elementIsSelected(el); - conditionB = webdriver.until.elementIsVisible(el); - conditionB = webdriver.until.elementTextContains(el, 'text'); - conditionB = webdriver.until.elementTextIs(el, 'text'); - conditionB = webdriver.until.elementTextMatches(el, /text/); conditionB = webdriver.until.stalenessOf(el); conditionB = webdriver.until.titleContains('text'); conditionB = webdriver.until.titleIs('text'); conditionB = webdriver.until.titleMatches(/text/); + conditionB = webdriver.until.urlContains('text'); + conditionB = webdriver.until.urlIs('text'); + conditionB = webdriver.until.urlMatches(/text/); + conditionWebElement = webdriver.until.elementIsDisabled(el); + conditionWebElement = webdriver.until.elementIsEnabled(el); + conditionWebElement = webdriver.until.elementIsNotSelected(el); + conditionWebElement = webdriver.until.elementIsNotVisible(el); + conditionWebElement = webdriver.until.elementIsSelected(el); + conditionWebElement = webdriver.until.elementIsVisible(el); conditionWebElement = webdriver.until.elementLocated(webdriver.By.id('id')); + conditionWebElement = webdriver.until.elementTextContains(el, 'text'); + conditionWebElement = webdriver.until.elementTextIs(el, 'text'); + conditionWebElement = webdriver.until.elementTextMatches(el, /text/); conditionWebElements = webdriver.until.elementsLocated(webdriver.By.className('class')); } @@ -955,18 +939,10 @@ function TestPromiseClass() { promise = new webdriver.promise.Promise((resolve: (value: webdriver.promise.Promise) => void, reject: () => void) => {}); promise = new webdriver.promise.Promise((resolve: (value: string) => void, reject: () => void) => {}, controlFlow); - promise.cancel('Abort'); - - var isPending: boolean = promise.isPending(); - promise = promise.then(); promise = promise.then((a: string) => 'cde'); promise = promise.then((a: string) => 'cde', (e: any) => {}); promise = promise.then((a: string) => 'cde', (e: any) => 123); - - promise = promise.thenCatch((error: any) => {}); - - promise.thenFinally(() => {}); } function TestThenableClass() { @@ -974,46 +950,9 @@ function TestThenableClass() { resolve('a'); }); - thenable.cancel('Abort'); - - var isPending: boolean = thenable.isPending(); - thenable = thenable.then((a: string) => 'cde'); thenable = thenable.then((a: string) => 'cde', (e: any) => {}); thenable = thenable.then((a: string) => 'cde', (e: any) => 123); - - thenable = thenable.thenCatch((error: any) => {}); - - thenable.thenFinally(() => {}); -} - -function TestErrorCode() { - var errorCode: number; - - errorCode = new webdriver.error.ElementNotSelectableError().code(); - errorCode = new webdriver.error.ElementNotVisibleError().code(); - errorCode = new webdriver.error.InvalidArgumentError().code(); - errorCode = new webdriver.error.InvalidCookieDomainError().code(); - errorCode = new webdriver.error.InvalidElementCoordinatesError().code(); - errorCode = new webdriver.error.InvalidElementStateError().code(); - errorCode = new webdriver.error.InvalidSelectorError().code(); - errorCode = new webdriver.error.NoSuchSessionError().code(); - errorCode = new webdriver.error.JavascriptError().code(); - errorCode = new webdriver.error.MoveTargetOutOfBoundsError().code(); - errorCode = new webdriver.error.NoSuchAlertError().code(); - errorCode = new webdriver.error.NoSuchElementError().code(); - errorCode = new webdriver.error.NoSuchFrameError().code(); - errorCode = new webdriver.error.NoSuchWindowError().code(); - errorCode = new webdriver.error.ScriptTimeoutError().code(); - errorCode = new webdriver.error.SessionNotCreatedError().code(); - errorCode = new webdriver.error.StaleElementReferenceError().code(); - errorCode = new webdriver.error.TimeoutError().code(); - errorCode = new webdriver.error.UnableToSetCookieError().code(); - errorCode = new webdriver.error.UnableToCaptureScreenError().code(); - errorCode = new webdriver.error.UnexpectedAlertOpenError().code(); - errorCode = new webdriver.error.UnknownCommandError().code(); - errorCode = new webdriver.error.UnknownMethodError().code(); - errorCode = new webdriver.error.UnsupportedOperationError().code(); } async function TestAsyncAwaitable() { diff --git a/selenium-webdriver/test/remote.ts b/selenium-webdriver/test/remote.ts new file mode 100644 index 0000000000..a783101290 --- /dev/null +++ b/selenium-webdriver/test/remote.ts @@ -0,0 +1,11 @@ +import * as remote from "selenium-webdriver/remote"; +import * as webdriver from "selenium-webdriver"; + +function TestRemoteFileDetector() { + const driver: webdriver.WebDriver = new webdriver.Builder() + .withCapabilities(webdriver.Capabilities.chrome()) + .build(); + + const fileDetector: remote.FileDetector = new remote.FileDetector(); + fileDetector.handleFile(driver, 'path/to/file').then((path: string) => { /* empty */ }); +} diff --git a/selenium-webdriver/tsconfig.json b/selenium-webdriver/tsconfig.json index 50c76c7b28..a72458a455 100644 --- a/selenium-webdriver/tsconfig.json +++ b/selenium-webdriver/tsconfig.json @@ -20,7 +20,6 @@ "index.d.ts", "chrome.d.ts", "edge.d.ts", - "executors.d.ts", "firefox.d.ts", "http.d.ts", "ie.d.ts", @@ -30,6 +29,7 @@ "testing.d.ts", "test/index.ts", "test/chrome.ts", - "test/firefox.ts" + "test/firefox.ts", + "test/remote.ts" ] -} \ No newline at end of file +} diff --git a/selenium-webdriver/tslint.json b/selenium-webdriver/tslint.json index eb0befd093..93fffac84e 100644 --- a/selenium-webdriver/tslint.json +++ b/selenium-webdriver/tslint.json @@ -3,7 +3,7 @@ "rules": { "callable-types": false, "forbidden-types": false, - "interface-name": false, + "interface-name": [false], "no-empty-interface": false, "unified-signatures": false } diff --git a/selenium-webdriver/v2/chrome.d.ts b/selenium-webdriver/v2/chrome.d.ts new file mode 100644 index 0000000000..eb7b9f13c1 --- /dev/null +++ b/selenium-webdriver/v2/chrome.d.ts @@ -0,0 +1,415 @@ +/* tslint:disable */ +import * as webdriver from './index'; +import * as remote from './remote'; + +/** + * Creates a new WebDriver client for Chrome. + * + * @extends {webdriver.WebDriver} + */ +export class Driver extends webdriver.WebDriver { + /** + * @param {(webdriver.Capabilities|Options)=} opt_config The configuration + * options. + * @param {remote.DriverService=} opt_service The session to use; will use + * the {@link getDefaultService default service} by default. + * @param {webdriver.promise.ControlFlow=} opt_flow The control flow to use, or + * {@code null} to use the currently active flow. + * @constructor + */ + constructor(opt_config?: Options | webdriver.Capabilities, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); +} + +interface IOptionsValues { + args: string[]; + binary?: string; + detach: boolean; + extensions: string[]; + localState?: any; + logFile?: string; + prefs?: any; +} + +interface IPerfLoggingPrefs { + enableNetwork: boolean; + enablePage: boolean; + enableTimeline: boolean; + tracingCategories: string; + bufferUsageReportingInterval: number; +} + +/** + * Class for managing ChromeDriver specific options. + */ +export class Options { + /** + * @constructor + */ + constructor(); + + /** + * Extracts the ChromeDriver specific options from the given capabilities + * object. + * @param {!webdriver.Capabilities} capabilities The capabilities object. + * @return {!Options} The ChromeDriver options. + */ + static fromCapabilities(capabilities: webdriver.Capabilities): Options; + + + /** + * Add additional command line arguments to use when launching the Chrome + * browser. Each argument may be specified with or without the '--' prefix + * (e.g. '--foo' and 'foo'). Arguments with an associated value should be + * delimited by an '=': 'foo=bar'. + * @param {...(string|!Array.)} var_args The arguments to add. + * @return {!Options} A self reference. + */ + addArguments(...var_args: string[]): Options; + + + /** + * List of Chrome command line switches to exclude that ChromeDriver by default + * passes when starting Chrome. Do not prefix switches with '--'. + * + * @param {...(string|!Array)} var_args The switches to exclude. + * @return {!Options} A self reference. + */ + excludeSwitches(...var_args: string[]): Options; + + + /** + * Add additional extensions to install when launching Chrome. Each extension + * should be specified as the path to the packed CRX file, or a Buffer for an + * extension. + * @param {...(string|!Buffer|!Array.<(string|!Buffer)>)} var_args The + * extensions to add. + * @return {!Options} A self reference. + */ + addExtensions(...var_args: any[]): Options; + + + /** + * Sets the path to the Chrome binary to use. On Mac OS X, this path should + * reference the actual Chrome executable, not just the application binary + * (e.g. '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'). + * + * The binary path be absolute or relative to the chromedriver server + * executable, but it must exist on the machine that will launch Chrome. + * + * @param {string} path The path to the Chrome binary to use. + * @return {!Options} A self reference. + */ + setChromeBinaryPath(path: string): Options; + + + /** + * Sets whether to leave the started Chrome browser running if the controlling + * ChromeDriver service is killed before {@link webdriver.WebDriver#quit()} is + * called. + * @param {boolean} detach Whether to leave the browser running if the + * chromedriver service is killed before the session. + * @return {!Options} A self reference. + */ + detachDriver(detach: boolean): Options; + + + /** + * Sets the user preferences for Chrome's user profile. See the 'Preferences' + * file in Chrome's user data directory for examples. + * @param {!Object} prefs Dictionary of user preferences to use. + * @return {!Options} A self reference. + */ + setUserPreferences(prefs: any): Options; + + + /** + * Sets the logging preferences for the new session. + * @param {!webdriver.logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPrefs(prefs: webdriver.logging.Preferences): Options; + + /** + * Sets the performance logging preferences. Options include: + * + * - `enableNetwork`: Whether or not to collect events from Network domain. + * - `enablePage`: Whether or not to collect events from Page domain. + * - `enableTimeline`: Whether or not to collect events from Timeline domain. + * Note: when tracing is enabled, Timeline domain is implicitly disabled, + * unless `enableTimeline` is explicitly set to true. + * - `tracingCategories`: A comma-separated string of Chrome tracing categories + * for which trace events should be collected. An unspecified or empty + * string disables tracing. + * - `bufferUsageReportingInterval`: The requested number of milliseconds + * between DevTools trace buffer usage events. For example, if 1000, then + * once per second, DevTools will report how full the trace buffer is. If a + * report indicates the buffer usage is 100%, a warning will be issued. + * + * @param {{enableNetwork: boolean, + * enablePage: boolean, + * enableTimeline: boolean, + * tracingCategories: string, + * bufferUsageReportingInterval: number}} prefs The performance + * logging preferences. + * @return {!Options} A self reference. + */ + setPerfLoggingPrefs(prefs: IPerfLoggingPrefs): Options; + + + /** + * Sets preferences for the 'Local State' file in Chrome's user data + * directory. + * @param {!Object} state Dictionary of local state preferences. + * @return {!Options} A self reference. + */ + setLocalState(state: any): Options; + + + /** + * Sets the name of the activity hosting a Chrome-based Android WebView. This + * option must be set to connect to an [Android WebView]( + * https://sites.google.com/a/chromium.org/chromedriver/getting-started/getting-started---android) + * + * @param {string} name The activity name. + * @return {!Options} A self reference. + */ + androidActivity(name: string): Options; + + + /** + * Sets the device serial number to connect to via ADB. If not specified, the + * ChromeDriver will select an unused device at random. An error will be + * returned if all devices already have active sessions. + * + * @param {string} serial The device serial number to connect to. + * @return {!Options} A self reference. + */ + androidDeviceSerial(serial: string): Options; + + + /** + * Configures the ChromeDriver to launch Chrome on Android via adb. This + * function is shorthand for + * {@link #androidPackage options.androidPackage('com.android.chrome')}. + * @return {!Options} A self reference. + */ + androidChrome(): Options; + + + /** + * Sets the package name of the Chrome or WebView app. + * + * @param {?string} pkg The package to connect to, or `null` to disable Android + * and switch back to using desktop Chrome. + * @return {!Options} A self reference. + */ + androidPackage(pkg: string): Options; + + + /** + * Sets the process name of the Activity hosting the WebView (as given by `ps`). + * If not specified, the process name is assumed to be the same as + * {@link #androidPackage}. + * + * @param {string} processName The main activity name. + * @return {!Options} A self reference. + */ + androidProcess(processName: string): Options; + + + /** + * Sets whether to connect to an already-running instead of the specified + * {@linkplain #androidProcess app} instead of launching the app with a clean + * data directory. + * + * @param {boolean} useRunning Whether to connect to a running instance. + * @return {!Options} A self reference. + */ + androidUseRunningApp(useRunning: boolean): Options; + + + /** + * Sets the path to Chrome's log file. This path should exist on the machine + * that will launch Chrome. + * @param {string} path Path to the log file to use. + * @return {!Options} A self reference. + */ + setChromeLogFile(path: string): Options; + + + /** + * Sets the directory to store Chrome minidumps in. This option is only + * supported when ChromeDriver is running on Linux. + * @param {string} path The directory path. + * @return {!Options} A self reference. + */ + setChromeMinidumpPath(path: string): Options; + + + /** + * Configures Chrome to emulate a mobile device. For more information, refer + * to the ChromeDriver project page on [mobile emulation][em]. Configuration + * options include: + * + * - `deviceName`: The name of a pre-configured [emulated device][devem] + * - `width`: screen width, in pixels + * - `height`: screen height, in pixels + * - `pixelRatio`: screen pixel ratio + * + * __Example 1: Using a Pre-configured Device__ + * + * let options = new chrome.Options().setMobileEmulation( + * {deviceName: 'Google Nexus 5'}); + * + * let driver = new chrome.Driver(options); + * + * __Example 2: Using Custom Screen Configuration__ + * + * let options = new chrome.Options().setMobileEmulation({ + * width: 360, + * height: 640, + * pixelRatio: 3.0 + * }); + * + * let driver = new chrome.Driver(options); + * + * + * [em]: https://sites.google.com/a/chromium.org/chromedriver/mobile-emulation + * [devem]: https://developer.chrome.com/devtools/docs/device-mode + * + * @param {?({deviceName: string}| + * {width: number, height: number, pixelRatio: number})} config The + * mobile emulation configuration, or `null` to disable emulation. + * @return {!Options} A self reference. + */ + setMobileEmulation(config: any): Options; + + /** + * Sets the proxy settings for the new session. + * @param {webdriver.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + + /** + * Converts this options instance to a {@link webdriver.Capabilities} object. + * @param {webdriver.Capabilities=} opt_capabilities The capabilities to merge + * these options into, if any. + * @return {!webdriver.Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities?: webdriver.Capabilities): webdriver.Capabilities; +} + +/** + * Creates {@link remote.DriverService} instances that manage a ChromeDriver + * server. + */ +export class ServiceBuilder { + /** + * @param {string=} opt_exe Path to the server executable to use. If omitted, + * the builder will attempt to locate the chromedriver on the current + * PATH. + * @throws {Error} If provided executable does not exist, or the chromedriver + * cannot be found on the PATH. + * @constructor + */ + constructor(opt_exe?: string); + + /** + * Sets the port to start the ChromeDriver on. + * @param {number} port The port to use, or 0 for any free port. + * @return {!ServiceBuilder} A self reference. + * @throws {Error} If the port is invalid. + */ + usingPort(port: number): ServiceBuilder; + + + /** + * Sets which port adb is listening to. _The ChromeDriver will connect to adb + * if an {@linkplain Options#androidPackage Android session} is requested, but + * adb **must** be started beforehand._ + * + * @param {number} port Which port adb is running on. + * @return {!ServiceBuilder} A self reference. + */ + setAdbPort(port: number): ServiceBuilder; + + + /** + * Sets the path of the log file the driver should log to. If a log file is + * not specified, the driver will log to stderr. + * @param {string} path Path of the log file to use. + * @return {!ServiceBuilder} A self reference. + */ + loggingTo(path: string): ServiceBuilder; + + + /** + * Enables verbose logging. + * @return {!ServiceBuilder} A self reference. + */ + enableVerboseLogging(): ServiceBuilder; + + + /** + * Sets the number of threads the driver should use to manage HTTP requests. + * By default, the driver will use 4 threads. + * @param {number} n The number of threads to use. + * @return {!ServiceBuilder} A self reference. + */ + setNumHttpThreads(n: number): ServiceBuilder; + + + /** + * Sets the base path for WebDriver REST commands (e.g. '/wd/hub'). + * By default, the driver will accept commands relative to '/'. + * @param {string} path The base path to use. + * @return {!ServiceBuilder} A self reference. + */ + setUrlBasePath(path: string): ServiceBuilder; + + + /** + * Defines the stdio configuration for the driver service. See + * {@code child_process.spawn} for more information. + * @param {(string|!Array.)} config The + * configuration to use. + * @return {!ServiceBuilder} A self reference. + */ + setStdio(config: string | Array): ServiceBuilder; + + + /** + * Defines the environment to start the server under. This settings will be + * inherited by every browser session started by the server. + * @param {!Object.} env The environment to use. + * @return {!ServiceBuilder} A self reference. + */ + withEnvironment(env: { [key: string]: string }): ServiceBuilder; + + + /** + * Creates a new DriverService using this instance's current configuration. + * @return {remote.DriverService} A new driver service using this instance's + * current configuration. + * @throws {Error} If the driver exectuable was not specified and a default + * could not be found on the current PATH. + */ + build(): remote.DriverService; +} + +/** + * Returns the default ChromeDriver service. If such a service has not been + * configured, one will be constructed using the default configuration for + * a ChromeDriver executable found on the system PATH. + * @return {!remote.DriverService} The default ChromeDriver service. + */ +export function getDefaultService(): remote.DriverService; + +/** + * Sets the default service to use for new ChromeDriver instances. + * @param {!remote.DriverService} service The service to use. + * @throws {Error} If the default service is currently running. + */ +export function setDefaultService(service: remote.DriverService): void; diff --git a/selenium-webdriver/v2/edge.d.ts b/selenium-webdriver/v2/edge.d.ts new file mode 100644 index 0000000000..576dc01f94 --- /dev/null +++ b/selenium-webdriver/v2/edge.d.ts @@ -0,0 +1,125 @@ +/* tslint:disable */ +import * as webdriver from './index'; +import * as remote from './remote'; + +export class Driver extends webdriver.WebDriver { + /** + * @param {(capabilities.Capabilities|Options)=} opt_config The configuration + * options. + * @param {remote.DriverService=} opt_service The session to use; will use + * the {@linkplain #getDefaultService default service} by default. + * @param {promise.ControlFlow=} opt_flow The control flow to use, or + * {@code null} to use the currently active flow. + */ + constructor(opt_config?: webdriver.Capabilities | Options, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); + + /** + * This function is a no-op as file detectors are not supported by this + * implementation. + * @override + */ + setFileDetector(): void; +} + +/** + * Class for managing MicrosoftEdgeDriver specific options. + */ +export class Options { + + /** + * Extracts the MicrosoftEdgeDriver specific options from the given + * capabilities object. + * @param {!capabilities.Capabilities} caps The capabilities object. + * @return {!Options} The MicrosoftEdgeDriver options. + */ + static fromCapabilities(cap: webdriver.Capabilities): Options; + + /** + * Sets the proxy settings for the new session. + * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + /** + * Sets the page load strategy for Edge. + * Supported values are 'normal', 'eager', and 'none'; + * + * @param {string} pageLoadStrategy The page load strategy to use. + * @return {!Options} A self reference. + */ + setPageLoadStrategy(pageLoadStrategy: string): Options; + + /** + * Converts this options instance to a {@link capabilities.Capabilities} + * object. + * @param {capabilities.Capabilities=} opt_capabilities The capabilities to + * merge these options into, if any. + * @return {!capabilities.Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; +} + +/** + * Creates {@link remote.DriverService} instances that manage a + * MicrosoftEdgeDriver server in a child process. + */ +export class ServiceBuilder { + /** + * @param {string=} opt_exe Path to the server executable to use. If omitted, + * the builder will attempt to locate the MicrosoftEdgeDriver on the current + * PATH. + * @throws {Error} If provided executable does not exist, or the + * MicrosoftEdgeDriver cannot be found on the PATH. + */ + constructor(opt_exe?: string); + + /** + * Defines the stdio configuration for the driver service. See + * {@code child_process.spawn} for more information. + * @param {(string|!Array.)} + * config The configuration to use. + * @return {!ServiceBuilder} A self reference. + */ + setStdio(config: string | Array): ServiceBuilder; + + /** + * Sets the port to start the MicrosoftEdgeDriver on. + * @param {number} port The port to use, or 0 for any free port. + * @return {!ServiceBuilder} A self reference. + * @throws {Error} If the port is invalid. + */ + usingPort(port: number): ServiceBuilder; + + /** + * Defines the environment to start the server under. This settings will be + * inherited by every browser session started by the server. + * @param {!Object.} env The environment to use. + * @return {!ServiceBuilder} A self reference. + */ + withEnvironment(env: Object): ServiceBuilder; + + /** + * Creates a new DriverService using this instance's current configuration. + * @return {!remote.DriverService} A new driver service using this instance's + * current configuration. + * @throws {Error} If the driver exectuable was not specified and a default + * could not be found on the current PATH. + */ + build(): remote.DriverService; +} + +/** + * Returns the default MicrosoftEdgeDriver service. If such a service has + * not been configured, one will be constructed using the default configuration + * for an MicrosoftEdgeDriver executable found on the system PATH. + * @return {!remote.DriverService} The default MicrosoftEdgeDriver service. + */ +export function getDefaultService(): remote.DriverService; + +/** + * Sets the default service to use for new MicrosoftEdgeDriver instances. + * @param {!remote.DriverService} service The service to use. + * @throws {Error} If the default service is currently running. + */ +export function setDefaultService(service: remote.DriverService): void; diff --git a/selenium-webdriver/executors.d.ts b/selenium-webdriver/v2/executors.d.ts similarity index 96% rename from selenium-webdriver/executors.d.ts rename to selenium-webdriver/v2/executors.d.ts index c7bf15ef8d..ddb3e5b752 100644 --- a/selenium-webdriver/executors.d.ts +++ b/selenium-webdriver/v2/executors.d.ts @@ -1,3 +1,4 @@ +/* tslint:disable */ import * as webdriver from './index'; /** diff --git a/selenium-webdriver/v2/firefox.d.ts b/selenium-webdriver/v2/firefox.d.ts new file mode 100644 index 0000000000..9865896ba7 --- /dev/null +++ b/selenium-webdriver/v2/firefox.d.ts @@ -0,0 +1,254 @@ +/* tslint:disable */ +import * as webdriver from './index'; +import * as remote from './remote'; + +/** + * Manages a Firefox subprocess configured for use with WebDriver. + */ +export class Binary { + /** + * @param {string=} opt_exe Path to the Firefox binary to use. If not + * specified, will attempt to locate Firefox on the current system. + * @constructor + */ + constructor(opt_exe?: string); + + /** + * Add arguments to the command line used to start Firefox. + * @param {...(string|!Array.)} var_args Either the arguments to add as + * varargs, or the arguments as an array. + */ + addArguments(...var_args: string[]): void; + + + /** + * Launches Firefox and eturns a promise that will be fulfilled when the process + * terminates. + * @param {string} profile Path to the profile directory to use. + * @return {!promise.Promise.} A promise for the process result. + * @throws {Error} If this instance has already been started. + */ + launch(profile: string): webdriver.promise.Promise; + + + /** + * Kills the managed Firefox process. + * @return {!promise.Promise} A promise for when the process has terminated. + */ + kill(): webdriver.promise.Promise; +} + +/** + * Models a Firefox proifle directory for use with the FirefoxDriver. The + * {@code Proifle} directory uses an in-memory model until {@link #writeToDisk} + * is called. + */ +export class Profile { + /** + * @param {string=} opt_dir Path to an existing Firefox profile directory to + * use a template for this profile. If not specified, a blank profile will + * be used. + * @constructor + */ + constructor(opt_dir?: string); + + /** + * Registers an extension to be included with this profile. + * @param {string} extension Path to the extension to include, as either an + * unpacked extension directory or the path to a xpi file. + */ + addExtension(extension: string): void; + + + /** + * Sets a desired preference for this profile. + * @param {string} key The preference key. + * @param {(string|number|boolean)} value The preference value. + * @throws {Error} If attempting to set a frozen preference. + */ + setPreference(key: string, value: string): void; + setPreference(key: string, value: number): void; + setPreference(key: string, value: boolean): void; + + + /** + * Returns the currently configured value of a profile preference. This does + * not include any defaults defined in the profile's template directory user.js + * file (if a template were specified on construction). + * @param {string} key The desired preference. + * @return {(string|number|boolean|undefined)} The current value of the + * requested preference. + */ + getPreference(key: string): any; + + + /** + * @return {number} The port this profile is currently configured to use, or + * 0 if the port will be selected at random when the profile is written + * to disk. + */ + getPort(): number; + + + /** + * Sets the port to use for the WebDriver extension loaded by this profile. + * @param {number} port The desired port, or 0 to use any free port. + */ + setPort(port: number): void; + + + /** + * @return {boolean} Whether the FirefoxDriver is configured to automatically + * accept untrusted SSL certificates. + */ + acceptUntrustedCerts(): boolean; + + + /** + * Sets whether the FirefoxDriver should automatically accept untrusted SSL + * certificates. + * @param {boolean} value . + */ + setAcceptUntrustedCerts(value: boolean): void; + + + /** + * Sets whether to assume untrusted certificates come from untrusted issuers. + * @param {boolean} value . + */ + setAssumeUntrustedCertIssuer(value: boolean): void; + + + /** + * @return {boolean} Whether to assume untrusted certs come from untrusted + * issuers. + */ + assumeUntrustedCertIssuer(): boolean; + + + /** + * Sets whether to use native events with this profile. + * @param {boolean} enabled . + */ + setNativeEventsEnabled(enabled: boolean): void; + + + /** + * Returns whether native events are enabled in this profile. + * @return {boolean} . + */ + nativeEventsEnabled(): boolean; + + + /** + * Writes this profile to disk. + * @param {boolean=} opt_excludeWebDriverExt Whether to exclude the WebDriver + * extension from the generated profile. Used to reduce the size of an + * {@link #encode() encoded profile} since the server will always install + * the extension itself. + * @return {!promise.Promise.} A promise for the path to the new + * profile directory. + */ + writeToDisk(opt_excludeWebDriverExt?: boolean): webdriver.promise.Promise; + + + /** + * Encodes this profile as a zipped, base64 encoded directory. + * @return {!promise.Promise.} A promise for the encoded profile. + */ + encode(): webdriver.promise.Promise; +} + +/** + * Configuration options for the FirefoxDriver. + */ +export class Options { + /** + * Sets the profile to use. The profile may be specified as a + * {@link Profile} object or as the path to an existing Firefox profile to use + * as a template. + * + * @param {(string|!Profile)} profile The profile to use. + * @return {!Options} A self reference. + */ + setProfile(profile: string | any): Options; + + /** + * Sets the binary to use. The binary may be specified as the path to a Firefox + * executable, or as a {@link Binary} object. + * + * @param {(string|!Binary)} binary The binary to use. + * @return {!Options} A self reference. + */ + setBinary(binary: string | any): Options; + + /** + * Sets the logging preferences for the new session. + * @param {logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPreferences(prefs: webdriver.logging.Preferences): Options; + + /** + * Sets the proxy to use. + * + * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + /** + * Sets whether to use Mozilla's Marionette to drive the browser. + * + * @see https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver + */ + useMarionette(marionette: any): Options; + + /** + * Converts these options to a {@link capabilities.Capabilities} instance. + * + * @return {!capabilities.Capabilities} A new capabilities object. + */ + toCapabilities(): webdriver.Capabilities; +} + +/** + * @return {string} . + * @throws {Error} + */ +export function findWires(): string; + +/** + * @param {(string|!Binary)} binary . + * @return {!remote.DriverService} . + */ +export function createWiresService(binary: string | any): remote.DriverService; + +/** + * @param {(Profile|string)} profile The profile to prepare. + * @param {number} port The port the FirefoxDriver should listen on. + * @return {!Promise} a promise for the path to the profile directory. + */ +export function prepareProfile(profile: string | any, port: number): any; + +/** + * A WebDriver client for Firefox. + */ +export class Driver extends webdriver.WebDriver { + /** + * @param {(Options|capabilities.Capabilities|Object)=} opt_config The + * configuration options for this driver, specified as either an + * {@link Options} or {@link capabilities.Capabilities}, or as a raw hash + * object. + * @param {promise.ControlFlow=} opt_flow The flow to + * schedule commands through. Defaults to the active flow object. + */ + constructor(opt_config?: Options | webdriver.Capabilities | Object, opt_flow?: webdriver.promise.ControlFlow); + + /** + * This function is a no-op as file detectors are not supported by this + * implementation. + * @override + */ + setFileDetector(): void; +} diff --git a/selenium-webdriver/v2/http.d.ts b/selenium-webdriver/v2/http.d.ts new file mode 100644 index 0000000000..bdb2797406 --- /dev/null +++ b/selenium-webdriver/v2/http.d.ts @@ -0,0 +1,153 @@ +/* tslint:disable */ +import * as webdriver from './index'; + +/** + * Converts a headers map to a HTTP header block string. + * @param {!Map} headers The map to convert. + * @return {string} The headers as a string. + */ +export function headersToString(headers: any): string; + +/** + * Represents a HTTP request message. This class is a 'partial' request and only + * defines the path on the server to send a request to. It is each client's + * responsibility to build the full URL for the final request. + * @final + */ +export class HttpRequest { + /** + * @param {string} method The HTTP method to use for the request. + * @param {string} path The path on the server to send the request to. + * @param {Object=} opt_data This request's non-serialized JSON payload data. + */ + constructor(method: string, path: string, opt_data?: Object); + + /** @override */ + toString(): string; +} + +/** + * Represents a HTTP response message. + * @final + */ +export class HttpResponse { + /** + * @param {number} status The response code. + * @param {!Object} headers The response headers. All header names + * will be converted to lowercase strings for consistent lookups. + * @param {string} body The response body. + */ + constructor(status: number, headers: Object, body: string); + + /** @override */ + toString(): string; +} + + +export function post(path: string): any; +export function del(path: string): any; +export function get(path: string): any; +export function resource(method: string, path: string): any; + +/** + * A basic HTTP client used to send messages to a remote end. + */ +export class HttpClient { + /** + * @param {string} serverUrl URL for the WebDriver server to send commands to. + * @param {http.Agent=} opt_agent The agent to use for each request. + * Defaults to `http.globalAgent`. + * @param {?string=} opt_proxy The proxy to use for the connection to the + * server. Default is to use no proxy. + */ + constructor(serverUrl: string, opt_agent?: any, opt_proxy?: string); + + /** + * Sends a request to the server. The client will automatically follow any + * redirects returned by the server, fulfilling the returned promise with the + * final response. + * + * @param {!HttpRequest} httpRequest The request to send. + * @return {!promise.Promise} A promise that will be fulfilled + * with the server's response. + */ + send(httpRequest: HttpRequest): webdriver.promise.Promise; +} + +/** + * Sends a single HTTP request. + * @param {!Object} options The request options. + * @param {function(!HttpResponse)} onOk The function to call if the + * request succeeds. + * @param {function(!Error)} onError The function to call if the request fails. + * @param {?string=} opt_data The data to send with the request. + * @param {?string=} opt_proxy The proxy server to use for the request. + */ +export function sendRequest(options: Object, onOk: any, onError: any, opt_data?: string, opt_proxy?: string): any; + +/** + * A command executor that communicates with the server using HTTP + JSON. + * + * By default, each instance of this class will use the legacy wire protocol + * from [Selenium project][json]. The executor will automatically switch to the + * [W3C wire protocol][w3c] if the remote end returns a compliant response to + * a new session command. + * + * [json]: https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol + * [w3c]: https://w3c.github.io/webdriver/webdriver-spec.html + * + * @implements {cmd.Executor} + */ +export class Executor { + /** + * @param {!HttpClient} client The client to use for sending requests to the + * server. + */ + constructor(client: HttpClient); + + /** + * Defines a new command for use with this executor. When a command is sent, + * the {@code path} will be preprocessed using the command's parameters; any + * path segments prefixed with ':' will be replaced by the parameter of the + * same name. For example, given '/person/:name' and the parameters + * '{name: 'Bob'}', the final command path will be '/person/Bob'. + * + * @param {string} name The command name. + * @param {string} method The HTTP method to use when sending this command. + * @param {string} path The path to send the command to, relative to + * the WebDriver server's command root and of the form + * '/path/:variable/segment'. + */ + defineCommand(name: string, method: string, path: string): void; + + /** @override */ + execute(command: any): any; +} + +/** + * @param {string} str . + * @return {?} . + */ +export function tryParse(str: string): any; + +/** + * Callback used to parse {@link HttpResponse} objects from a + * {@link HttpClient}. + * @param {!HttpResponse} httpResponse The HTTP response to parse. + * @param {boolean} w3c Whether the response should be processed using the + * W3C wire protocol. + * @return {{value: ?}} The parsed response. + * @throws {WebDriverError} If the HTTP response is an error. + */ +export function parseHttpResponse(httpResponse: HttpResponse, w3c: boolean): any; + +/** + * Builds a fully qualified path using the given set of command parameters. Each + * path segment prefixed with ':' will be replaced by the value of the + * corresponding parameter. All parameters spliced into the path will be + * removed from the parameter map. + * @param {string} path The original resource path. + * @param {!Object<*>} parameters The parameters object to splice into the path. + * @return {string} The modified path. + */ +export function buildPath(path: string, parameters: Object): string; diff --git a/selenium-webdriver/v2/ie.d.ts b/selenium-webdriver/v2/ie.d.ts new file mode 100644 index 0000000000..a9ae4b2c4a --- /dev/null +++ b/selenium-webdriver/v2/ie.d.ts @@ -0,0 +1,206 @@ +/* tslint:disable */ +import * as webdriver from './index'; + +/** + * A WebDriver client for Microsoft's Internet Explorer. + */ +export class Driver extends webdriver.WebDriver { + /** + * @param {(capabilities.Capabilities|Options)=} opt_config The configuration + * options. + * @param {promise.ControlFlow=} opt_flow The control flow to use, + * or {@code null} to use the currently active flow. + */ + constructor(opt_config?: webdriver.Capabilities | Options, opt_flow?: webdriver.promise.ControlFlow); + + /** + * This function is a no-op as file detectors are not supported by this + * implementation. + * @override + */ + setFileDetector(): void; +} + +/** + * Class for managing IEDriver specific options. + */ +export class Options { + constructor(); + + /** + * Extracts the IEDriver specific options from the given capabilities + * object. + * @param {!capabilities.Capabilities} caps The capabilities object. + * @return {!Options} The IEDriver options. + */ + static fromCapabilities(caps: webdriver.Capabilities): Options; + + /** + * Whether to disable the protected mode settings check when the session is + * created. Disbling this setting may lead to significant instability as the + * browser may become unresponsive/hang. Only 'best effort' support is provided + * when using this capability. + * + * For more information, refer to the IEDriver's + * [required system configuration](http://goo.gl/eH0Yi3). + * + * @param {boolean} ignoreSettings Whether to ignore protected mode settings. + * @return {!Options} A self reference. + */ + introduceFlakinessByIgnoringProtectedModeSettings(ignoreSettings: boolean): Options; + + /** + * Indicates whether to skip the check that the browser's zoom level is set to + * 100%. + * + * @param {boolean} ignore Whether to ignore the browser's zoom level settings. + * @return {!Options} A self reference. + */ + ignoreZoomSetting(ignore: boolean): Options; + + /** + * Sets the initial URL loaded when IE starts. This is intended to be used with + * {@link #ignoreProtectedModeSettings} to allow the user to initialize IE in + * the proper Protected Mode zone. Setting this option may cause browser + * instability or flaky and unresponsive code. Only 'best effort' support is + * provided when using this option. + * + * @param {string} url The initial browser URL. + * @return {!Options} A self reference. + */ + initialBrowserUrl(url: string): Options; + + /** + * Configures whether to enable persistent mouse hovering (true by default). + * Persistent hovering is achieved by continuously firing mouse over events at + * the last location the mouse cursor has been moved to. + * + * @param {boolean} enable Whether to enable persistent hovering. + * @return {!Options} A self reference. + */ + enablePersistentHover(enable: boolean): Options; + + /** + * Configures whether the driver should attempt to remove obsolete + * {@linkplain webdriver.WebElement WebElements} from its internal cache on + * page navigation (true by default). Disabling this option will cause the + * driver to run with a larger memory footprint. + * + * @param {boolean} enable Whether to enable element reference cleanup. + * @return {!Options} A self reference. + */ + enableElementCacheCleanup(enable: boolean): Options; + + /** + * Configures whether to require the IE window to have input focus before + * performing any user interactions (i.e. mouse or keyboard events). This + * option is disabled by default, but delivers much more accurate interaction + * events when enabled. + * + * @param {boolean} require Whether to require window focus. + * @return {!Options} A self reference. + */ + requireWindowFocus(require: boolean): Options; + + /** + * Configures the timeout, in milliseconds, that the driver will attempt to + * located and attach to a newly opened instance of Internet Explorer. The + * default is zero, which indicates waiting indefinitely. + * + * @param {number} timeout How long to wait for IE. + * @return {!Options} A self reference. + */ + browserAttachTimeout(timeout: number): Options; + + /** + * Configures whether to launch Internet Explorer using the CreateProcess API. + * If this option is not specified, IE is launched using IELaunchURL, if + * available. For IE 8 and above, this option requires the TabProcGrowth + * registry value to be set to 0. + * + * @param {boolean} force Whether to use the CreateProcess API. + * @return {!Options} A self reference. + */ + forceCreateProcessApi(force: boolean): Options; + + /** + * Specifies command-line switches to use when launching Internet Explorer. + * This is only valid when used with {@link #forceCreateProcessApi}. + * + * @param {...(string|!Array.)} var_args The arguments to add. + * @return {!Options} A self reference. + */ + addArguments(...var_args: string[]): Options; + + /** + * Configures whether proxies should be configured on a per-process basis. If + * not set, setting a {@linkplain #setProxy proxy} will configure the system + * proxy. The default behavior is to use the system proxy. + * + * @param {boolean} enable Whether to enable per-process proxy settings. + * @return {!Options} A self reference. + */ + usePerProcessProxy(enable: boolean): Options; + + /** + * Configures whether to clear the cache, cookies, history, and saved form data + * before starting the browser. _Using this capability will clear session data + * for all running instances of Internet Explorer, including those started + * manually._ + * + * @param {boolean} cleanSession Whether to clear all session data on startup. + * @return {!Options} A self reference. + */ + ensureCleanSession(cleanSession: boolean): Options; + + /** + * Sets the path to the log file the driver should log to. + * @param {string} file The log file path. + * @return {!Options} A self reference. + */ + setLogFile(file: string): Options; + + /** + * Sets the IEDriverServer's logging {@linkplain Level level}. + * @param {Level} level The logging level. + * @return {!Options} A self reference. + */ + setLogLevel(level: webdriver.logging.Level): Options; + + /** + * Sets the IP address of the driver's host adapter. + * @param {string} host The IP address to use. + * @return {!Options} A self reference. + */ + setHost(host: string): Options; + + /** + * Sets the path of the temporary data directory to use. + * @param {string} path The log file path. + * @return {!Options} A self reference. + */ + setExtractPath(path: string): Options; + + /** + * Sets whether the driver should start in silent mode. + * @param {boolean} silent Whether to run in silent mode. + * @return {!Options} A self reference. + */ + silent(silent: boolean): Options; + + /** + * Sets the proxy settings for the new session. + * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + /** + * Converts this options instance to a {@link capabilities.Capabilities} + * object. + * @param {capabilities.Capabilities=} opt_capabilities The capabilities to + * merge these options into, if any. + * @return {!capabilities.Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; +} diff --git a/selenium-webdriver/v2/index.d.ts b/selenium-webdriver/v2/index.d.ts new file mode 100644 index 0000000000..25e9e0f606 --- /dev/null +++ b/selenium-webdriver/v2/index.d.ts @@ -0,0 +1,5050 @@ +// Type definitions for Selenium WebDriverJS 2.53 +// Project: https://github.com/SeleniumHQ/selenium/tree/master/javascript/node/selenium-webdriver +// Definitions by: Bill Armstrong , Yuki Kokubun , Craig Nishina +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 +/* tslint:disable */ + +import * as chrome from './chrome'; +import * as edge from './edge'; +import * as firefox from './firefox'; +import * as ie from './ie'; +import * as opera from './opera'; +import * as safari from './safari'; + +export namespace error { + class IError extends Error { + constructor(opt_error?: string); + + code(): number; + } + + /** + * The base WebDriver error type. This error type is only used directly when a + * more appropriate category is not defined for the offending error. + */ + class WebDriverError extends IError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An attempt was made to select an element that cannot be selected. + */ + class ElementNotSelectableError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An element command could not be completed because the element is not visible + * on the page. + */ + class ElementNotVisibleError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * The arguments passed to a command are either invalid or malformed. + */ + class InvalidArgumentError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An illegal attempt was made to set a cookie under a different domain than + * the current page. + */ + class InvalidCookieDomainError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * The coordinates provided to an interactions operation are invalid. + */ + class InvalidElementCoordinatesError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An element command could not be completed because the element is in an + * invalid state, e.g. attempting to click an element that is no longer attached + * to the document. + */ + class InvalidElementStateError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * Argument was an invalid selector. + */ + class InvalidSelectorError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * Occurs when a command is directed to a session that does not exist. + */ + class NoSuchSessionError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An error occurred while executing JavaScript supplied by the user. + */ + class JavascriptError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * The target for mouse interaction is not in the browser’s viewport and cannot + * be brought into that viewport. + */ + class MoveTargetOutOfBoundsError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An attempt was made to operate on a modal dialog when one was not open. + */ + class NoSuchAlertError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An element could not be located on the page using the given search + * parameters. + */ + class NoSuchElementError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A request to switch to a frame could not be satisfied because the frame + * could not be found. + */ + class NoSuchFrameError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A request to switch to a window could not be satisfied because the window + * could not be found. + */ + class NoSuchWindowError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A script did not complete before its timeout expired. + */ + class ScriptTimeoutError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A new session could not be created. + */ + class SessionNotCreatedError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An element command failed because the referenced element is no longer + * attached to the DOM. + */ + class StaleElementReferenceError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * An operation did not completErrorCodee before its timeout expired. + */ + class TimeoutError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A request to set a cookie’s value could not be satisfied. + */ + class UnableToSetCookieError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A screen capture operation was not possible. + */ + class UnableToCaptureScreenError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A modal dialog was open, blocking this operation. + */ + class UnexpectedAlertOpenError extends WebDriverError { + /** + * @param {string=} opt_error the error message, if any. + * @param {string=} opt_text the text of the open dialog, if available. + */ + constructor(opt_error?: string, opt_text?: string); + + /** + * @return {(string|undefined)} The text displayed with the unhandled alert, + * if available. + */ + getAlertText(): string; + } + + /** + * A command could not be executed because the remote end is not aware of it. + */ + class UnknownCommandError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * The requested command matched a known URL but did not match an method for + * that URL. + */ + class UnknownMethodError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * Reports an unsupport operation. + */ + class UnsupportedOperationError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } +} + +export namespace logging { + + /** + * A hash describing log preferences. + * @typedef {Object.} + */ + class Preferences { + setLevel(type: string, level: Level | string | number): void; + toJSON(): { [key: string]: string }; + } + + interface IType { + /** Logs originating from the browser. */ + BROWSER: string; + /** Logs from a WebDriver client. */ + CLIENT: string; + /** Logs from a WebDriver implementation. */ + DRIVER: string; + /** Logs related to performance. */ + PERFORMANCE: string; + /** Logs from the remote server. */ + SERVER: string; + } + + /** + * Common log types. + * @enum {string} + */ + var Type: IType; + + /** + * Defines a message level that may be used to control logging output. + * + * @final + */ + class Level { + name_: string; + value_: number; + /** + * @param {string} name the level's name. + * @param {number} level the level's numeric value. + */ + constructor(name: string, level: number); + + /** @override */ + toString(): string; + + /** This logger's name. */ + name: string; + + /** The numeric log level. */ + value: number; + + /** + * Indicates no log messages should be recorded. + * @const + */ + static OFF: Level; + /** + * Log messages with a level of `1000` or higher. + * @const + */ + static SEVERE: Level; + /** + * Log messages with a level of `900` or higher. + * @const + */ + static WARNING: Level; + /** + * Log messages with a level of `800` or higher. + * @const + */ + static INFO: Level; + /** + * Log messages with a level of `700` or higher. + * @const + */ + static DEBUG: Level; + /** + * Log messages with a level of `500` or higher. + * @const + */ + static FINE: Level; + /** + * Log messages with a level of `400` or higher. + * @const + */ + static FINER: Level; + /** + * Log messages with a level of `300` or higher. + * @const + */ + static FINEST: Level; + /** + * Indicates all log messages should be recorded. + * @const + */ + static ALL: Level; + } + + /** + * Converts a level name or value to a {@link logging.Level} value. + * If the name/value is not recognized, {@link logging.Level.ALL} + * will be returned. + * @param {(number|string)} nameOrValue The log level name, or value, to + * convert . + * @return {!logging.Level} The converted level. + */ + function getLevel(nameOrValue: string | number): Level; + + interface IEntryJSON { + level: string; + message: string; + timestamp: number; + type: string; + } + + /** + * A single log entry. + */ + class Entry { + /** + * @param {(!logging.Level|string)} level The entry level. + * @param {string} message The log message. + * @param {number=} opt_timestamp The time this entry was generated, in + * milliseconds since 0:00:00, January 1, 1970 UTC. If omitted, the + * current time will be used. + * @param {string=} opt_type The log type, if known. + * @constructor + */ + constructor(level: Level | string | number, message: string, opt_timestamp?: number, opt_type?: string | IType); + + /** @type {!logging.Level} */ + level: Level; + + /** @type {string} */ + message: string; + + /** @type {number} */ + timestamp: number; + + /** @type {string} */ + type: string; + + /** + * @return {{level: string, message: string, timestamp: number, + * type: string}} The JSON representation of this entry. + */ + toJSON(): IEntryJSON; + } + + /** + * An object used to log debugging messages. Loggers use a hierarchical, + * dot-separated naming scheme. For instance, 'foo' is considered the parent of + * the 'foo.bar' and an ancestor of 'foo.bar.baz'. + * + * Each logger may be assigned a {@linkplain #setLevel log level}, which + * controls which level of messages will be reported to the + * {@linkplain #addHandler handlers} attached to this instance. If a log level + * is not explicitly set on a logger, it will inherit its parent. + * + * This class should never be directly instantiated. Instead, users should + * obtain logger references using the {@linkplain ./logging.getLogger() + * getLogger()} function. + * + * @final + */ + class Logger { + /** + * @param {string} name the name of this logger. + * @param {Level=} opt_level the initial level for this logger. + */ + constructor(name: string, opt_level?: Level); + + /** @private {string} */ + name_: string; + /** @private {Level} */ + level_: Level; + /** @private {Logger} */ + parent_: Logger; + /** @private {Set} */ + handlers_: any; + + /** @return {string} the name of this logger. */ + getName(): string; + + /** + * @param {Level} level the new level for this logger, or `null` if the logger + * should inherit its level from its parent logger. + */ + setLevel(level: Level): void; + + /** @return {Level} the log level for this logger. */ + getLevel(): Level; + + /** + * @return {!Level} the effective level for this logger. + */ + getEffectiveLevel(): Level; + + /** + * @param {!Level} level the level to check. + * @return {boolean} whether messages recorded at the given level are loggable + * by this instance. + */ + isLoggable(level: Level): boolean; + + /** + * Adds a handler to this logger. The handler will be invoked for each message + * logged with this instance, or any of its descendants. + * + * @param {function(!Entry)} handler the handler to add. + */ + addHandler(handler: any): void; + + /** + * Removes a handler from this logger. + * + * @param {function(!Entry)} handler the handler to remove. + * @return {boolean} whether a handler was successfully removed. + */ + removeHandler(handler: any): void; + + /** + * Logs a message at the given level. The message may be defined as a string + * or as a function that will return the message. If a function is provided, + * it will only be invoked if this logger's + * {@linkplain #getEffectiveLevel() effective log level} includes the given + * `level`. + * + * @param {!Level} level the level at which to log the message. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + log(level: Level, loggable: string | Function): void; + + /** + * Logs a message at the {@link Level.SEVERE} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + severe(loggable: string | Function): void; + + /** + * Logs a message at the {@link Level.WARNING} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + warning(loggable: string | Function): void; + + /** + * Logs a message at the {@link Level.INFO} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + info(loggable: string | Function): void; + + /** + * Logs a message at the {@link Level.DEBUG} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + debug(loggable: string | Function): void; + + /** + * Logs a message at the {@link Level.FINE} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + fine(loggable: string | Function): void; + + /** + * Logs a message at the {@link Level.FINER} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + finer(loggable: string | Function): void; + + /** + * Logs a message at the {@link Level.FINEST} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + finest(loggable: string | Function): void; + } + + /** + * Maintains a collection of loggers. + * + * @final + */ + class LogManager { + /** + * Retrieves a named logger, creating it in the process. This function will + * implicitly create the requested logger, and any of its parents, if they + * do not yet exist. + * + * @param {string} name the logger's name. + * @return {!Logger} the requested logger. + */ + getLogger(name: string): Logger; + + /** + * Creates a new logger. + * + * @param {string} name the logger's name. + * @param {!Logger} parent the logger's parent. + * @return {!Logger} the new logger. + * @private + */ + createLogger_(name: string, parent: Logger): Logger; + } +} + +export namespace promise { + // region Functions + + /** + * Given an array of promises, will return a promise that will be fulfilled + * with the fulfillment values of the input array's values. If any of the + * input array's promises are rejected, the returned promise will be rejected + * with the same reason. + * + * @param {!Array<(T|!ManagedPromise)>} arr An array of + * promises to wait on. + * @return {!ManagedPromise} A promise that is + * fulfilled with an array containing the fulfilled values of the + * input array, or rejected with the same reason as the first + * rejected value. + * @template T + */ + function all(arr: Array>): Promise; + + /** + * Invokes the appropriate callback function as soon as a promised + * {@code value} is resolved. This function is similar to + * {@link promise.when}, except it does not return a new promise. + * @param {*} value The value to observe. + * @param {Function} callback The function to call when the value is + * resolved successfully. + * @param {Function=} opt_errback The function to call when the value is + * rejected. + */ + function asap(value: any, callback: Function, opt_errback?: Function): void; + + /** + * @return {!promise.ControlFlow} The currently active control flow. + */ + function controlFlow(): ControlFlow; + + /** + * Creates a new control flow. The provided callback will be invoked as the + * first task within the new flow, with the flow as its sole argument. Returns + * a promise that resolves to the callback result. + * @param {function(!ControlFlow)} callback The entry point + * to the newly created flow. + * @return {!ManagedPromise} A promise that resolves to the callback + * result. + */ + function createFlow(callback: (flow: ControlFlow) => R): Promise; + + /** + * Determines whether a {@code value} should be treated as a promise. + * Any object whose 'then' property is a function will be considered a promise. + * + * @param {*} value The value to test. + * @return {boolean} Whether the value is a promise. + */ + function isPromise(value: any): boolean; + + /** + * Tests is a function is a generator. + * @param {!Function} fn The function to test. + * @return {boolean} Whether the function is a generator. + */ + function isGenerator(fn: Function): boolean; + + /** + * Creates a promise that will be resolved at a set time in the future. + * @param {number} ms The amount of time, in milliseconds, to wait before + * resolving the promise. + * @return {!ManagedPromise} The promise. + */ + function delayed(ms: number): Promise; + + /** + * Calls a function for each element in an array, and if the function returns + * true adds the element to a new array. + * + * If the return value of the filter function is a promise, this function + * will wait for it to be fulfilled before determining whether to insert the + * element into the new array. + * + * If the filter function throws or returns a rejected promise, the promise + * returned by this function will be rejected with the same reason. Only the + * first failure will be reported; all subsequent errors will be silently + * ignored. + * + * @param {!(Array|ManagedPromise>)} arr The + * array to iterator over, or a promise that will resolve to said array. + * @param {function(this: SELF, TYPE, number, !Array): ( + * boolean|ManagedPromise)} fn The function + * to call for each element in the array. + * @param {SELF=} opt_self The object to be used as the value of 'this' within + * {@code fn}. + * @template TYPE, SELF + */ + function filter(arr: T[] | Promise, fn: (element: T, type: any, index: number, array: T[]) => any, opt_self?: any): Promise; + + /** + * Creates a new deferred object. + * @return {!promise.Deferred} The new deferred object. + */ + function defer(): Deferred; + + /** + * Creates a promise that has been resolved with the given value. + * @param {T=} opt_value The resolved value. + * @return {!ManagedPromise} The resolved promise. + * @template T + */ + function fulfilled(opt_value?: T): Promise; + + /** + * Calls a function for each element in an array and inserts the result into a + * new array, which is used as the fulfillment value of the promise returned + * by this function. + * + * If the return value of the mapping function is a promise, this function + * will wait for it to be fulfilled before inserting it into the new array. + * + * If the mapping function throws or returns a rejected promise, the + * promise returned by this function will be rejected with the same reason. + * Only the first failure will be reported; all subsequent errors will be + * silently ignored. + * + * @param {!(Array|ManagedPromise>)} arr The + * array to iterator over, or a promise that will resolve to said array. + * @param {function(this: SELF, TYPE, number, !Array): ?} fn The + * function to call for each element in the array. This function should + * expect three arguments (the element, the index, and the array itself. + * @param {SELF=} opt_self The object to be used as the value of 'this' within + * {@code fn}. + * @template TYPE, SELF + */ + function map(arr: T[] | Promise, fn: (self: any, type: any, index: number, array: T[]) => any, opt_self?: any): Promise; + + /** + * Creates a promise that has been rejected with the given reason. + * @param {*=} opt_reason The rejection reason; may be any value, but is + * usually an Error or a string. + * @return {!ManagedPromise} The rejected promise. + * @template T + */ + function rejected(opt_reason?: any): Promise; + + /** + * Wraps a function that expects a node-style callback as its final + * argument. This callback expects two arguments: an error value (which will be + * null if the call succeeded), and the success value as the second argument. + * The callback will the resolve or reject the returned promise, based on its + * arguments. + * @param {!Function} fn The function to wrap. + * @param {...?} var_args The arguments to apply to the function, excluding the + * final callback. + * @return {!ManagedPromise} A promise that will be resolved with the + * result of the provided function's callback. + */ + function checkedNodeCall(fn: Function, ...var_args: any[]): Promise; + + /** + * Consumes a {@code GeneratorFunction}. Each time the generator yields a + * promise, this function will wait for it to be fulfilled before feeding the + * fulfilled value back into {@code next}. Likewise, if a yielded promise is + * rejected, the rejection error will be passed to {@code throw}. + * + * __Example 1:__ the Fibonacci Sequence. + * + * promise.consume(function* fibonacci() { + * var n1 = 1, n2 = 1; + * for (var i = 0; i < 4; ++i) { + * var tmp = yield n1 + n2; + * n1 = n2; + * n2 = tmp; + * } + * return n1 + n2; + * }).then(function(result) { + * console.log(result); // 13 + * }); + * + * __Example 2:__ a generator that throws. + * + * promise.consume(function* () { + * yield promise.delayed(250).then(function() { + * throw Error('boom'); + * }); + * }).catch(function(e) { + * console.log(e.toString()); // Error: boom + * }); + * + * @param {!Function} generatorFn The generator function to execute. + * @param {Object=} opt_self The object to use as 'this' when invoking the + * initial generator. + * @param {...*} var_args Any arguments to pass to the initial generator. + * @return {!ManagedPromise} A promise that will resolve to the + * generator's final result. + * @throws {TypeError} If the given function is not a generator. + */ + function consume(generatorFn: Function, opt_self?: any, ...var_args: any[]): Promise; + + /** + * Registers an observer on a promised {@code value}, returning a new promise + * that will be resolved when the value is. If {@code value} is not a promise, + * then the return promise will be immediately resolved. + * @param {*} value The value to observe. + * @param {Function=} opt_callback The function to call when the value is + * resolved successfully. + * @param {Function=} opt_errback The function to call when the value is + * rejected. + * @return {!ManagedPromise} A new promise. + */ + function when(value: T | Promise, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): Promise; + + /** + * Returns a promise that will be resolved with the input value in a + * fully-resolved state. If the value is an array, each element will be fully + * resolved. Likewise, if the value is an object, all keys will be fully + * resolved. In both cases, all nested arrays and objects will also be + * fully resolved. All fields are resolved in place; the returned promise will + * resolve on {@code value} and not a copy. + * + * Warning: This function makes no checks against objects that contain + * cyclical references: + * + * var value = {}; + * value['self'] = value; + * promise.fullyResolved(value); // Stack overflow. + * + * @param {*} value The value to fully resolve. + * @return {!ManagedPromise} A promise for a fully resolved version + * of the input value. + */ + function fullyResolved(value: any): Promise; + + /** + * Changes the default flow to use when no others are active. + * @param {!ControlFlow} flow The new default flow. + * @throws {Error} If the default flow is not currently active. + */ + function setDefaultFlow(flow: ControlFlow): void; + + // endregion + + /** + * Error used when the computation of a promise is cancelled. + */ + class CancellationError extends Error { + /** + * @param {string=} opt_msg The cancellation message. + */ + constructor(opt_msg?: string); + } + + interface IThenable { + /** + * Cancels the computation of this promise's value, rejecting the promise in + * the process. This method is a no-op if the promise has already been + * resolved. + * + * @param {(string|Error)=} opt_reason The reason this promise is being + * cancelled. This value will be wrapped in a {@link CancellationError}. + */ + cancel(opt_reason?: string | Error): void; + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + /** + * Registers listeners for when this instance is resolved. + * + * @param {?(function(T): (R|IThenable))=} opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param {?(function(*): (R|IThenable))=} opt_errback + * The function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + then(opt_callback?: (value: T) => R | IThenable, opt_errback?: (error: any) => any): Promise; + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + * + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } + * + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); + * + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + catch(errback: Function): Promise; + } + + /** + * Thenable is a promise-like object with a {@code then} method which may be + * used to schedule callbacks on a promised value. + * + * @interface + * @template T + */ + class Thenable implements IThenable { + /** + * Cancels the computation of this promise's value, rejecting the promise in + * the process. This method is a no-op if the promise has already been + * resolved. + * + * @param {(string|Error)=} opt_reason The reason this promise is being + * cancelled. This value will be wrapped in a {@link CancellationError}. + */ + cancel(opt_reason?: string | Error): void; + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + /** + * Registers listeners for when this instance is resolved. + * + * @param {?(function(T): (R|IThenable))=} opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param {?(function(*): (R|IThenable))=} opt_errback + * The function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + then(opt_callback?: (value: T) => R | IThenable, opt_errback?: (error: any) => R | IThenable): Promise; + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + * + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } + * + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); + * + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + catch(errback: Function): Promise; + + /** + * Registers a listener to invoke when this promise is resolved, regardless + * of whether the promise's value was successfully computed. This function + * is synonymous with the {@code finally} clause in a synchronous API: + * + * // Synchronous API: + * try { + * doSynchronousWork(); + * } finally { + * cleanUp(); + * } + * + * // Asynchronous promise API: + * doAsynchronousWork().finally(cleanUp); + * + * __Note:__ similar to the {@code finally} clause, if the registered + * callback returns a rejected promise or throws an error, it will silently + * replace the rejection error (if any) from this promise: + * + * try { + * throw Error('one'); + * } finally { + * throw Error('two'); // Hides Error: one + * } + * + * promise.rejected(Error('one')) + * .finally(function() { + * throw Error('two'); // Hides Error: one + * }); + * + * @param {function(): (R|IThenable)} callback The function to call when + * this promise is resolved. + * @return {!ManagedPromise} A promise that will be fulfilled + * with the callback result. + * @template R + */ + finally(callback: Function): Promise; + + /** + * Adds a property to a class prototype to allow runtime checks of whether + * instances of that class implement the Thenable interface. This function + * will also ensure the prototype's {@code then} function is exported from + * compiled code. + * @param {function(new: Thenable, ...?)} ctor The + * constructor whose prototype to modify. + */ + static addImplementation(ctor: Function): void; + + /** + * Checks if an object has been tagged for implementing the Thenable + * interface as defined by {@link Thenable.addImplementation}. + * @param {*} object The object to test. + * @return {boolean} Whether the object is an implementation of the Thenable + * interface. + */ + static isImplementation(object: any): boolean; + } + + interface IFulfilledCallback { + (value: T | IThenable | Thenable | undefined): void; + } + + interface IRejectedCallback { + (reason: any): void; + } + + /** + * Represents the eventual value of a completed operation. Each promise may be + * in one of three states: pending, fulfilled, or rejected. Each promise starts + * in the pending state and may make a single transition to either a + * fulfilled or rejected state, at which point the promise is considered + * resolved. + * + * @implements {promise.Thenable} + * @template T + * @see http://promises-aplus.github.io/promises-spec/ + */ + class Promise implements IThenable { + /** + * @param {function( + * function((T|IThenable|Thenable)=), + * function(*=))} resolver + * Function that is invoked immediately to begin computation of this + * promise's value. The function should accept a pair of callback + * functions, one for fulfilling the promise and another for rejecting it. + * @param {ControlFlow=} opt_flow The control flow + * this instance was created under. Defaults to the currently active flow. + */ + constructor(resolver: (resolve: IFulfilledCallback, reject: IRejectedCallback) => void, opt_flow?: ControlFlow); + + // region Methods + + /** + * Cancels the computation of this promise's value, rejecting the promise in the + * process. + * @param {*} reason The reason this promise is being cancelled. If not an + * {@code Error}, one will be created using the value's string + * representation. + */ + cancel(opt_reason?: string | Error): void; + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + /** + * Registers listeners for when this instance is resolved. This function most + * overridden by subtypes. + * + * @param opt_callback The function to call if this promise is + * successfully resolved. The function should expect a single argument: the + * promise's resolved value. + * @param opt_errback The function to call if this promise is + * rejected. The function should expect a single argument: the rejection + * reason. + * @return A new promise which will be resolved + * with the result of the invoked callback. + */ + then(opt_callback?: (value: T) => IThenable | R, opt_errback?: (error: any) => any): Promise; + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + *

+     *   // Synchronous API:
+     *   try {
+     *     doSynchronousWork();
+     *   } catch (ex) {
+     *     console.error(ex);
+     *   }
+     *
+     *   // Asynchronous promise API:
+     *   doAsynchronousWork().thenCatch(function(ex) {
+     *     console.error(ex);
+     *   });
+     * 
+ * + * @param {function(*): (R|promise.Promise.)} errback The function + * to call if this promise is rejected. The function should expect a single + * argument: the rejection reason. + * @return {!promise.Promise.} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + thenCatch(errback: (error: any) => any): Promise; + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + * + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } + * + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); + * + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + catch(errback: Function): Promise; + + + /** + * Registers a listener to invoke when this promise is resolved, regardless + * of whether the promise's value was successfully computed. This function + * is synonymous with the {@code finally} clause in a synchronous API: + *

+     *   // Synchronous API:
+     *   try {
+     *     doSynchronousWork();
+     *   } finally {
+     *     cleanUp();
+     *   }
+     *
+     *   // Asynchronous promise API:
+     *   doAsynchronousWork().thenFinally(cleanUp);
+     * 
+ * + * Note: similar to the {@code finally} clause, if the registered + * callback returns a rejected promise or throws an error, it will silently + * replace the rejection error (if any) from this promise: + *

+     *   try {
+     *     throw Error('one');
+     *   } finally {
+     *     throw Error('two');  // Hides Error: one
+     *   }
+     *
+     *   promise.rejected(Error('one'))
+     *       .thenFinally(function() {
+     *         throw Error('two');  // Hides Error: one
+     *       });
+     * 
+ * + * + * @param {function(): (R|promise.Promise.)} callback The function + * to call when this promise is resolved. + * @return {!promise.Promise.} A promise that will be fulfilled + * with the callback result. + * @template R + */ + thenFinally(callback: Function): Promise; + + // endregion + } + + /** + * Represents a value that will be resolved at some point in the future. This + * class represents the protected 'producer' half of a Promise - each Deferred + * has a {@code promise} property that may be returned to consumers for + * registering callbacks, reserving the ability to resolve the deferred to the + * producer. + * + *

If this Deferred is rejected and there are no listeners registered before + * the next turn of the event loop, the rejection will be passed to the + * {@link promise.ControlFlow} as an unhandled failure. + * + *

If this Deferred is cancelled, the cancellation reason will be forward to + * the Deferred's canceller function (if provided). The canceller may return a + * truth-y value to override the reason provided for rejection. + * + * @extends {promise.Promise} + */ + class Deferred extends Promise { + // region Constructors + + /** + * + * @param {promise.ControlFlow=} opt_flow The control flow + * this instance was created under. This should only be provided during + * unit tests. + * @constructor + */ + constructor(opt_flow?: ControlFlow); + + // endregion + + static State_: { + BLOCKED: number; + PENDING: number; + REJECTED: number; + RESOLVED: number; + }; + + // region Properties + + /** + * The consumer promise for this instance. Provides protected access to the + * callback registering functions. + * @type {!promise.Promise} + */ + promise: Promise; + + // endregion + + // region Methods + + /** + * Rejects this promise. If the error is itself a promise, this instance will + * be chained to it and be rejected with the error's resolved value. + * @param {*=} opt_error The rejection reason, typically either a + * {@code Error} or a {@code string}. + */ + reject(opt_error?: any): void; + errback(opt_error?: any): void; + + /** + * Resolves this promise with the given value. If the value is itself a + * promise and not a reference to this deferred, this instance will wait for + * it before resolving. + * @param {*=} opt_value The resolved value. + */ + fulfill(opt_value?: T): void; + + /** + * Removes all of the listeners previously registered on this deferred. + * @throws {Error} If this deferred has already been resolved. + */ + removeAll(): void; + + // endregion + } + + interface IControlFlowTimer { + clearInterval: (ms: number) => void; + clearTimeout: (ms: number) => void; + setInterval: (fn: Function, ms: number) => number; + setTimeout: (fn: Function, ms: number) => number; + } + + interface IEventType { + /** Emitted when all tasks have been successfully executed. */ + IDLE: string; + + /** Emitted when a ControlFlow has been reset. */ + RESET: string; + + /** Emitted whenever a new task has been scheduled. */ + SCHEDULE_TASK: string; + + /** + * Emitted whenever a control flow aborts due to an unhandled promise + * rejection. This event will be emitted along with the offending rejection + * reason. Upon emitting this event, the control flow will empty its task + * queue and revert to its initial state. + */ + UNCAUGHT_EXCEPTION: string; + } + + /** + * Handles the execution of scheduled tasks, each of which may be an + * asynchronous operation. The control flow will ensure tasks are executed in + * the ordered scheduled, starting each task only once those before it have + * completed. + * + * Each task scheduled within this flow may return a + * {@link promise.Promise} to indicate it is an asynchronous + * operation. The ControlFlow will wait for such promises to be resolved before + * marking the task as completed. + * + * Tasks and each callback registered on a {@link promise.Promise} + * will be run in their own ControlFlow frame. Any tasks scheduled within a + * frame will take priority over previously scheduled tasks. Furthermore, if any + * of the tasks in the frame fail, the remainder of the tasks in that frame will + * be discarded and the failure will be propagated to the user through the + * callback/task's promised result. + * + * Each time a ControlFlow empties its task queue, it will fire an + * {@link promise.ControlFlow.EventType.IDLE IDLE} event. Conversely, + * whenever the flow terminates due to an unhandled error, it will remove all + * remaining tasks in its queue and fire an + * {@link promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION + * UNCAUGHT_EXCEPTION} event. If there are no listeners registered with the + * flow, the error will be rethrown to the global error handler. + * + * @extends {EventEmitter} + * @final + */ + class ControlFlow extends EventEmitter { + /** + * @constructor + */ + constructor(); + + /** + * Events that may be emitted by an {@link promise.ControlFlow}. + * @enum {string} + */ + static EventType: IEventType; + + /** + * Returns a string representation of this control flow, which is its current + * {@link #getSchedule() schedule}, sans task stack traces. + * @return {string} The string representation of this contorl flow. + * @override + */ + toString(): string; + + /** + * Resets this instance, clearing its queue and removing all event listeners. + */ + reset(): void; + + /** + * Generates an annotated string describing the internal state of this control + * flow, including the currently executing as well as pending tasks. If + * {@code opt_includeStackTraces === true}, the string will include the + * stack trace from when each task was scheduled. + * @param {string=} opt_includeStackTraces Whether to include the stack traces + * from when each task was scheduled. Defaults to false. + * @return {string} String representation of this flow's internal state. + */ + getSchedule(opt_includeStackTraces?: boolean): string; + + /** + * Schedules a task for execution. If there is nothing currently in the + * queue, the task will be executed in the next turn of the event loop. If + * the task function is a generator, the task will be executed using + * {@link promise.consume}. + * + * @param {function(): (T|promise.Promise)} fn The function to + * call to start the task. If the function returns a + * {@link promise.Promise}, this instance will wait for it to be + * resolved before starting the next task. + * @param {string=} opt_description A description of the task. + * @return {!promise.Promise} A promise that will be resolved + * with the result of the action. + * @template T + */ + execute(fn: () => (T | Promise), opt_description?: string): Promise; + + /** + * Inserts a {@code setTimeout} into the command queue. This is equivalent to + * a thread sleep in a synchronous programming language. + * + * @param {number} ms The timeout delay, in milliseconds. + * @param {string=} opt_description A description to accompany the timeout. + * @return {!promise.Promise} A promise that will be resolved with + * the result of the action. + */ + timeout(ms: number, opt_description?: string): Promise; + + /** + * Schedules a task that shall wait for a condition to hold. Each condition + * function may return any value, but it will always be evaluated as a boolean. + * + * Condition functions may schedule sub-tasks with this instance, however, + * their execution time will be factored into whether a wait has timed out. + * + * In the event a condition returns a Promise, the polling loop will wait for + * it to be resolved before evaluating whether the condition has been satisfied. + * The resolution time for a promise is factored into whether a wait has timed + * out. + * + * If the condition function throws, or returns a rejected promise, the + * wait task will fail. + * + * If the condition is defined as a promise, the flow will wait for it to + * settle. If the timeout expires before the promise settles, the promise + * returned by this function will be rejected. + * + * If this function is invoked with `timeout === 0`, or the timeout is omitted, + * the flow will wait indefinitely for the condition to be satisfied. + * + * @param {(!promise.Promise|function())} condition The condition to poll, + * or a promise to wait on. + * @param {number=} opt_timeout How long to wait, in milliseconds, for the + * condition to hold before timing out. If omitted, the flow will wait + * indefinitely. + * @param {string=} opt_message An optional error message to include if the + * wait times out; defaults to the empty string. + * @return {!promise.Promise} A promise that will be fulfilled + * when the condition has been satisified. The promise shall be rejected if + * the wait times out waiting for the condition. + * @throws {TypeError} If condition is not a function or promise or if timeout + * is not a number >= 0. + * @template T + */ + wait(condition: Promise | Function, opt_timeout?: number, opt_message?: string): Promise; + } +} + +export namespace until { + /** + * Defines a condition to + */ + class Condition { + /** + * @param {string} message A descriptive error message. Should complete the + * sentence 'Waiting [...]' + * @param {function(!WebDriver): OUT} fn The condition function to + * evaluate on each iteration of the wait loop. + * @constructor + */ + constructor(message: string, fn: (webdriver: WebDriver) => any); + + /** @return {string} A description of this condition. */ + description(): string; + + /** @type {function(!WebDriver): OUT} */ + fn(webdriver: WebDriver): any; + } + + /** + * Creates a condition that will wait until the input driver is able to switch + * to the designated frame. The target frame may be specified as + * + * 1. a numeric index into + * [window.frames](https://developer.mozilla.org/en-US/docs/Web/API/Window.frames) + * for the currently selected frame. + * 2. a {@link ./WebElement}, which must reference a FRAME or IFRAME + * element on the current page. + * 3. a locator which may be used to first locate a FRAME or IFRAME on the + * current page before attempting to switch to it. + * + * Upon successful resolution of this condition, the driver will be left + * focused on the new frame. + * + * @param {!(number|./WebElement|By| + * function(!./WebDriver): !./WebElement)} frame + * The frame identifier. + * @return {!Condition} A new condition. + */ + function ableToSwitchToFrame(frame: number | WebElement | By | ((webdriver: WebDriver) => WebElement)): Condition; + + /** + * Creates a condition that waits for an alert to be opened. Upon success, the + * returned promise will be fulfilled with the handle for the opened alert. + * + * @return {!Condition} The new condition. + */ + function alertIsPresent(): Condition; + + /** + * Creates a condition that will wait for the given element to be disabled. + * + * @param {!WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see WebDriver#isEnabled + */ + function elementIsDisabled(element: WebElement): Condition; + + /** + * Creates a condition that will wait for the given element to be enabled. + * + * @param {!WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see WebDriver#isEnabled + */ + function elementIsEnabled(element: WebElement): Condition; + + /** + * Creates a condition that will wait for the given element to be deselected. + * + * @param {!WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see WebDriver#isSelected + */ + function elementIsNotSelected(element: WebElement): Condition; + + /** + * Creates a condition that will wait for the given element to be in the DOM, + * yet not visible to the user. + * + * @param {!WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see WebDriver#isDisplayed + */ + function elementIsNotVisible(element: WebElement): Condition; + + /** + * Creates a condition that will wait for the given element to be selected. + * @param {!WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see WebDriver#isSelected + */ + function elementIsSelected(element: WebElement): Condition; + + /** + * Creates a condition that will wait for the given element to become visible. + * + * @param {!WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see WebDriver#isDisplayed + */ + function elementIsVisible(element: WebElement): Condition; + + /** + * Creates a condition that will loop until an element is + * {@link ./WebDriver#findElement found} with the given locator. + * + * @param {!(By|Function)} locator The locator to use. + * @return {!until.Condition.} The new condition. + */ + function elementLocated(locator: By | Function): Condition; + + /** + * Creates a condition that will wait for the given element's + * {@link WebDriver#getText visible text} to contain the given + * substring. + * + * @param {!WebElement} element The element to test. + * @param {string} substr The substring to search for. + * @return {!until.Condition.} The new condition. + * @see WebDriver#getText + */ + function elementTextContains(element: WebElement, substr: string): Condition; + + /** + * Creates a condition that will wait for the given element's + * {@link WebDriver#getText visible text} to match the given + * {@code text} exactly. + * + * @param {!WebElement} element The element to test. + * @param {string} text The expected text. + * @return {!until.Condition.} The new condition. + * @see WebDriver#getText + */ + function elementTextIs(element: WebElement, text: string): Condition; + + /** + * Creates a condition that will wait for the given element's + * {@link WebDriver#getText visible text} to match a regular + * expression. + * + * @param {!WebElement} element The element to test. + * @param {!RegExp} regex The regular expression to test against. + * @return {!until.Condition} The new condition. + * @see WebDriver#getText + */ + function elementTextMatches(element: WebElement, regex: RegExp): Condition; + + /** + * Creates a condition that will loop until at least one element is + * {@link WebDriver#findElement found} with the given locator. + * + * @param {!(Locator|By.Hash|Function)} locator The locator + * to use. + * @return {!until.Condition.>} The new + * condition. + */ + function elementsLocated(locator: By | Function): Condition; + + /** + * Creates a condition that will wait for the given element to become stale. An + * element is considered stale once it is removed from the DOM, or a new page + * has loaded. + * + * @param {!WebElement} element The element that should become stale. + * @return {!until.Condition} The new condition. + */ + function stalenessOf(element: WebElement): Condition; + + /** + * Creates a condition that will wait for the current page's title to contain + * the given substring. + * + * @param {string} substr The substring that should be present in the page + * title. + * @return {!until.Condition.} The new condition. + */ + function titleContains(substr: string): Condition; + + /** + * Creates a condition that will wait for the current page's title to match the + * given value. + * + * @param {string} title The expected page title. + * @return {!until.Condition} The new condition. + */ + function titleIs(title: string): Condition; + + /** + * Creates a condition that will wait for the current page's title to match the + * given regular expression. + * + * @param {!RegExp} regex The regular expression to test against. + * @return {!until.Condition.} The new condition. + */ + function titleMatches(regex: RegExp): Condition; +} + +interface ILocation { + x: number; + y: number; +} + +interface ISize { + width: number; + height: number; +} + +interface IButton { + LEFT: string; + MIDDLE: string; + RIGHT: string; +} + +/** + * Representations of pressable keys that aren't text. These are stored in + * the Unicode PUA (Private Use Area) code points, 0xE000-0xF8FF. Refer to + * http://www.google.com.au/search?&q=unicode+pua&btnG=Search + * + * @enum {string} + */ +export var Button: IButton; + +interface IKey { + NULL: string; + CANCEL: string; // ^break + HELP: string; + BACK_SPACE: string; + TAB: string; + CLEAR: string; + RETURN: string; + ENTER: string; + SHIFT: string; + CONTROL: string; + ALT: string; + PAUSE: string; + ESCAPE: string; + SPACE: string; + PAGE_UP: string; + PAGE_DOWN: string; + END: string; + HOME: string; + ARROW_LEFT: string; + LEFT: string; + ARROW_UP: string; + UP: string; + ARROW_RIGHT: string; + RIGHT: string; + ARROW_DOWN: string; + DOWN: string; + INSERT: string; + DELETE: string; + SEMICOLON: string; + EQUALS: string; + + NUMPAD0: string; // number pad keys + NUMPAD1: string; + NUMPAD2: string; + NUMPAD3: string; + NUMPAD4: string; + NUMPAD5: string; + NUMPAD6: string; + NUMPAD7: string; + NUMPAD8: string; + NUMPAD9: string; + MULTIPLY: string; + ADD: string; + SEPARATOR: string; + SUBTRACT: string; + DECIMAL: string; + DIVIDE: string; + + F1: string; // function keys + F2: string; + F3: string; + F4: string; + F5: string; + F6: string; + F7: string; + F8: string; + F9: string; + F10: string; + F11: string; + F12: string; + + COMMAND: string; // Apple command key + META: string; // alias for Windows key + + /** + * Simulate pressing many keys at once in a 'chord'. Takes a sequence of + * keys or strings, appends each of the values to a string, + * and adds the chord termination key ({@link Key.NULL}) and returns + * the resulting string. + * + * Note: when the low-level webdriver key handlers see Keys.NULL, active + * modifier keys (CTRL/ALT/SHIFT/etc) release via a keyup event. + * + * @param {...string} var_args The key sequence to concatenate. + * @return {string} The null-terminated key sequence. + */ + chord: (...var_args: Array) => string; +} + +/** + * Representations of pressable keys that aren't text. These are stored in + * the Unicode PUA (Private Use Area) code points, 0xE000-0xF8FF. Refer to + * http://www.google.com.au/search?&q=unicode+pua&btnG=Search + * + * @enum {string} + */ +export var Key: IKey; + +/** + * Class for defining sequences of complex user interactions. Each sequence + * will not be executed until {@link #perform} is called. + * + * Example: + * + * new ActionSequence(driver). + * keyDown(Key.SHIFT). + * click(element1). + * click(element2). + * dragAndDrop(element3, element4). + * keyUp(Key.SHIFT). + * perform(); + * + */ +export class ActionSequence { + + // region Constructors + + /** + * @param {!WebDriver} driver The driver instance to use. + * @constructor + */ + constructor(driver: WebDriver); + + // endregion + + // region Methods + + /** + * Executes this action sequence. + * @return {!promise.Promise} A promise that will be resolved once + * this sequence has completed. + */ + perform(): promise.Promise; + + /** + * Moves the mouse. The location to move to may be specified in terms of the + * mouse's current location, an offset relative to the top-left corner of an + * element, or an element (in which case the middle of the element is used). + * + * @param {(!./WebElement|{x: number, y: number})} location The + * location to drag to, as either another WebElement or an offset in + * pixels. + * @param {{x: number, y: number}=} opt_offset If the target {@code location} + * is defined as a {@link ./WebElement}, this parameter defines + * an offset within that element. The offset should be specified in pixels + * relative to the top-left corner of the element's bounding box. If + * omitted, the element's center will be used as the target offset. + * @return {!ActionSequence} A self reference. + */ + mouseMove(location: WebElement | ILocation, opt_offset?: ILocation): ActionSequence; + + /** + * Presses a mouse button. The mouse button will not be released until + * {@link #mouseUp} is called, regardless of whether that call is made in this + * sequence or another. The behavior for out-of-order events (e.g. mouseDown, + * click) is undefined. + * + * If an element is provided, the mouse will first be moved to the center + * of that element. This is equivalent to: + * + * sequence.mouseMove(element).mouseDown() + * + * Warning: this method currently only supports the left mouse button. See + * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). + * + * @param {(./WebElement|input.Button)=} opt_elementOrButton Either + * the element to interact with or the button to click with. + * Defaults to {@link input.Button.LEFT} if neither an element nor + * button is specified. + * @param {input.Button=} opt_button The button to use. Defaults to + * {@link input.Button.LEFT}. Ignored if a button is provided as the + * first argument. + * @return {!ActionSequence} A self reference. + */ + mouseDown(opt_elementOrButton?: WebElement | string, opt_button?: string): ActionSequence; + + /** + * Releases a mouse button. Behavior is undefined for calling this function + * without a previous call to {@link #mouseDown}. + * + * If an element is provided, the mouse will first be moved to the center + * of that element. This is equivalent to: + * + * sequence.mouseMove(element).mouseUp() + * + * Warning: this method currently only supports the left mouse button. See + * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). + * + * @param {(./WebElement|input.Button)=} opt_elementOrButton Either + * the element to interact with or the button to click with. + * Defaults to {@link input.Button.LEFT} if neither an element nor + * button is specified. + * @param {input.Button=} opt_button The button to use. Defaults to + * {@link input.Button.LEFT}. Ignored if a button is provided as the + * first argument. + * @return {!ActionSequence} A self reference. + */ + mouseUp(opt_elementOrButton?: WebElement | string, opt_button?: string): ActionSequence; + + /** + * Convenience function for performing a 'drag and drop' manuever. The target + * element may be moved to the location of another element, or by an offset (in + * pixels). + * + * @param {!./WebElement} element The element to drag. + * @param {(!./WebElement|{x: number, y: number})} location The + * location to drag to, either as another WebElement or an offset in + * pixels. + * @return {!ActionSequence} A self reference. + */ + dragAndDrop(element: WebElement, location: WebElement | ILocation): ActionSequence; + + /** + * Clicks a mouse button. + * + * If an element is provided, the mouse will first be moved to the center + * of that element. This is equivalent to: + * + * sequence.mouseMove(element).click() + * + * @param {(./WebElement|input.Button)=} opt_elementOrButton Either + * the element to interact with or the button to click with. + * Defaults to {@link input.Button.LEFT} if neither an element nor + * button is specified. + * @param {input.Button=} opt_button The button to use. Defaults to + * {@link input.Button.LEFT}. Ignored if a button is provided as the + * first argument. + * @return {!ActionSequence} A self reference. + */ + click(opt_elementOrButton?: WebElement | string, opt_button?: string): ActionSequence; + + /** + * Double-clicks a mouse button. + * + * If an element is provided, the mouse will first be moved to the center of + * that element. This is equivalent to: + * + * sequence.mouseMove(element).doubleClick() + * + * Warning: this method currently only supports the left mouse button. See + * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). + * + * @param {(./WebElement|input.Button)=} opt_elementOrButton Either + * the element to interact with or the button to click with. + * Defaults to {@link input.Button.LEFT} if neither an element nor + * button is specified. + * @param {input.Button=} opt_button The button to use. Defaults to + * {@link input.Button.LEFT}. Ignored if a button is provided as the + * first argument. + * @return {!ActionSequence} A self reference. + */ + doubleClick(opt_elementOrButton?: WebElement | string, opt_button?: string): ActionSequence; + + /** + * Performs a modifier key press. The modifier key is not released + * until {@link #keyUp} or {@link #sendKeys} is called. The key press will be + * targetted at the currently focused element. + * @param {!Key} key The modifier key to push. Must be one of + * {ALT, CONTROL, SHIFT, COMMAND, META}. + * @return {!ActionSequence} A self reference. + * @throws {Error} If the key is not a valid modifier key. + */ + keyDown(key: string): ActionSequence; + + /** + * Performs a modifier key release. The release is targetted at the currently + * focused element. + * @param {!Key} key The modifier key to release. Must be one of + * {ALT, CONTROL, SHIFT, COMMAND, META}. + * @return {!ActionSequence} A self reference. + * @throws {Error} If the key is not a valid modifier key. + */ + keyUp(key: string): ActionSequence; + + /** + * Simulates typing multiple keys. Each modifier key encountered in the + * sequence will not be released until it is encountered again. All key events + * will be targeted at the currently focused element. + * + * @param {...(string|!input.Key|!Array<(string|!input.Key)>)} var_args + * The keys to type. + * @return {!ActionSequence} A self reference. + * @throws {Error} If the key is not a valid modifier key. + */ + sendKeys(...var_args: Array>): ActionSequence; + + // endregion +} + + +/** + * Class for defining sequences of user touch interactions. Each sequence + * will not be executed until {@link #perform} is called. + * + * Example: + * + * new TouchSequence(driver). + * tapAndHold({x: 0, y: 0}). + * move({x: 3, y: 4}). + * release({x: 10, y: 10}). + * perform(); + */ +export class TouchSequence { + /* + * @param {!WebDriver} driver The driver instance to use. + * @constructor + */ + constructor(driver: WebDriver); + + + /** + * Executes this action sequence. + * @return {!promise.Promise} A promise that will be resolved once + * this sequence has completed. + */ + perform(): promise.Promise; + + + /** + * Taps an element. + * + * @param {!WebElement} elem The element to tap. + * @return {!TouchSequence} A self reference. + */ + tap(elem: WebElement): TouchSequence; + + + /** + * Double taps an element. + * + * @param {!WebElement} elem The element to double tap. + * @return {!TouchSequence} A self reference. + */ + doubleTap(elem: WebElement): TouchSequence; + + + /** + * Long press on an element. + * + * @param {!WebElement} elem The element to long press. + * @return {!TouchSequence} A self reference. + */ + longPress(elem: WebElement): TouchSequence; + + + /** + * Touch down at the given location. + * + * @param {{ x: number, y: number }} location The location to touch down at. + * @return {!TouchSequence} A self reference. + */ + tapAndHold(location: ILocation): TouchSequence; + + + /** + * Move a held {@linkplain #tapAndHold touch} to the specified location. + * + * @param {{x: number, y: number}} location The location to move to. + * @return {!TouchSequence} A self reference. + */ + move(location: ILocation): TouchSequence; + + + /** + * Release a held {@linkplain #tapAndHold touch} at the specified location. + * + * @param {{x: number, y: number}} location The location to release at. + * @return {!TouchSequence} A self reference. + */ + release(location: ILocation): TouchSequence; + + + /** + * Scrolls the touch screen by the given offset. + * + * @param {{x: number, y: number}} offset The offset to scroll to. + * @return {!TouchSequence} A self reference. + */ + scroll(offset: IOffset): TouchSequence; + + /** + * Scrolls the touch screen, starting on `elem` and moving by the specified + * offset. + * + * @param {!WebElement} elem The element where scroll starts. + * @param {{x: number, y: number}} offset The offset to scroll to. + * @return {!TouchSequence} A self reference. + */ + scrollFromElement(elem: WebElement, offset: IOffset): TouchSequence; + + /** + * Flick, starting anywhere on the screen, at speed xspeed and yspeed. + * + * @param {{xspeed: number, yspeed: number}} speed The speed to flick in each + direction, in pixels per second. + * @return {!TouchSequence} A self reference. + */ + flick(speed: ISpeed): TouchSequence; + + /** + * Flick starting at elem and moving by x and y at specified speed. + * + * @param {!WebElement} elem The element where flick starts. + * @param {{x: number, y: number}} offset The offset to flick to. + * @param {number} speed The speed to flick at in pixels per second. + * @return {!TouchSequence} A self reference. + */ + flickElement(elem: WebElement, offset: IOffset, speed: number): TouchSequence; +} + +interface IOffset { + x: number; + y: number; +} + +interface ISpeed { + xspeed: number; + yspeed: number; +} + +/** + * Represents a modal dialog such as {@code alert}, {@code confirm}, or + * {@code prompt}. Provides functions to retrieve the message displayed with + * the alert, accept or dismiss the alert, and set the response text (in the + * case of {@code prompt}). + */ +export class Alert { + /** + * @param {!WebDriver} driver The driver controlling the browser this alert + * is attached to. + * @param {string} text The message text displayed with this alert. + */ + constructor(driver: WebDriver, text: string); + + // region Methods + + /** + * Retrieves the message text displayed with this alert. For instance, if the + * alert were opened with alert('hello'), then this would return 'hello'. + * @return {!promise.Promise} A promise that will be resolved to the + * text displayed with this alert. + */ + getText(): promise.Promise; + + /** + * Sets the username and password in an alert prompting for credentials (such + * as a Basic HTTP Auth prompt). This method will implicitly + * {@linkplain #accept() submit} the dialog. + * + * @param {string} username The username to send. + * @param {string} password The password to send. + * @return {!promise.Promise} A promise that will be resolved when this + * command has completed. + */ + authenticateAs(username: string, password: string): promise.Promise; + + /** + * Accepts this alert. + * @return {!promise.Promise} A promise that will be resolved when + * this command has completed. + */ + accept(): promise.Promise; + + /** + * Dismisses this alert. + * @return {!promise.Promise} A promise that will be resolved when + * this command has completed. + */ + dismiss(): promise.Promise; + + /** + * Sets the response text on this alert. This command will return an error if + * the underlying alert does not support response text (e.g. window.alert and + * window.confirm). + * @param {string} text The text to set. + * @return {!promise.Promise} A promise that will be resolved when + * this command has completed. + */ + sendKeys(text: string): promise.Promise; + + // endregion + +} + +/** + * AlertPromise is a promise that will be fulfilled with an Alert. This promise + * serves as a forward proxy on an Alert, allowing calls to be scheduled + * directly on this instance before the underlying Alert has been fulfilled. In + * other words, the following two statements are equivalent: + * + * driver.switchTo().alert().dismiss(); + * driver.switchTo().alert().then(function(alert) { + * return alert.dismiss(); + * }); + * + * @implements {promise.Thenable.} + * @final + */ +export class AlertPromise extends Alert implements promise.IThenable { + /** + * @param {!WebDriver} driver The driver controlling the browser this + * alert is attached to. + * @param {!promise.Thenable} alert A thenable + * that will be fulfilled with the promised alert. + */ + constructor(driver: WebDriver, alert: promise.Promise); + + // region Methods + + /** + * Cancels the computation of this promise's value, rejecting the promise in the + * process. + * @param {*} reason The reason this promise is being cancelled. If not an + * {@code Error}, one will be created using the value's string + * representation. + */ + cancel(opt_reason?: string | Error): void; + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + /** + * Registers listeners for when this instance is resolved. This function most + * overridden by subtypes. + * + * @param opt_callback The function to call if this promise is + * successfully resolved. The function should expect a single argument: the + * promise's resolved value. + * @param opt_errback The function to call if this promise is + * rejected. The function should expect a single argument: the rejection + * reason. + * @return A new promise which will be resolved + * with the result of the invoked callback. + */ + then(opt_callback?: Function, opt_errback?: Function): promise.Promise; + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + *


+   *   // Synchronous API:
+   *   try {
+   *     doSynchronousWork();
+   *   } catch (ex) {
+   *     console.error(ex);
+   *   }
+   *
+   *   // Asynchronous promise API:
+   *   doAsynchronousWork().thenCatch(function(ex) {
+   *     console.error(ex);
+   *   });
+   * 
+ * + * @param {function(*): (R|promise.Promise.)} errback The function + * to call if this promise is rejected. The function should expect a single + * argument: the rejection reason. + * @return {!promise.Promise.} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + thenCatch(errback: (error: any) => any): promise.Promise; + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + * + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } + * + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); + * + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + catch(errback: Function): promise.Promise; + + + /** + * Registers a listener to invoke when this promise is resolved, regardless + * of whether the promise's value was successfully computed. This function + * is synonymous with the {@code finally} clause in a synchronous API: + *

+   *   // Synchronous API:
+   *   try {
+   *     doSynchronousWork();
+   *   } finally {
+   *     cleanUp();
+   *   }
+   *
+   *   // Asynchronous promise API:
+   *   doAsynchronousWork().thenFinally(cleanUp);
+   * 
+ * + * Note: similar to the {@code finally} clause, if the registered + * callback returns a rejected promise or throws an error, it will silently + * replace the rejection error (if any) from this promise: + *

+   *   try {
+   *     throw Error('one');
+   *   } finally {
+   *     throw Error('two');  // Hides Error: one
+   *   }
+   *
+   *   promise.rejected(Error('one'))
+   *       .thenFinally(function() {
+   *         throw Error('two');  // Hides Error: one
+   *       });
+   * 
+ * + * + * @param {function(): (R|promise.Promise.)} callback The function + * to call when this promise is resolved. + * @return {!promise.Promise.} A promise that will be fulfilled + * with the callback result. + * @template R + */ + thenFinally(callback: Function): promise.Promise; +} + +/** @deprecated Use {@link error.UnexpectedAlertOpenError} instead. */ +export class UnhandledAlertError extends error.UnexpectedAlertOpenError { +} + +/** + * Recognized browser names. + * @enum {string} + */ +interface IBrowser { + ANDROID: string; + CHROME: string; + EDGE: string; + FIREFOX: string; + IE: string; + INTERNET_EXPLORER: string; + IPAD: string; + IPHONE: string; + OPERA: string; + PHANTOM_JS: string; + SAFARI: string; + HTMLUNIT: string; +} + +export var Browser: IBrowser; + +interface ProxyConfig { + proxyType: string; + proxyAutoconfigUrl?: string; + ftpProxy?: string; + httpProxy?: string; + sslProxy?: string; + noProxy?: string; +} + +/** + * Creates new {@link WebDriver WebDriver} instances. The environment + * variables listed below may be used to override a builder's configuration, + * allowing quick runtime changes. + * + * - {@code SELENIUM_BROWSER}: defines the target browser in the form + * {@code browser[:version][:platform]}. + * + * - {@code SELENIUM_REMOTE_URL}: defines the remote URL for all builder + * instances. This environment variable should be set to a fully qualified + * URL for a WebDriver server (e.g. http://localhost:4444/wd/hub). This + * option always takes precedence over {@code SELENIUM_SERVER_JAR}. + * + * - {@code SELENIUM_SERVER_JAR}: defines the path to the + * + * standalone Selenium server jar to use. The server will be started the + * first time a WebDriver instance and be killed when the process exits. + * + * Suppose you had mytest.js that created WebDriver with + * + * var driver = new Builder() + * .forBrowser('chrome') + * .build(); + * + * This test could be made to use Firefox on the local machine by running with + * `SELENIUM_BROWSER=firefox node mytest.js`. Rather than change the code to + * target Google Chrome on a remote machine, you can simply set the + * `SELENIUM_BROWSER` and `SELENIUM_REMOTE_URL` environment variables: + * + * SELENIUM_BROWSER=chrome:36:LINUX \ + * SELENIUM_REMOTE_URL=http://www.example.com:4444/wd/hub \ + * node mytest.js + * + * You could also use a local copy of the standalone Selenium server: + * + * SELENIUM_BROWSER=chrome:36:LINUX \ + * SELENIUM_SERVER_JAR=/path/to/selenium-server-standalone.jar \ + * node mytest.js + */ +export class Builder { + + // region Constructors + + /** + * @constructor + */ + constructor(); + + // endregion + + // region Methods + + /** + * Configures this builder to ignore any environment variable overrides and to + * only use the configuration specified through this instance's API. + * + * @return {!Builder} A self reference. + */ + disableEnvironmentOverrides(): Builder; + + /** + * Creates a new WebDriver client based on this builder's current + * configuration. + * + * While this method will immediately return a new WebDriver instance, any + * commands issued against it will be deferred until the associated browser + * has been fully initialized. Users may call {@link #buildAsync()} to obtain + * a promise that will not be fulfilled until the browser has been created + * (the difference is purely in style). + * + * @return {!WebDriver} A new WebDriver instance. + * @throws {Error} If the current configuration is invalid. + * @see #buildAsync() + */ + build(): WebDriver; + + /** + * Creates a new WebDriver client based on this builder's current + * configuration. This method returns a promise that will not be fulfilled + * until the new browser session has been fully initialized. + * + * __Note:__ this method is purely a convenience wrapper around + * {@link #build()}. + * + * @return {!promise.Promise} A promise that will be + * fulfilled with the newly created WebDriver instance once the browser + * has been fully initialized. + * @see #build() + */ + buildAsync(): promise.Promise; + + /** + * Configures the target browser for clients created by this instance. + * Any calls to {@link #withCapabilities} after this function will + * overwrite these settings. + * + *

You may also define the target browser using the {@code SELENIUM_BROWSER} + * environment variable. If set, this environment variable should be of the + * form {@code browser[:[version][:platform]]}. + * + * @param {(string|Browser)} name The name of the target browser; + * common defaults are available on the {@link Browser} enum. + * @param {string=} opt_version A desired version; may be omitted if any + * version should be used. + * @param {string=} opt_platform The desired platform; may be omitted if any + * version may be used. + * @return {!Builder} A self reference. + */ + forBrowser(name: string, opt_version?: string, opt_platform?: string): Builder; + + /** + * Returns the base set of capabilities this instance is currently configured + * to use. + * @return {!Capabilities} The current capabilities for this builder. + */ + getCapabilities(): Capabilities; + + /** + * @return {string} The URL of the WebDriver server this instance is configured + * to use. + */ + getServerUrl(): string; + + /** + * @return {?string} The URL of the proxy server to use for the WebDriver's + * HTTP connections, or `null` if not set. + */ + getWebDriverProxy(): string; + + /** + * Sets the default action to take with an unexpected alert before returning + * an error. + * @param {string} beahvior The desired behavior; should be 'accept', 'dismiss', + * or 'ignore'. Defaults to 'dismiss'. + * @return {!Builder} A self reference. + */ + setAlertBehavior(behavior: string): Builder; + + /** + * Sets Chrome-specific options for drivers created by this builder. Any + * logging or proxy settings defined on the given options will take precedence + * over those set through {@link #setLoggingPrefs} and {@link #setProxy}, + * respectively. + * + * @param {!chrome.Options} options The ChromeDriver options to use. + * @return {!Builder} A self reference. + */ + setChromeOptions(options: chrome.Options): Builder; + + /** + * Sets the control flow that created drivers should execute actions in. If + * the flow is never set, or is set to {@code null}, it will use the active + * flow at the time {@link #build()} is called. + * @param {promise.ControlFlow} flow The control flow to use, or + * {@code null} to + * @return {!Builder} A self reference. + */ + setControlFlow(flow: promise.ControlFlow): Builder; + + /** + * Set {@linkplain edge.Options options} specific to Microsoft's Edge browser + * for drivers created by this builder. Any proxy settings defined on the + * given options will take precedence over those set through + * {@link #setProxy}. + * + * @param {!edge.Options} options The MicrosoftEdgeDriver options to use. + * @return {!Builder} A self reference. + */ + setEdgeOptions(options: edge.Options): Builder; + + /** + * Sets whether native events should be used. + * @param {boolean} enabled Whether to enable native events. + * @return {!Builder} A self reference. + */ + setEnableNativeEvents(enabled: boolean): Builder; + + /** + * Sets Firefox-specific options for drivers created by this builder. Any + * logging or proxy settings defined on the given options will take precedence + * over those set through {@link #setLoggingPrefs} and {@link #setProxy}, + * respectively. + * + * @param {!firefox.Options} options The FirefoxDriver options to use. + * @return {!Builder} A self reference. + */ + setFirefoxOptions(options: firefox.Options): Builder; + + /** + * Set Internet Explorer specific {@linkplain ie.Options options} for drivers + * created by this builder. Any proxy settings defined on the given options + * will take precedence over those set through {@link #setProxy}. + * + * @param {!ie.Options} options The IEDriver options to use. + * @return {!Builder} A self reference. + */ + setIeOptions(options: ie.Options): Builder; + + /** + * Sets the logging preferences for the created session. Preferences may be + * changed by repeated calls, or by calling {@link #withCapabilities}. + * @param {!(logging.Preferences|Object.)} prefs The + * desired logging preferences. + * @return {!Builder} A self reference. + */ + setLoggingPrefs(prefs: logging.Preferences | Object): Builder; + + /** + * Sets Opera specific {@linkplain opera.Options options} for drivers created + * by this builder. Any logging or proxy settings defined on the given options + * will take precedence over those set through {@link #setLoggingPrefs} and + * {@link #setProxy}, respectively. + * + * @param {!opera.Options} options The OperaDriver options to use. + * @return {!Builder} A self reference. + */ + setOperaOptions(options: opera.Options): Builder; + + /** + * Sets the proxy configuration to use for WebDriver clients created by this + * builder. Any calls to {@link #withCapabilities} after this function will + * overwrite these settings. + * @param {!capabilities.ProxyConfig} config The configuration to use. + * @return {!Builder} A self reference. + */ + setProxy(config: ProxyConfig): Builder; + + /** + * Sets Safari specific {@linkplain safari.Options options} for drivers + * created by this builder. Any logging settings defined on the given options + * will take precedence over those set through {@link #setLoggingPrefs}. + * + * @param {!safari.Options} options The Safari options to use. + * @return {!Builder} A self reference. + */ + setSafari(options: safari.Options): Builder; + + /** + * Sets how elements should be scrolled into view for interaction. + * @param {number} behavior The desired scroll behavior: either 0 to align with + * the top of the viewport or 1 to align with the bottom. + * @return {!Builder} A self reference. + */ + setScrollBehavior(behavior: number): Builder; + + /** + * Sets the URL of a remote WebDriver server to use. Once a remote URL has been + * specified, the builder direct all new clients to that server. If this method + * is never called, the Builder will attempt to create all clients locally. + * + *

As an alternative to this method, you may also set the + * {@code SELENIUM_REMOTE_URL} environment variable. + * + * @param {string} url The URL of a remote server to use. + * @return {!Builder} A self reference. + */ + usingServer(url: string): Builder; + + /** + * Sets the URL of the proxy to use for the WebDriver's HTTP connections. + * If this method is never called, the Builder will create a connection + * without a proxy. + * + * @param {string} proxy The URL of a proxy to use. + * @return {!Builder} A self reference. + */ + usingWebDriverProxy(proxy: string): Builder; + + /** + * Sets the desired capabilities when requesting a new session. This will + * overwrite any previously set capabilities. + * @param {!(Object|Capabilities)} capabilities The desired + * capabilities for a new session. + * @return {!Builder} A self reference. + */ + withCapabilities(capabilities: Object | Capabilities): Builder; + + // endregion +} + +/** + * Describes a mechanism for locating an element on the page. + * @final + */ +export class By { + + /** + * @param {string} using the name of the location strategy to use. + * @param {string} value the value to search for. + */ + constructor(using: string, value: string); + + /** + * Locates elements that have a specific class name. + * + * @param {string} name The class name to search for. + * @return {!By} The new locator. + * @see http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#classes + * @see http://www.w3.org/TR/CSS2/selector.html#class-html + */ + static className(name: string): By; + + /** + * Locates elements using a CSS selector. + * + * @param {string} selector The CSS selector to use. + * @return {!By} The new locator. + * @see http://www.w3.org/TR/CSS2/selector.html + */ + static css(selector: string): By; + + /** + * Locates eleemnts by the ID attribute. This locator uses the CSS selector + * `*[id='$ID']`, _not_ `document.getElementById`. + * + * @param {string} id The ID to search for. + * @return {!By} The new locator. + */ + static id(id: string): By; + + /** + * Locates link elements whose + * {@linkplain WebElement#getText visible text} matches the given + * string. + * + * @param {string} text The link text to search for. + * @return {!By} The new locator. + */ + static linkText(text: string): By; + + /** + * Locates an elements by evaluating a + * {@linkplain WebDriver#executeScript JavaScript expression}. + * The result of this expression must be an element or list of elements. + * + * @param {!(string|Function)} script The script to execute. + * @param {...*} var_args The arguments to pass to the script. + * @return {function(!./WebDriver): !./promise.Promise} + * A new JavaScript-based locator function. + */ + static js(script: string | Function, ...var_args: any[]): (webdriver: WebDriver) => promise.Promise; + + /** + * Locates elements whose `name` attribute has the given value. + * + * @param {string} name The name attribute to search for. + * @return {!By} The new locator. + */ + static name(name: string): By; + + /** + * Locates link elements whose + * {@linkplain WebElement#getText visible text} contains the given + * substring. + * + * @param {string} text The substring to check for in a link's visible text. + * @return {!By} The new locator. + */ + static partialLinkText(text: string): By; + + /** + * Locates elements with a given tag name. + * + * @param {string} name The tag name to search for. + * @return {!By} The new locator. + * @deprecated Use {@link By.css() By.css(tagName)} instead. + */ + static tagName(name: string): By; + + /** + * Locates elements matching a XPath selector. Care should be taken when + * using an XPath selector with a {@link WebElement} as WebDriver + * will respect the context in the specified in the selector. For example, + * given the selector `//div`, WebDriver will search from the document root + * regardless of whether the locator was used with a WebElement. + * + * @param {string} xpath The XPath selector to use. + * @return {!By} The new locator. + * @see http://www.w3.org/TR/xpath/ + */ + static xpath(xpath: string): By; + + /** @override */ + toString(): string; +} + +/** + * Short-hand expressions for the primary element locator strategies. + * For example the following two statements are equivalent: + * + * var e1 = driver.findElement(By.id('foo')); + * var e2 = driver.findElement({id: 'foo'}); + * + * Care should be taken when using JavaScript minifiers (such as the + * Closure compiler), as locator hashes will always be parsed using + * the un-obfuscated properties listed. + * + * @typedef {( + * {className: string}| + * {css: string}| + * {id: string}| + * {js: string}| + * {linkText: string}| + * {name: string}| + * {partialLinkText: string}| + * {tagName: string}| + * {xpath: string})} + */ +type ByHash = { className: string } | + { css: string } | + { id: string } | + { js: string } | + { linkText: string } | + { name: string } | + { partialLinkText: string } | + { tagName: string } | + { xpath: string }; + +/** + * Common webdriver capability keys. + * @enum {string} + */ +interface ICapability { + + /** + * Indicates whether a driver should accept all SSL certs by default. This + * capability only applies when requesting a new session. To query whether + * a driver can handle insecure SSL certs, see + * {@link Capability.SECURE_SSL}. + */ + ACCEPT_SSL_CERTS: string; + + + /** + * The browser name. Common browser names are defined in the + * {@link Browser} enum. + */ + BROWSER_NAME: string; + + /** + * Defines how elements should be scrolled into the viewport for interaction. + * This capability will be set to zero (0) if elements are aligned with the + * top of the viewport, or one (1) if aligned with the bottom. The default + * behavior is to align with the top of the viewport. + */ + ELEMENT_SCROLL_BEHAVIOR: string; + + /** + * Whether the driver is capable of handling modal alerts (e.g. alert, + * confirm, prompt). To define how a driver should handle alerts, + * use {@link Capability.UNEXPECTED_ALERT_BEHAVIOR}. + */ + HANDLES_ALERTS: string; + + /** + * Key for the logging driver logging preferences. + */ + LOGGING_PREFS: string; + + /** + * Whether this session generates native events when simulating user input. + */ + NATIVE_EVENTS: string; + + /** + * Describes the platform the browser is running on. Will be one of + * ANDROID, IOS, LINUX, MAC, UNIX, or WINDOWS. When requesting a + * session, ANY may be used to indicate no platform preference (this is + * semantically equivalent to omitting the platform capability). + */ + PLATFORM: string; + + /** + * Describes the proxy configuration to use for a new WebDriver session. + */ + PROXY: string; + + /** Whether the driver supports changing the brower's orientation. */ + ROTATABLE: string; + + /** + * Whether a driver is only capable of handling secure SSL certs. To request + * that a driver accept insecure SSL certs by default, use + * {@link Capability.ACCEPT_SSL_CERTS}. + */ + SECURE_SSL: string; + + /** Whether the driver supports manipulating the app cache. */ + SUPPORTS_APPLICATION_CACHE: string; + + /** Whether the driver supports locating elements with CSS selectors. */ + SUPPORTS_CSS_SELECTORS: string; + + /** Whether the browser supports JavaScript. */ + SUPPORTS_JAVASCRIPT: string; + + /** Whether the driver supports controlling the browser's location info. */ + SUPPORTS_LOCATION_CONTEXT: string; + + /** Whether the driver supports taking screenshots. */ + TAKES_SCREENSHOT: string; + + /** + * Defines how the driver should handle unexpected alerts. The value should + * be one of 'accept', 'dismiss', or 'ignore. + */ + UNEXPECTED_ALERT_BEHAVIOR: string; + + /** Defines the browser version. */ + VERSION: string; +} + +export var Capability: ICapability; + +export class Capabilities { + // region Constructors + + /** + * @param {(Capabilities|Object)=} opt_other Another set of + * capabilities to merge into this instance. + * @constructor + */ + constructor(opt_other?: Capabilities | Object); + + // endregion + + // region Methods + + /** @return {!Object} The JSON representation of this instance. */ + toJSON(): any; + + /** + * Merges another set of capabilities into this instance. Any duplicates in + * the provided set will override those already set on this instance. + * @param {!(Capabilities|Object)} other The capabilities to + * merge into this instance. + * @return {!Capabilities} A self reference. + */ + merge(other: Capabilities | Object): Capabilities; + + /** + * @param {string} key The capability to set. + * @param {*} value The capability value. Capability values must be JSON + * serializable. Pass {@code null} to unset the capability. + * @return {!Capabilities} A self reference. + */ + set(key: string, value: any): Capabilities; + + /** + * Sets the logging preferences. Preferences may be specified as a + * {@link logging.Preferences} instance, or a as a map of log-type to + * log-level. + * @param {!(logging.Preferences|Object.)} prefs The + * logging preferences. + * @return {!Capabilities} A self reference. + */ + setLoggingPrefs(prefs: logging.Preferences | Object): Capabilities; + + /** + * Sets the proxy configuration for this instance. + * @param {ProxyConfig} proxy The desired proxy configuration. + * @return {!Capabilities} A self reference. + */ + setProxy(proxy: ProxyConfig): Capabilities; + + + /** + * Sets whether native events should be used. + * @param {boolean} enabled Whether to enable native events. + * @return {!Capabilities} A self reference. + */ + setEnableNativeEvents(enabled: boolean): Capabilities; + + + /** + * Sets how elements should be scrolled into view for interaction. + * @param {number} behavior The desired scroll behavior: either 0 to align with + * the top of the viewport or 1 to align with the bottom. + * @return {!Capabilities} A self reference. + */ + setScrollBehavior(behavior: number): Capabilities; + + /** + * Sets the default action to take with an unexpected alert before returning + * an error. + * @param {string} behavior The desired behavior; should be 'accept', 'dismiss', + * or 'ignore'. Defaults to 'dismiss'. + * @return {!Capabilities} A self reference. + */ + setAlertBehavior(behavior: string): Capabilities; + + /** + * @param {string} key The capability to return. + * @return {*} The capability with the given key, or {@code null} if it has + * not been set. + */ + get(key: string): any; + + /** + * @param {string} key The capability to check. + * @return {boolean} Whether the specified capability is set. + */ + has(key: string): boolean; + + // endregion + + // region Static Methods + + /** + * @return {!Capabilities} A basic set of capabilities for Android. + */ + static android(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for Chrome. + */ + static chrome(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for Microsoft Edge. + */ + static edge(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for Firefox. + */ + static firefox(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for + * Internet Explorer. + */ + static ie(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for iPad. + */ + static ipad(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for iPhone. + */ + static iphone(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for Opera. + */ + static opera(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for + * PhantomJS. + */ + static phantomjs(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for Safari. + */ + static safari(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for HTMLUnit. + */ + static htmlunit(): Capabilities; + + /** + * @return {!Capabilities} A basic set of capabilities for HTMLUnit + * with enabled Javascript. + */ + static htmlunitwithjs(): Capabilities; + + // endregion +} + +/** + * An enumeration of valid command string. + */ +interface ICommandName { + GET_SERVER_STATUS: string; + + NEW_SESSION: string; + GET_SESSIONS: string; + DESCRIBE_SESSION: string; + + CLOSE: string; + QUIT: string; + + GET_CURRENT_URL: string; + GET: string; + GO_BACK: string; + GO_FORWARD: string; + REFRESH: string; + + ADD_COOKIE: string; + GET_COOKIE: string; + GET_ALL_COOKIES: string; + DELETE_COOKIE: string; + DELETE_ALL_COOKIES: string; + + GET_ACTIVE_ELEMENT: string; + FIND_ELEMENT: string; + FIND_ELEMENTS: string; + FIND_CHILD_ELEMENT: string; + FIND_CHILD_ELEMENTS: string; + + CLEAR_ELEMENT: string; + CLICK_ELEMENT: string; + SEND_KEYS_TO_ELEMENT: string; + SUBMIT_ELEMENT: string; + + GET_CURRENT_WINDOW_HANDLE: string; + GET_WINDOW_HANDLES: string; + GET_WINDOW_POSITION: string; + SET_WINDOW_POSITION: string; + GET_WINDOW_SIZE: string; + SET_WINDOW_SIZE: string; + MAXIMIZE_WINDOW: string; + + SWITCH_TO_WINDOW: string; + SWITCH_TO_FRAME: string; + GET_PAGE_SOURCE: string; + GET_TITLE: string; + + EXECUTE_SCRIPT: string; + EXECUTE_ASYNC_SCRIPT: string; + + GET_ELEMENT_TEXT: string; + GET_ELEMENT_TAG_NAME: string; + IS_ELEMENT_SELECTED: string; + IS_ELEMENT_ENABLED: string; + IS_ELEMENT_DISPLAYED: string; + GET_ELEMENT_LOCATION: string; + GET_ELEMENT_LOCATION_IN_VIEW: string; + GET_ELEMENT_SIZE: string; + GET_ELEMENT_ATTRIBUTE: string; + GET_ELEMENT_VALUE_OF_CSS_PROPERTY: string; + ELEMENT_EQUALS: string; + + SCREENSHOT: string; + IMPLICITLY_WAIT: string; + SET_SCRIPT_TIMEOUT: string; + SET_TIMEOUT: string; + + ACCEPT_ALERT: string; + DISMISS_ALERT: string; + GET_ALERT_TEXT: string; + SET_ALERT_TEXT: string; + + EXECUTE_SQL: string; + GET_LOCATION: string; + SET_LOCATION: string; + GET_APP_CACHE: string; + GET_APP_CACHE_STATUS: string; + CLEAR_APP_CACHE: string; + IS_BROWSER_ONLINE: string; + SET_BROWSER_ONLINE: string; + + GET_LOCAL_STORAGE_ITEM: string; + GET_LOCAL_STORAGE_KEYS: string; + SET_LOCAL_STORAGE_ITEM: string; + REMOVE_LOCAL_STORAGE_ITEM: string; + CLEAR_LOCAL_STORAGE: string; + GET_LOCAL_STORAGE_SIZE: string; + + GET_SESSION_STORAGE_ITEM: string; + GET_SESSION_STORAGE_KEYS: string; + SET_SESSION_STORAGE_ITEM: string; + REMOVE_SESSION_STORAGE_ITEM: string; + CLEAR_SESSION_STORAGE: string; + GET_SESSION_STORAGE_SIZE: string; + + SET_SCREEN_ORIENTATION: string; + GET_SCREEN_ORIENTATION: string; + + // These belong to the Advanced user interactions - an element is + // optional for these commands. + CLICK: string; + DOUBLE_CLICK: string; + MOUSE_DOWN: string; + MOUSE_UP: string; + MOVE_TO: string; + SEND_KEYS_TO_ACTIVE_ELEMENT: string; + + // These belong to the Advanced Touch API + TOUCH_SINGLE_TAP: string; + TOUCH_DOWN: string; + TOUCH_UP: string; + TOUCH_MOVE: string; + TOUCH_SCROLL: string; + TOUCH_DOUBLE_TAP: string; + TOUCH_LONG_PRESS: string; + TOUCH_FLICK: string; + + GET_AVAILABLE_LOG_TYPES: string; + GET_LOG: string; + GET_SESSION_LOGS: string; + + UPLOAD_FILE: string; +} + +export var CommandName: ICommandName; + +/** + * Describes a command to be executed by the WebDriverJS framework. + * @param {!CommandName} name The name of this command. + * @constructor + */ +export class Command { + // region Constructors + + /** + * @param {!CommandName} name The name of this command. + * @constructor + */ + constructor(name: string); + + // endregion + + // region Methods + + /** + * @return {!CommandName} This command's name. + */ + getName(): string; + + /** + * Sets a parameter to send with this command. + * @param {string} name The parameter name. + * @param {*} value The parameter value. + * @return {!Command} A self reference. + */ + setParameter(name: string, value: any): Command; + + /** + * Sets the parameters for this command. + * @param {!Object.<*>} parameters The command parameters. + * @return {!Command} A self reference. + */ + setParameters(parameters: any): Command; + + /** + * Returns a named command parameter. + * @param {string} key The parameter key to look up. + * @return {*} The parameter value, or undefined if it has not been set. + */ + getParameter(key: string): any; + + /** + * @return {!Object.<*>} The parameters to send with this command. + */ + getParameters(): any; + + // endregion +} + +/** + * Handles the execution of WebDriver {@link Command commands}. + * @interface + */ +export class Executor { + /** + * Executes the given {@code command}. If there is an error executing the + * command, the provided callback will be invoked with the offending error. + * Otherwise, the callback will be invoked with a null Error and non-null + * response object. + * + * @param {!Command} command The command to execute. + * @return {!promise.Promise} A promise that will be fulfilled with + * the command result. + */ + execute(command: Command): promise.Promise +} + +/** + * Wraps a promised {@link Executor}, ensuring no commands are executed until + * the wrapped executor has been fully resolved. + * @implements {Executor} + */ +export class DeferredExecutor { + /** + * @param {!promise.Promise} delegate The promised delegate, which + * may be provided by any promise-like thenable object. + */ + constructor(delegate: promise.Promise); +} + +/** + * Describes an event listener registered on an {@linkplain EventEmitter}. + */ +export class Listener { + /** + * @param {!Function} fn The acutal listener function. + * @param {(Object|undefined)} scope The object in whose scope to invoke the + * listener. + * @param {boolean} oneshot Whether this listener should only be used once. + */ + constructor(fn: Function, scope: Object, oneshot: boolean); +} + +/** + * Object that can emit events for others to listen for. This is used instead + * of Closure's event system because it is much more light weight. The API is + * based on Node's EventEmitters. + */ +export class EventEmitter { + // region Constructors + + /** + * @constructor + */ + constructor(); + + // endregion + + // region Methods + + /** + * Fires an event and calls all listeners. + * @param {string} type The type of event to emit. + * @param {...*} var_args Any arguments to pass to each listener. + */ + emit(type: string, ...var_args: any[]): void; + + /** + * Returns a mutable list of listeners for a specific type of event. + * @param {string} type The type of event to retrieve the listeners for. + * @return {!Set} The registered listeners for the given event + * type. + */ + listeners(type: string): any; + + /** + * Registers a listener. + * @param {string} type The type of event to listen for. + * @param {!Function} fn The function to invoke when the event is fired. + * @param {Object=} opt_self The object in whose scope to invoke the listener. + * @param {boolean=} opt_oneshot Whether the listener should b (e removed after + * the first event is fired. + * @return {!EventEmitter} A self reference. + * @private + */ + addListener(type: string, fn: Function, opt_scope?: any, opt_oneshot?: boolean): EventEmitter; + + + /** + * Registers a one-time listener which will be called only the first time an + * event is emitted, after which it will be removed. + * @param {string} type The type of event to listen for. + * @param {!Function} fn The function to invoke when the event is fired. + * @param {Object=} opt_scope The object in whose scope to invoke the listener. + * @return {!EventEmitter} A self reference. + */ + once(type: string, fn: any, opt_scope?: any): EventEmitter; + + /** + * An alias for {@code #addListener()}. + * @param {string} type The type of event to listen for. + * @param {!Function} fn The function to invoke when the event is fired. + * @param {Object=} opt_scope The object in whose scope to invoke the listener. + * @return {!EventEmitter} A self reference. + */ + on(type: string, fn: Function, opt_scope?: any): EventEmitter; + + /** + * Removes a previously registered event listener. + * @param {string} type The type of event to unregister. + * @param {!Function} listenerFn The handler function to remove. + * @return {!EventEmitter} A self reference. + */ + removeListener(type: string, listenerFn: Function): EventEmitter; + + /** + * Removes all listeners for a specific type of event. If no event is + * specified, all listeners across all types will be removed. + * @param {string=} opt_type The type of event to remove listeners from. + * @return {!EventEmitter} A self reference. + */ + removeAllListeners(opt_type?: string): EventEmitter; + + // endregion +} + + +/** + * Interface for navigating back and forth in the browser history. + */ +export class Navigation { + // region Constructors + + /** + * Interface for navigating back and forth in the browser history. + * + * This class should never be instantiated directly. Insead, obtain an instance + * with + * + * navigate() + * + * @see WebDriver#navigate() + */ + constructor(driver: WebDriver); + + // endregion + + // region Methods + + /** + * Schedules a command to navigate to a new URL. + * @param {string} url The URL to navigate to. + * @return {!promise.Promise.} A promise that will be resolved + * when the URL has been loaded. + */ + to(url: string): promise.Promise; + + /** + * Schedules a command to move backwards in the browser history. + * @return {!promise.Promise.} A promise that will be resolved + * when the navigation event has completed. + */ + back(): promise.Promise; + + /** + * Schedules a command to move forwards in the browser history. + * @return {!promise.Promise.} A promise that will be resolved + * when the navigation event has completed. + */ + forward(): promise.Promise; + + /** + * Schedules a command to refresh the current page. + * @return {!promise.Promise.} A promise that will be resolved + * when the navigation event has completed. + */ + refresh(): promise.Promise; + + // endregion +} + +interface IWebDriverOptionsCookie { + name: string; + value: string; + path?: string; + domain?: string; + secure?: boolean; + expiry?: number; +} + +/** + * Provides methods for managing browser and driver state. + */ +export class Options { + // region Constructors + + /** + * @param {!WebDriver} driver The parent driver. + * @constructor + */ + constructor(driver: WebDriver); + + // endregion + + // region Methods + + /** + * Schedules a command to add a cookie. + * @param {string} name The cookie name. + * @param {string} value The cookie value. + * @param {string=} opt_path The cookie path. + * @param {string=} opt_domain The cookie domain. + * @param {boolean=} opt_isSecure Whether the cookie is secure. + * @param {(number|!Date)=} opt_expiry When the cookie expires. If specified + * as a number, should be in milliseconds since midnight, + * January 1, 1970 UTC. + * @return {!promise.Promise} A promise that will be resolved + * when the cookie has been added to the page. + */ + addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: number | Date): promise.Promise; + + /** + * Schedules a command to delete all cookies visible to the current page. + * @return {!promise.Promise} A promise that will be resolved when all + * cookies have been deleted. + */ + deleteAllCookies(): promise.Promise; + + /** + * Schedules a command to delete the cookie with the given name. This command is + * a no-op if there is no cookie with the given name visible to the current + * page. + * @param {string} name The name of the cookie to delete. + * @return {!promise.Promise} A promise that will be resolved when the + * cookie has been deleted. + */ + deleteCookie(name: string): promise.Promise; + + /** + * Schedules a command to retrieve all cookies visible to the current page. + * Each cookie will be returned as a JSON object as described by the WebDriver + * wire protocol. + * @return {!promise.Promise} A promise that will be resolved with the + * cookies visible to the current page. + * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol#Cookie_JSON_Object + */ + getCookies(): promise.Promise; + + /** + * Schedules a command to retrieve the cookie with the given name. Returns null + * if there is no such cookie. The cookie will be returned as a JSON object as + * described by the WebDriver wire protocol. + * @param {string} name The name of the cookie to retrieve. + * @return {!promise.Promise} A promise that will be resolved with the + * named cookie, or {@code null} if there is no such cookie. + * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol#Cookie_JSON_Object + */ + getCookie(name: string): promise.Promise; + + /** + * @return {!Logs} The interface for managing driver + * logs. + */ + logs(): Logs; + + /** + * @return {!Timeouts} The interface for managing driver + * timeouts. + */ + timeouts(): Timeouts; + + /** + * @return {!Window} The interface for managing the + * current window. + */ + window(): Window; + + // endregion +} + +/** + * An interface for managing timeout behavior for WebDriver instances. + */ +export class Timeouts { + // region Constructors + + /** + * @param {!WebDriver} driver The parent driver. + * @constructor + */ + constructor(driver: WebDriver); + + // endregion + + // region Methods + + /** + * Specifies the amount of time the driver should wait when searching for an + * element if it is not immediately present. + *

+ * When searching for a single element, the driver should poll the page + * until the element has been found, or this timeout expires before failing + * with a {@code bot.ErrorCode.NO_SUCH_ELEMENT} error. When searching + * for multiple elements, the driver should poll the page until at least one + * element has been found or this timeout has expired. + *

+ * Setting the wait timeout to 0 (its default value), disables implicit + * waiting. + *

+ * Increasing the implicit wait timeout should be used judiciously as it + * will have an adverse effect on test run time, especially when used with + * slower location strategies like XPath. + * + * @param {number} ms The amount of time to wait, in milliseconds. + * @return {!promise.Promise} A promise that will be resolved when the + * implicit wait timeout has been set. + */ + implicitlyWait(ms: number): promise.Promise; + + /** + * Sets the amount of time to wait, in milliseconds, for an asynchronous script + * to finish execution before returning an error. If the timeout is less than or + * equal to 0, the script will be allowed to run indefinitely. + * + * @param {number} ms The amount of time to wait, in milliseconds. + * @return {!promise.Promise} A promise that will be resolved when the + * script timeout has been set. + */ + setScriptTimeout(ms: number): promise.Promise; + + /** + * Sets the amount of time to wait for a page load to complete before returning + * an error. If the timeout is negative, page loads may be indefinite. + * @param {number} ms The amount of time to wait, in milliseconds. + * @return {!promise.Promise} A promise that will be resolved when + * the timeout has been set. + */ + pageLoadTimeout(ms: number): promise.Promise; + + // endregion +} + +/** + * An interface for managing the current window. + */ +export class Window { + + // region Constructors + + /** + * @param {!WebDriver} driver The parent driver. + * @constructor + */ + constructor(driver: WebDriver); + + // endregion + + // region Methods + + /** + * Retrieves the window's current position, relative to the top left corner of + * the screen. + * @return {!promise.Promise} A promise that will be resolved with the + * window's position in the form of a {x:number, y:number} object literal. + */ + getPosition(): promise.Promise; + + /** + * Repositions the current window. + * @param {number} x The desired horizontal position, relative to the left side + * of the screen. + * @param {number} y The desired vertical position, relative to the top of the + * of the screen. + * @return {!promise.Promise} A promise that will be resolved when the + * command has completed. + */ + setPosition(x: number, y: number): promise.Promise; + + /** + * Retrieves the window's current size. + * @return {!promise.Promise} A promise that will be resolved with the + * window's size in the form of a {width:number, height:number} object + * literal. + */ + getSize(): promise.Promise; + + /** + * Resizes the current window. + * @param {number} width The desired window width. + * @param {number} height The desired window height. + * @return {!promise.Promise} A promise that will be resolved when the + * command has completed. + */ + setSize(width: number, height: number): promise.Promise; + + /** + * Maximizes the current window. + * @return {!promise.Promise} A promise that will be resolved when the + * command has completed. + */ + maximize(): promise.Promise; + + // endregion +} + +/** + * Interface for managing WebDriver log records. + */ +export class Logs { + + // region Constructors + + /** + * @param {!WebDriver} driver The parent driver. + * @constructor + */ + constructor(driver: WebDriver); + + // endregion + + // region + + /** + * Fetches available log entries for the given type. + * + *

Note that log buffers are reset after each call, meaning that + * available log entries correspond to those entries not yet returned for a + * given log type. In practice, this means that this call will return the + * available log entries since the last call, or from the start of the + * session. + * + * @param {!logging.Type} type The desired log type. + * @return {!promise.Promise.>} A + * promise that will resolve to a list of log entries for the specified + * type. + */ + get(type: string): promise.Promise; + + /** + * Retrieves the log types available to this driver. + * @return {!promise.Promise.>} A + * promise that will resolve to a list of available log types. + */ + getAvailableLogTypes(): promise.Promise; + + // endregion +} + +/** + * An interface for changing the focus of the driver to another frame or window. + */ +export class TargetLocator { + + // region Constructors + + /** + * @param {!WebDriver} driver The parent driver. + * @constructor + */ + constructor(driver: WebDriver); + + // endregion + + // region Methods + + /** + * Schedules a command retrieve the {@code document.activeElement} element on + * the current document, or {@code document.body} if activeElement is not + * available. + * @return {!WebElement} The active element. + */ + activeElement(): WebElementPromise; + + /** + * Schedules a command to switch focus of all future commands to the first frame + * on the page. + * @return {!promise.Promise} A promise that will be resolved when the + * driver has changed focus to the default content. + */ + defaultContent(): promise.Promise; + + /** + * Schedules a command to switch the focus of all future commands to another + * frame on the page. The target frame may be specified as one of the + * following: + * + * - A number that specifies a (zero-based) index into [window.frames]( + * https://developer.mozilla.org/en-US/docs/Web/API/Window.frames). + * - A {@link WebElement} reference, which correspond to a `frame` or `iframe` + * DOM element. + * - The `null` value, to select the topmost frame on the page. Passing `null` + * is the same as calling {@link #defaultContent defaultContent()}. + * + * If the specified frame can not be found, the returned promise will be + * rejected with a {@linkplain error.NoSuchFrameError}. + * + * @param {(number|WebElement|null)} id The frame locator. + * @return {!promise.Promise} A promise that will be resolved + * when the driver has changed focus to the specified frame. + */ + frame(nameOrIndex: number | WebElement): promise.Promise; + + /** + * Schedules a command to switch the focus of all future commands to another + * window. Windows may be specified by their {@code window.name} attribute or + * by its handle (as returned by {@link WebDriver#getWindowHandles}). + * + * If the specified window cannot be found, the returned promise will be + * rejected with a {@linkplain error.NoSuchWindowError}. + * + * @param {string} nameOrHandle The name or window handle of the window to + * switch focus to. + * @return {!promise.Promise} A promise that will be resolved + * when the driver has changed focus to the specified window. + */ + window(nameOrHandle: string): promise.Promise; + + /** + * Schedules a command to change focus to the active modal dialog, such as + * those opened by `window.alert()`, `window.confirm()`, and + * `window.prompt()`. The returned promise will be rejected with a + * {@linkplain error.NoSuchAlertError} if there are no open alerts. + * + * @return {!AlertPromise} The open alert. + */ + alert(): AlertPromise; + + // endregion +} + +/** + * Used with {@link WebElement#sendKeys WebElement#sendKeys} on file + * input elements ({@code }) to detect when the entered key + * sequence defines the path to a file. + * + * By default, {@linkplain WebElement WebElement's} will enter all + * key sequences exactly as entered. You may set a + * {@linkplain WebDriver#setFileDetector file detector} on the parent + * WebDriver instance to define custom behavior for handling file elements. Of + * particular note is the {@link selenium-webdriver/remote.FileDetector}, which + * should be used when running against a remote + * [Selenium Server](http://docs.seleniumhq.org/download/). + */ +export class FileDetector { + /** @constructor */ + constructor(); + + /** + * Handles the file specified by the given path, preparing it for use with + * the current browser. If the path does not refer to a valid file, it will + * be returned unchanged, otherwisee a path suitable for use with the current + * browser will be returned. + * + * This default implementation is a no-op. Subtypes may override this + * function for custom tailored file handling. + * + * @param {!WebDriver} driver The driver for the current browser. + * @param {string} path The path to process. + * @return {!promise.Promise} A promise for the processed + * file path. + * @package + */ + handleFile(driver: WebDriver, path: string): promise.Promise; +} + +/** + * Creates a new WebDriver client, which provides control over a browser. + * + * Every WebDriver command returns a {@code promise.Promise} that + * represents the result of that command. Callbacks may be registered on this + * object to manipulate the command result or catch an expected error. Any + * commands scheduled with a callback are considered sub-commands and will + * execute before the next command in the current frame. For example: + * + * var message = []; + * driver.call(message.push, message, 'a').then(function() { + * driver.call(message.push, message, 'b'); + * }); + * driver.call(message.push, message, 'c'); + * driver.call(function() { + * alert('message is abc? ' + (message.join('') == 'abc')); + * }); + * + */ +export class WebDriver { + // region Constructors + + /** + * @param {!(Session|promise.Promise)} session Either a + * known session or a promise that will be resolved to a session. + * @param {!command.Executor} executor The executor to use when sending + * commands to the browser. + * @param {promise.ControlFlow=} opt_flow The flow to + * schedule commands through. Defaults to the active flow object. + */ + constructor(session: Session | promise.Promise, executor: Executor, opt_flow?: promise.ControlFlow); + + // endregion + + // region StaticMethods + + /** + * Creates a new WebDriver client for an existing session. + * @param {!command.Executor} executor Command executor to use when querying + * for session details. + * @param {string} sessionId ID of the session to attach to. + * @param {promise.ControlFlow=} opt_flow The control flow all + * driver commands should execute under. Defaults to the + * {@link promise.controlFlow() currently active} control flow. + * @return {!WebDriver} A new client for the specified session. + */ + static attachToSession(executor: Executor, sessionId: string, opt_flow?: promise.ControlFlow): WebDriver; + + /** + * Creates a new WebDriver session. + * @param {!command.Executor} executor The executor to create the new session + * with. + * @param {!./capabilities.Capabilities} desiredCapabilities The desired + * capabilities for the new session. + * @param {promise.ControlFlow=} opt_flow The control flow all driver + * commands should execute under, including the initial session creation. + * Defaults to the {@link promise.controlFlow() currently active} + * control flow. + * @return {!WebDriver} The driver for the newly created session. + */ + static createSession(executor: Executor, desiredCapabilities: Capabilities, opt_flow?: promise.ControlFlow): WebDriver; + + // endregion + + // region Methods + + /** + * @return {!promise.ControlFlow} The control flow used by this + * instance. + */ + controlFlow(): promise.ControlFlow; + + /** + * Schedules a {@link command.Command} to be executed by this driver's + * {@link command.Executor}. + * + * @param {!command.Command} command The command to schedule. + * @param {string} description A description of the command for debugging. + * @return {!promise.Promise} A promise that will be resolved + * with the command result. + * @template T + */ + schedule(command: Command, description: string): promise.Promise; + + + /** + * Sets the {@linkplain input.FileDetector file detector} that should be + * used with this instance. + * @param {input.FileDetector} detector The detector to use or {@code null}. + */ + setFileDetector(detector: FileDetector): void; + + + /** + * @return {!promise.Promise.} A promise for this + * client's session. + */ + getSession(): promise.Promise; + + + /** + * @return {!promise.Promise.} A promise + * that will resolve with the this instance's capabilities. + */ + getCapabilities(): promise.Promise; + + + /** + * Schedules a command to quit the current session. After calling quit, this + * instance will be invalidated and may no longer be used to issue commands + * against the browser. + * @return {!promise.Promise.} A promise that will be resolved + * when the command has completed. + */ + quit(): promise.Promise; + + /** + * Creates a new action sequence using this driver. The sequence will not be + * scheduled for execution until {@link actions.ActionSequence#perform} is + * called. Example: + * + * driver.actions(). + * mouseDown(element1). + * mouseMove(element2). + * mouseUp(). + * perform(); + * + * @return {!actions.ActionSequence} A new action sequence for this instance. + */ + actions(): ActionSequence; + + + /** + * Creates a new touch sequence using this driver. The sequence will not be + * scheduled for execution until {@link actions.TouchSequence#perform} is + * called. Example: + * + * driver.touchActions(). + * tap(element1). + * doubleTap(element2). + * perform(); + * + * @return {!actions.TouchSequence} A new touch sequence for this instance. + */ + touchActions(): TouchSequence; + + + /** + * Schedules a command to execute JavaScript in the context of the currently + * selected frame or window. The script fragment will be executed as the body + * of an anonymous function. If the script is provided as a function object, + * that function will be converted to a string for injection into the target + * window. + * + * Any arguments provided in addition to the script will be included as script + * arguments and may be referenced using the {@code arguments} object. + * Arguments may be a boolean, number, string, or {@code WebElement}. + * Arrays and objects may also be used as script arguments as long as each item + * adheres to the types previously mentioned. + * + * The script may refer to any variables accessible from the current window. + * Furthermore, the script will execute in the window's context, thus + * {@code document} may be used to refer to the current document. Any local + * variables will not be available once the script has finished executing, + * though global variables will persist. + * + * If the script has a return value (i.e. if the script contains a return + * statement), then the following steps will be taken for resolving this + * functions return value: + * + * - For a HTML element, the value will resolve to a + * {@link WebElement} + * - Null and undefined return values will resolve to null + * - Booleans, numbers, and strings will resolve as is + * - Functions will resolve to their string representation + * - For arrays and objects, each member item will be converted according to + * the rules above + * + * @param {!(string|Function)} script The script to execute. + * @param {...*} var_args The arguments to pass to the script. + * @return {!promise.Promise.} A promise that will resolve to the + * scripts return value. + * @template T + */ + executeScript(script: string | Function, ...var_args: any[]): promise.Promise; + + /** + * Schedules a command to execute asynchronous JavaScript in the context of the + * currently selected frame or window. The script fragment will be executed as + * the body of an anonymous function. If the script is provided as a function + * object, that function will be converted to a string for injection into the + * target window. + * + * Any arguments provided in addition to the script will be included as script + * arguments and may be referenced using the {@code arguments} object. + * Arguments may be a boolean, number, string, or {@code WebElement}. + * Arrays and objects may also be used as script arguments as long as each item + * adheres to the types previously mentioned. + * + * Unlike executing synchronous JavaScript with {@link #executeScript}, + * scripts executed with this function must explicitly signal they are finished + * by invoking the provided callback. This callback will always be injected + * into the executed function as the last argument, and thus may be referenced + * with {@code arguments[arguments.length - 1]}. The following steps will be + * taken for resolving this functions return value against the first argument + * to the script's callback function: + * + * - For a HTML element, the value will resolve to a + * {@link WebElement} + * - Null and undefined return values will resolve to null + * - Booleans, numbers, and strings will resolve as is + * - Functions will resolve to their string representation + * - For arrays and objects, each member item will be converted according to + * the rules above + * + * __Example #1:__ Performing a sleep that is synchronized with the currently + * selected window: + * + * var start = new Date().getTime(); + * driver.executeAsyncScript( + * 'window.setTimeout(arguments[arguments.length - 1], 500);'). + * then(function() { + * console.log( + * 'Elapsed time: ' + (new Date().getTime() - start) + ' ms'); + * }); + * + * __Example #2:__ Synchronizing a test with an AJAX application: + * + * var button = driver.findElement(By.id('compose-button')); + * button.click(); + * driver.executeAsyncScript( + * 'var callback = arguments[arguments.length - 1];' + + * 'mailClient.getComposeWindowWidget().onload(callback);'); + * driver.switchTo().frame('composeWidget'); + * driver.findElement(By.id('to')).sendKeys('dog@example.com'); + * + * __Example #3:__ Injecting a XMLHttpRequest and waiting for the result. In + * this example, the inject script is specified with a function literal. When + * using this format, the function is converted to a string for injection, so it + * should not reference any symbols not defined in the scope of the page under + * test. + * + * driver.executeAsyncScript(function() { + * var callback = arguments[arguments.length - 1]; + * var xhr = new XMLHttpRequest(); + * xhr.open('GET', '/resource/data.json', true); + * xhr.onreadystatechange = function() { + * if (xhr.readyState == 4) { + * callback(xhr.responseText); + * } + * } + * xhr.send(''); + * }).then(function(str) { + * console.log(JSON.parse(str)['food']); + * }); + * + * @param {!(string|Function)} script The script to execute. + * @param {...*} var_args The arguments to pass to the script. + * @return {!promise.Promise.} A promise that will resolve to the + * scripts return value. + * @template T + */ + executeAsyncScript(script: string | Function, ...var_args: any[]): promise.Promise; + + /** + * Schedules a command to execute a custom function. + * @param {function(...): (T|promise.Promise.)} fn The function to + * execute. + * @param {Object=} opt_scope The object in whose scope to execute the function. + * @param {...*} var_args Any arguments to pass to the function. + * @return {!promise.Promise.} A promise that will be resolved' + * with the function's result. + * @template T + */ + call(fn: (...var_args: any[]) => (T | promise.Promise), opt_scope?: any, ...var_args: any[]): promise.Promise; + + /** + * Schedules a command to wait for a condition to hold. The condition may be + * specified by a {@link until.Condition}, as a custom function, or + * as a {@link promise.Promise}. + * + * For a {@link until.Condition} or function, the wait will repeatedly + * evaluate the condition until it returns a truthy value. If any errors occur + * while evaluating the condition, they will be allowed to propagate. In the + * event a condition returns a {@link promise.Promise promise}, the + * polling loop will wait for it to be resolved and use the resolved value for + * whether the condition has been satisified. Note the resolution time for + * a promise is factored into whether a wait has timed out. + * + * *Example:* waiting up to 10 seconds for an element to be present and visible + * on the page. + * + * var button = driver.wait(until.elementLocated(By.id('foo'), 10000); + * button.click(); + * + * This function may also be used to block the command flow on the resolution + * of a {@link promise.Promise promise}. When given a promise, the + * command will simply wait for its resolution before completing. A timeout may + * be provided to fail the command if the promise does not resolve before the + * timeout expires. + * + * *Example:* Suppose you have a function, `startTestServer`, that returns a + * promise for when a server is ready for requests. You can block a `WebDriver` + * client on this promise with: + * + * var started = startTestServer(); + * driver.wait(started, 5 * 1000, 'Server should start within 5 seconds'); + * driver.get(getServerUrl()); + * + * @param {!(promise.Promise| + * until.Condition| + * function(!WebDriver): T)} condition The condition to + * wait on, defined as a promise, condition object, or a function to + * evaluate as a condition. + * @param {number=} opt_timeout How long to wait for the condition to be true. + * @param {string=} opt_message An optional message to use if the wait times + * out. + * @return {!promise.Promise} A promise that will be fulfilled + * with the first truthy value returned by the condition function, or + * rejected if the condition times out. + * @template T + */ + wait(condition: promise.Promise | until.Condition | ((driver: WebDriver) => T) | Function, timeout?: number, opt_message?: string): promise.Promise; + + /** + * Schedules a command to make the driver sleep for the given amount of time. + * @param {number} ms The amount of time, in milliseconds, to sleep. + * @return {!promise.Promise.} A promise that will be resolved + * when the sleep has finished. + */ + sleep(ms: number): promise.Promise; + + /** + * Schedules a command to retrieve they current window handle. + * @return {!promise.Promise.} A promise that will be + * resolved with the current window handle. + */ + getWindowHandle(): promise.Promise; + + /** + * Schedules a command to retrieve the current list of available window handles. + * @return {!promise.Promise.>} A promise that will + * be resolved with an array of window handles. + */ + getAllWindowHandles(): promise.Promise; + + /** + * Schedules a command to retrieve the current page's source. The page source + * returned is a representation of the underlying DOM: do not expect it to be + * formatted or escaped in the same way as the response sent from the web + * server. + * @return {!promise.Promise.} A promise that will be + * resolved with the current page source. + */ + getPageSource(): promise.Promise; + + /** + * Schedules a command to close the current window. + * @return {!promise.Promise.} A promise that will be resolved + * when this command has completed. + */ + close(): promise.Promise; + + /** + * Schedules a command to navigate to the given URL. + * @param {string} url The fully qualified URL to open. + * @return {!promise.Promise.} A promise that will be resolved + * when the document has finished loading. + */ + get(url: string): promise.Promise; + + /** + * Schedules a command to retrieve the URL of the current page. + * @return {!promise.Promise.} A promise that will be + * resolved with the current URL. + */ + getCurrentUrl(): promise.Promise; + + /** + * Schedules a command to retrieve the current page's title. + * @return {!promise.Promise.} A promise that will be + * resolved with the current page's title. + */ + getTitle(): promise.Promise; + + /** + * Schedule a command to find an element on the page. If the element cannot be + * found, a {@link bot.ErrorCode.NO_SUCH_ELEMENT} result will be returned + * by the driver. Unlike other commands, this error cannot be suppressed. In + * other words, scheduling a command to find an element doubles as an assert + * that the element is present on the page. To test whether an element is + * present on the page, use {@link #isElementPresent} instead. + * + * The search criteria for an element may be defined using one of the + * factories in the {@link By} namespace, or as a short-hand + * {@link By.Hash} object. For example, the following two statements + * are equivalent: + * + * var e1 = driver.findElement(By.id('foo')); + * var e2 = driver.findElement({id:'foo'}); + * + * You may also provide a custom locator function, which takes as input this + * instance and returns a {@link WebElement}, or a promise that will resolve + * to a WebElement. If the returned promise resolves to an array of + * WebElements, WebDriver will use the first element. For example, to find the + * first visible link on a page, you could write: + * + * var link = driver.findElement(firstVisibleLink); + * + * function firstVisibleLink(driver) { + * var links = driver.findElements(By.tagName('a')); + * return promise.filter(links, function(link) { + * return link.isDisplayed(); + * }); + * } + * + * @param {!(by.By|Function)} locator The locator to use. + * @return {!WebElementPromise} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locator: By | Function): WebElementPromise; + + /** + * Schedules a command to test if an element is present on the page. + * + * If given a DOM element, this function will check if it belongs to the + * document the driver is currently focused on. Otherwise, the function will + * test if at least one element can be found with the given search criteria. + * + * @param {!(by.By|Function)} locator The locator to use. + * @return {!promise.Promise} A promise that will resolve + * with whether the element is present on the page. + * @deprecated This method will be removed in Selenium 3.0 for consistency + * with the other Selenium language bindings. This method is equivalent + * to + * + * driver.findElements(locator).then(e => !!e.length); + */ + isElementPresent(locatorOrElement: By | Function): promise.Promise; + + /** + * Schedule a command to search for multiple elements on the page. + * + * @param {!(by.By|Function)} locator The locator to use. + * @return {!promise.Promise.>} A + * promise that will resolve to an array of WebElements. + */ + findElements(locator: By | Function): promise.Promise; + + /** + * Schedule a command to take a screenshot. The driver makes a best effort to + * return a screenshot of the following, in order of preference: + * + * 1. Entire page + * 2. Current window + * 3. Visible portion of the current frame + * 4. The entire display containing the browser + * + * @return {!promise.Promise} A promise that will be + * resolved to the screenshot as a base-64 encoded PNG. + */ + takeScreenshot(): promise.Promise; + + /** + * @return {!Options} The options interface for this + * instance. + */ + manage(): Options; + + /** + * @return {!Navigation} The navigation interface for this + * instance. + */ + navigate(): Navigation; + + /** + * @return {!TargetLocator} The target locator interface for + * this instance. + */ + switchTo(): TargetLocator; + + // endregion +} + +interface IWebElementId { + [ELEMENT: string]: string; +} + +/** + * Represents a DOM element. WebElements can be found by searching from the + * document root using a {@code WebDriver} instance, or by searching + * under another {@code WebElement}: + *


+ *   driver.get('http://www.google.com');
+ *   var searchForm = driver.findElement(By.tagName('form'));
+ *   var searchBox = searchForm.findElement(By.name('q'));
+ *   searchBox.sendKeys('webdriver');
+ * 
+ * + * The WebElement is implemented as a promise for compatibility with the promise + * API. It will always resolve itself when its internal state has been fully + * resolved and commands may be issued against the element. This can be used to + * catch errors when an element cannot be located on the page: + *

+ *   driver.findElement(By.id('not-there')).then(function(element) {
+ *     alert('Found an element that was not expected to be there!');
+ *   }, function(error) {
+ *     alert('The element was not found, as expected');
+ *   });
+ * 
+ */ +interface IWebElement { + // region Methods + + /** + * Schedules a command to click on this element. + * @return {!promise.Promise} A promise that will be resolved when + * the click command has completed. + */ + click(): promise.Promise; + + /** + * Schedules a command to type a sequence on the DOM element represented by + * this instance. + * + * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is + * processed in the key sequence, that key state is toggled until one of the + * following occurs: + * + * - The modifier key is encountered again in the sequence. At this point the + * state of the key is toggled (along with the appropriate keyup/down + * events). + * - The {@link input.Key.NULL} key is encountered in the sequence. When + * this key is encountered, all modifier keys current in the down state are + * released (with accompanying keyup events). The NULL key can be used to + * simulate common keyboard shortcuts: + * + * element.sendKeys('text was', + * Key.CONTROL, 'a', Key.NULL, + * 'now text is'); + * // Alternatively: + * element.sendKeys('text was', + * Key.chord(Key.CONTROL, 'a'), + * 'now text is'); + * + * - The end of the key sequence is encountered. When there are no more keys + * to type, all depressed modifier keys are released (with accompanying + * keyup events). + * + * If this element is a file input ({@code }), the + * specified key sequence should specify the path to the file to attach to + * the element. This is analogous to the user clicking 'Browse...' and entering + * the path into the file select dialog. + * + * var form = driver.findElement(By.css('form')); + * var element = form.findElement(By.css('input[type=file]')); + * element.sendKeys('/path/to/file.txt'); + * form.submit(); + * + * For uploads to function correctly, the entered path must reference a file + * on the _browser's_ machine, not the local machine running this script. When + * running against a remote Selenium server, a {@link input.FileDetector} + * may be used to transparently copy files to the remote machine before + * attempting to upload them in the browser. + * + * __Note:__ On browsers where native keyboard events are not supported + * (e.g. Firefox on OS X), key events will be synthesized. Special + * punctuation keys will be synthesized according to a standard QWERTY en-us + * keyboard layout. + * + * @param {...(number|string|!IThenable<(number|string)>)} var_args The + * sequence of keys to type. Number keys may be referenced numerically or + * by string (1 or '1'). All arguments will be joined into a single + * sequence. + * @return {!promise.Promise} A promise that will be resolved when all + * keys have been typed. + */ + sendKeys(...var_args: Array>): promise.Promise; + + /** + * Schedules a command to query for the tag/node name of this element. + * @return {!promise.Promise} A promise that will be resolved with the + * element's tag name. + */ + getTagName(): promise.Promise; + + /** + * Schedules a command to query for the computed style of the element + * represented by this instance. If the element inherits the named style from + * its parent, the parent will be queried for its value. Where possible, color + * values will be converted to their hex representation (e.g. #00ff00 instead of + * rgb(0, 255, 0)). + *

+ * Warning: the value returned will be as the browser interprets it, so + * it may be tricky to form a proper assertion. + * + * @param {string} cssStyleProperty The name of the CSS style property to look + * up. + * @return {!promise.Promise} A promise that will be resolved with the + * requested CSS value. + */ + getCssValue(cssStyleProperty: string): promise.Promise; + + /** + * Schedules a command to query for the value of the given attribute of the + * element. Will return the current value even if it has been modified after the + * page has been loaded. More exactly, this method will return the value of the + * given attribute, unless that attribute is not present, in which case the + * value of the property with the same name is returned. If neither value is + * set, null is returned. The 'style' attribute is converted as best can be to a + * text representation with a trailing semi-colon. The following are deemed to + * be 'boolean' attributes and will be returned as thus: + * + *

async, autofocus, autoplay, checked, compact, complete, controls, declare, + * defaultchecked, defaultselected, defer, disabled, draggable, ended, + * formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope, + * loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open, + * paused, pubdate, readonly, required, reversed, scoped, seamless, seeking, + * selected, spellcheck, truespeed, willvalidate + * + *

Finally, the following commonly mis-capitalized attribute/property names + * are evaluated as expected: + *

    + *
  • 'class' + *
  • 'readonly' + *
+ * @param {string} attributeName The name of the attribute to query. + * @return {!promise.Promise} A promise that will be resolved with the + * attribute's value. + */ + getAttribute(attributeName: string): promise.Promise; + + /** + * Get the visible (i.e. not hidden by CSS) innerText of this element, including + * sub-elements, without any leading or trailing whitespace. + * @return {!promise.Promise} A promise that will be resolved with the + * element's visible text. + */ + getText(): promise.Promise; + + /** + * Schedules a command to compute the size of this element's bounding box, in + * pixels. + * @return {!promise.Promise} A promise that will be resolved with the + * element's size as a {@code {width:number, height:number}} object. + */ + getSize(): promise.Promise; + + /** + * Schedules a command to compute the location of this element in page space. + * @return {!promise.Promise} A promise that will be resolved to the + * element's location as a {@code {x:number, y:number}} object. + */ + getLocation(): promise.Promise; + + /** + * Schedules a command to query whether the DOM element represented by this + * instance is enabled, as dicted by the {@code disabled} attribute. + * @return {!promise.Promise} A promise that will be resolved with + * whether this element is currently enabled. + */ + isEnabled(): promise.Promise; + + /** + * Schedules a command to query whether this element is selected. + * @return {!promise.Promise} A promise that will be resolved with + * whether this element is currently selected. + */ + isSelected(): promise.Promise; + + /** + * Schedules a command to submit the form containing this element (or this + * element if it is a FORM element). This command is a no-op if the element is + * not contained in a form. + * @return {!promise.Promise} A promise that will be resolved when + * the form has been submitted. + */ + submit(): promise.Promise; + + /** + * Schedules a command to clear the {@code value} of this element. This command + * has no effect if the underlying DOM element is neither a text INPUT element + * nor a TEXTAREA element. + * @return {!promise.Promise} A promise that will be resolved when + * the element has been cleared. + */ + clear(): promise.Promise; + + /** + * Schedules a command to test whether this element is currently displayed. + * @return {!promise.Promise} A promise that will be resolved with + * whether this element is currently visible on the page. + */ + isDisplayed(): promise.Promise; + + /** + * Schedules a command to retrieve the outer HTML of this element. + * @return {!promise.Promise} A promise that will be resolved with + * the element's outer HTML. + */ + getOuterHtml(): promise.Promise; + + /** + * @return {!promise.Promise.} A promise + * that resolves to this element's JSON representation as defined by the + * WebDriver wire protocol. + * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol + */ + getId(): promise.Promise; + + /** + * Schedules a command to retrieve the inner HTML of this element. + * @return {!promise.Promise} A promise that will be resolved with the + * element's inner HTML. + */ + getInnerHtml(): promise.Promise; + + // endregion +} + +interface IWebElementFinders { + /** + * Schedule a command to find a descendant of this element. If the element + * cannot be found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will + * be returned by the driver. Unlike other commands, this error cannot be + * suppressed. In other words, scheduling a command to find an element doubles + * as an assert that the element is present on the page. To test whether an + * element is present on the page, use {@code #isElementPresent} instead. + * + *

The search criteria for an element may be defined using one of the + * factories in the {@link By} namespace, or as a short-hand + * {@link By.Hash} object. For example, the following two statements + * are equivalent: + *

+   * var e1 = element.findElement(By.id('foo'));
+   * var e2 = element.findElement({id:'foo'});
+   * 
+ * + *

You may also provide a custom locator function, which takes as input + * this WebDriver instance and returns a {@link WebElement}, or a + * promise that will resolve to a WebElement. For example, to find the first + * visible link on a page, you could write: + *

+   * var link = element.findElement(firstVisibleLink);
+   *
+   * function firstVisibleLink(element) {
+   *   var links = element.findElements(By.tagName('a'));
+   *   return promise.filter(links, function(link) {
+   *     return links.isDisplayed();
+   *   }).then(function(visibleLinks) {
+   *     return visibleLinks[0];
+   *   });
+   * }
+   * 
+ * + * @param {!(Locator|By.Hash|Function)} locator The + * locator strategy to use when searching for the element. + * @return {!WebElement} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locator: By | Function): WebElementPromise; + + /** + * Schedules a command to test if there is at least one descendant of this + * element that matches the given search criteria. + * + * @param {!(Locator|By.Hash|Function)} locator The + * locator strategy to use when searching for the element. + * @return {!promise.Promise.} A promise that will be + * resolved with whether an element could be located on the page. + */ + isElementPresent(locator: By | Function): promise.Promise; + + /** + * Schedules a command to find all of the descendants of this element that + * match the given search criteria. + * + * @param {!(Locator|By.Hash|Function)} locator The + * locator strategy to use when searching for the elements. + * @return {!promise.Promise.>} A + * promise that will resolve to an array of WebElements. + */ + findElements(locator: By | Function): promise.Promise; +} + +/** + * Defines an object that can be asynchronously serialized to its WebDriver + * wire representation. + * + * @constructor + * @template T + */ +interface Serializable { + /** + * Returns either this instance's serialized represention, if immediately + * available, or a promise for its serialized representation. This function is + * conceptually equivalent to objects that have a {@code toJSON()} property, + * except the serialize() result may be a promise or an object containing a + * promise (which are not directly JSON friendly). + * + * @return {!(T|IThenable.)} This instance's serialized wire format. + */ + serialize(): T | promise.IThenable; +} + +/** + * Represents a DOM element. WebElements can be found by searching from the + * document root using a {@link WebDriver} instance, or by searching + * under another WebElement: + * + * driver.get('http://www.google.com'); + * var searchForm = driver.findElement(By.tagName('form')); + * var searchBox = searchForm.findElement(By.name('q')); + * searchBox.sendKeys('webdriver'); + * + * The WebElement is implemented as a promise for compatibility with the promise + * API. It will always resolve itself when its internal state has been fully + * resolved and commands may be issued against the element. This can be used to + * catch errors when an element cannot be located on the page: + * + * driver.findElement(By.id('not-there')).then(function(element) { + * alert('Found an element that was not expected to be there!'); + * }, function(error) { + * alert('The element was not found, as expected'); + * }); + * + * @extends {Serializable.} + */ +export class WebElement implements Serializable { + /** + * @param {!WebDriver} driver the parent WebDriver instance for this element. + * @param {(!IThenable|string)} id The server-assigned opaque ID for + * the underlying DOM element. + */ + constructor(driver: WebDriver, id: promise.Promise | string); + + /** + * @param {string} id The raw ID. + * @param {boolean=} opt_noLegacy Whether to exclude the legacy element key. + * @return {!Object} The element ID for use with WebDriver's wire protocol. + */ + static buildId(id: string, opt_noLegacy?: boolean): Object; + + /** + * Extracts the encoded WebElement ID from the object. + * + * @param {?} obj The object to extract the ID from. + * @return {string} the extracted ID. + * @throws {TypeError} if the object is not a valid encoded ID. + */ + static extractId(obj: IWebElementId): string; + + /** + * @param {?} obj the object to test. + * @return {boolean} whether the object is a valid encoded WebElement ID. + */ + static isId(obj: IWebElementId): boolean; + + /** + * Compares two WebElements for equality. + * + * @param {!WebElement} a A WebElement. + * @param {!WebElement} b A WebElement. + * @return {!promise.Promise} A promise that will be + * resolved to whether the two WebElements are equal. + */ + static equals(a: WebElement, b: WebElement): promise.Promise; + + /** + * @return {!WebDriver} The parent driver for this instance. + */ + getDriver(): WebDriver; + + /** + * @return {!promise.Promise} A promise that resolves to + * the server-assigned opaque ID assigned to this element. + */ + getId(): promise.Promise; + + /** + * @deprecated Use {@link #getId()} instead. + */ + getRawId(): any; + + /** + * Schedule a command to find a descendant of this element. If the element + * cannot be found, a {@link bot.ErrorCode.NO_SUCH_ELEMENT} result will + * be returned by the driver. Unlike other commands, this error cannot be + * suppressed. In other words, scheduling a command to find an element doubles + * as an assert that the element is present on the page. To test whether an + * element is present on the page, use {@link #isElementPresent} instead. + * + * The search criteria for an element may be defined using one of the + * factories in the {@link By} namespace, or as a short-hand + * {@link By.Hash} object. For example, the following two statements + * are equivalent: + * + * var e1 = element.findElement(By.id('foo')); + * var e2 = element.findElement({id:'foo'}); + * + * You may also provide a custom locator function, which takes as input + * this WebDriver instance and returns a {@link WebElement}, or a + * promise that will resolve to a WebElement. For example, to find the first + * visible link on a page, you could write: + * + * var link = element.findElement(firstVisibleLink); + * + * function firstVisibleLink(element) { + * var links = element.findElements(By.tagName('a')); + * return promise.filter(links, function(link) { + * return links.isDisplayed(); + * }).then(function(visibleLinks) { + * return visibleLinks[0]; + * }); + * } + * + * @param {!(by.By|Function)} locator The locator strategy to use when + * searching for the element. + * @return {!WebElementPromise} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locator: By | Function): WebElementPromise; + + /** + * Schedules a command to test if there is at least one descendant of this + * element that matches the given search criteria. + * + * @param {!(by.By|Function)} locator The locator strategy to use when + * searching for the element. + * @return {!promise.Promise} A promise that will be + * resolved with whether an element could be located on the page. + * @deprecated This method will be removed in Selenium 3.0 for consistency + * with the other Selenium language bindings. This method is equivalent + * to + * + * element.findElements(locator).then(e => !!e.length); + */ + isElementPresent(locator: By | Function): promise.Promise; + + /** + * Schedules a command to find all of the descendants of this element that + * match the given search criteria. + * + * @param {!(by.By|Function)} locator The locator strategy to use when + * searching for the element. + * @return {!promise.Promise>} A + * promise that will resolve to an array of WebElements. + */ + findElements(locator: By | Function): promise.Promise; + + /** + * Schedules a command to click on this element. + * @return {!promise.Promise.} A promise that will be resolved + * when the click command has completed. + */ + click(): promise.Promise; + + /** + * Schedules a command to type a sequence on the DOM element represented by this + * promsieinstance. + * + * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is + * processed in the keysequence, that key state is toggled until one of the + * following occurs: + * + * - The modifier key is encountered again in the sequence. At this point the + * state of the key is toggled (along with the appropriate keyup/down events). + * - The {@link Key.NULL} key is encountered in the sequence. When + * this key is encountered, all modifier keys current in the down state are + * released (with accompanying keyup events). The NULL key can be used to + * simulate common keyboard shortcuts: + * + * element.sendKeys('text was', + * Key.CONTROL, 'a', Key.NULL, + * 'now text is'); + * // Alternatively: + * element.sendKeys('text was', + * Key.chord(Key.CONTROL, 'a'), + * 'now text is'); + * + * - The end of the keysequence is encountered. When there are no more keys + * to type, all depressed modifier keys are released (with accompanying keyup + * events). + * + * If this element is a file input ({@code }), the + * specified key sequence should specify the path to the file to attach to + * the element. This is analgous to the user clicking 'Browse...' and entering + * the path into the file select dialog. + * + * var form = driver.findElement(By.css('form')); + * var element = form.findElement(By.css('input[type=file]')); + * element.sendKeys('/path/to/file.txt'); + * form.submit(); + * + * For uploads to function correctly, the entered path must reference a file + * on the _browser's_ machine, not the local machine running this script. When + * running against a remote Selenium server, a {@link FileDetector} + * may be used to transparently copy files to the remote machine before + * attempting to upload them in the browser. + * + * __Note:__ On browsers where native keyboard events are not supported + * (e.g. Firefox on OS X), key events will be synthesized. Special + * punctionation keys will be synthesized according to a standard QWERTY en-us + * keyboard layout. + * + * @param {...(string|!promise.Promise)} var_args The sequence + * of keys to type. All arguments will be joined into a single sequence. + * @return {!promise.Promise.} A promise that will be resolved + * when all keys have been typed. + */ + sendKeys(...var_args: Array>): promise.Promise; + + /** + * Schedules a command to query for the tag/node name of this element. + * @return {!promise.Promise.} A promise that will be + * resolved with the element's tag name. + */ + getTagName(): promise.Promise; + + /** + * Schedules a command to query for the computed style of the element + * represented by this instance. If the element inherits the named style from + * its parent, the parent will be queried for its value. Where possible, color + * values will be converted to their hex representation (e.g. #00ff00 instead of + * rgb(0, 255, 0)). + * + * _Warning:_ the value returned will be as the browser interprets it, so + * it may be tricky to form a proper assertion. + * + * @param {string} cssStyleProperty The name of the CSS style property to look + * up. + * @return {!promise.Promise} A promise that will be + * resolved with the requested CSS value. + */ + getCssValue(cssStyleProperty: string): promise.Promise; + + /** + * Schedules a command to query for the value of the given attribute of the + * element. Will return the current value, even if it has been modified after + * the page has been loaded. More exactly, this method will return the value of + * the given attribute, unless that attribute is not present, in which case the + * value of the property with the same name is returned. If neither value is + * set, null is returned (for example, the 'value' property of a textarea + * element). The 'style' attribute is converted as best can be to a + * text representation with a trailing semi-colon. The following are deemed to + * be 'boolean' attributes and will return either 'true' or null: + * + * async, autofocus, autoplay, checked, compact, complete, controls, declare, + * defaultchecked, defaultselected, defer, disabled, draggable, ended, + * formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope, + * loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open, + * paused, pubdate, readonly, required, reversed, scoped, seamless, seeking, + * selected, spellcheck, truespeed, willvalidate + * + * Finally, the following commonly mis-capitalized attribute/property names + * are evaluated as expected: + * + * - 'class' + * - 'readonly' + * + * @param {string} attributeName The name of the attribute to query. + * @return {!promise.Promise.} A promise that will be + * resolved with the attribute's value. The returned value will always be + * either a string or null. + */ + getAttribute(attributeName: string): promise.Promise; + + /** + * Get the visible (i.e. not hidden by CSS) innerText of this element, including + * sub-elements, without any leading or trailing whitespace. + * @return {!promise.Promise.} A promise that will be + * resolved with the element's visible text. + */ + getText(): promise.Promise; + + /** + * Schedules a command to compute the size of this element's bounding box, in + * pixels. + * @return {!promise.Promise.<{width: number, height: number}>} A + * promise that will be resolved with the element's size as a + * {@code {width:number, height:number}} object. + */ + getSize(): promise.Promise; + + /** + * Schedules a command to compute the location of this element in page space. + * @return {!promise.Promise.<{x: number, y: number}>} A promise that + * will be resolved to the element's location as a + * {@code {x:number, y:number}} object. + */ + getLocation(): promise.Promise; + + /** + * Schedules a command to query whether the DOM element represented by this + * instance is enabled, as dicted by the {@code disabled} attribute. + * @return {!promise.Promise.} A promise that will be + * resolved with whether this element is currently enabled. + */ + isEnabled(): promise.Promise; + + /** + * Schedules a command to query whether this element is selected. + * @return {!promise.Promise.} A promise that will be + * resolved with whether this element is currently selected. + */ + isSelected(): promise.Promise; + + /** + * Schedules a command to submit the form containing this element (or this + * element if it is a FORM element). This command is a no-op if the element is + * not contained in a form. + * @return {!promise.Promise.} A promise that will be resolved + * when the form has been submitted. + */ + submit(): promise.Promise; + + /** + * Schedules a command to clear the `value` of this element. This command has + * no effect if the underlying DOM element is neither a text INPUT element + * nor a TEXTAREA element. + * @return {!promise.Promise} A promise that will be resolved + * when the element has been cleared. + */ + clear(): promise.Promise; + + /** + * Schedules a command to test whether this element is currently displayed. + * @return {!promise.Promise.} A promise that will be + * resolved with whether this element is currently visible on the page. + */ + isDisplayed(): promise.Promise; + + /** + * Take a screenshot of the visible region encompassed by this element's + * bounding rectangle. + * + * @param {boolean=} opt_scroll Optional argument that indicates whether the + * element should be scrolled into view before taking a screenshot. + * Defaults to false. + * @return {!promise.Promise} A promise that will be + * resolved to the screenshot as a base-64 encoded PNG. + */ + takeScreenshot(opt_scroll?: boolean): promise.Promise; + + /** + * Schedules a command to retrieve the outer HTML of this element. + * @return {!promise.Promise.} A promise that will be + * resolved with the element's outer HTML. + */ + getOuterHtml(): promise.Promise; + + /** + * Schedules a command to retrieve the inner HTML of this element. + * @return {!promise.Promise} A promise that will be resolved with the + * element's inner HTML. + */ + getInnerHtml(): promise.Promise; + + /** @override */ + serialize(): promise.Promise; +} + +/** + * WebElementPromise is a promise that will be fulfilled with a WebElement. + * This serves as a forward proxy on WebElement, allowing calls to be + * scheduled without directly on this instance before the underlying + * WebElement has been fulfilled. In other words, the following two statements + * are equivalent: + *

+ *     driver.findElement({id: 'my-button'}).click();
+ *     driver.findElement({id: 'my-button'}).then(function(el) {
+ *       return el.click();
+ *     });
+ * 
+ * + * @param {!WebDriver} driver The parent WebDriver instance for this + * element. + * @param {!promise.Promise.} el A promise + * that will resolve to the promised element. + * @constructor + * @extends {WebElement} + * @implements {promise.Thenable.} + * @final + */ +export class WebElementPromise extends WebElement implements promise.IThenable { + /** + * @param {!WebDriver} driver The parent WebDriver instance for this + * element. + * @param {!promise.Promise} el A promise + * that will resolve to the promised element. + */ + constructor(driver: WebDriver, el: promise.Promise); + + /** + * Cancels the computation of this promise's value, rejecting the promise in the + * process. This method is a no-op if the promise has alreayd been resolved. + * + * @param {string=} opt_reason The reason this promise is being cancelled. + */ + cancel(opt_reason?: string): void; + + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + + /** + * Registers listeners for when this instance is resolved. + * + * @param opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param opt_errback The + * function to call if this promise is rejected. The function should expect + * a single argument: the rejection reason. + * @return A new promise which will be + * resolved with the result of the invoked callback. + */ + then(opt_callback?: (value: WebElement) => promise.Promise, opt_errback?: (error: any) => any): promise.Promise; + + /** + * Registers listeners for when this instance is resolved. + * + * @param opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param opt_errback The + * function to call if this promise is rejected. The function should expect + * a single argument: the rejection reason. + * @return A new promise which will be + * resolved with the result of the invoked callback. + */ + then(opt_callback?: (value: WebElement) => R, opt_errback?: (error: any) => any): promise.Promise; + + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + *

+   *   // Synchronous API:
+   *   try {
+   *     doSynchronousWork();
+   *   } catch (ex) {
+   *     console.error(ex);
+   *   }
+   *
+   *   // Asynchronous promise API:
+   *   doAsynchronousWork().thenCatch(function(ex) {
+   *     console.error(ex);
+   *   });
+   * 
+ * + * @param {function(*): (R|promise.Promise.)} errback The function + * to call if this promise is rejected. The function should expect a single + * argument: the rejection reason. + * @return {!promise.Promise.} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + thenCatch(errback: (error: any) => any): promise.Promise; + + + /** + * Registers a listener to invoke when this promise is resolved, regardless + * of whether the promise's value was successfully computed. This function + * is synonymous with the {@code finally} clause in a synchronous API: + *

+   *   // Synchronous API:
+   *   try {
+   *     doSynchronousWork();
+   *   } finally {
+   *     cleanUp();
+   *   }
+   *
+   *   // Asynchronous promise API:
+   *   doAsynchronousWork().thenFinally(cleanUp);
+   * 
+ * + * Note: similar to the {@code finally} clause, if the registered + * callback returns a rejected promise or throws an error, it will silently + * replace the rejection error (if any) from this promise: + *

+   *   try {
+   *     throw Error('one');
+   *   } finally {
+   *     throw Error('two');  // Hides Error: one
+   *   }
+   *
+   *   promise.rejected(Error('one'))
+   *       .thenFinally(function() {
+   *         throw Error('two');  // Hides Error: one
+   *       });
+   * 
+ * + * + * @param {function(): (R|promise.Promise.)} callback The function + * to call when this promise is resolved. + * @return {!promise.Promise.} A promise that will be fulfilled + * with the callback result. + * @template R + */ + thenFinally(callback: () => any): promise.Promise; + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + * + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } + * + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); + * + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + catch(errback: Function): promise.Promise; +} + +/** + * Contains information about a WebDriver session. + */ +export class Session { + + // region Constructors + + /** + * @param {string} id The session ID. + * @param {!(Object|Capabilities)} capabilities The session + * capabilities. + * @constructor + */ + constructor(id: string, capabilities: Capabilities | Object); + + // endregion + + // region Methods + + /** + * @return {string} This session's ID. + */ + getId(): string; + + /** + * @return {!Capabilities} This session's capabilities. + */ + getCapabilities(): Capabilities; + + /** + * Retrieves the value of a specific capability. + * @param {string} key The capability to retrieve. + * @return {*} The capability value. + */ + getCapability(key: string): any; + + /** + * Returns the JSON representation of this object, which is just the string + * session ID. + * @return {string} The JSON representation of this Session. + */ + toJSON(): string; + + // endregion +} diff --git a/selenium-webdriver/v2/opera.d.ts b/selenium-webdriver/v2/opera.d.ts new file mode 100644 index 0000000000..9976995e65 --- /dev/null +++ b/selenium-webdriver/v2/opera.d.ts @@ -0,0 +1,174 @@ +/* tslint:disable */ +import * as webdriver from './index'; +import * as remote from './remote'; + +/** + * Creates {@link remote.DriverService} instances that manages an + * [OperaDriver](https://github.com/operasoftware/operachromiumdriver) + * server in a child process. + */ +export class ServiceBuilder { + /** + * @param {string=} opt_exe Path to the server executable to use. If omitted, + * the builder will attempt to locate the operadriver on the current + * PATH. + * @throws {Error} If provided executable does not exist, or the operadriver + * cannot be found on the PATH. + */ + constructor(opt_exe?: string); + + /** + * Sets the port to start the OperaDriver on. + * @param {number} port The port to use, or 0 for any free port. + * @return {!ServiceBuilder} A self reference. + * @throws {Error} If the port is invalid. + */ + usingPort(port: number): ServiceBuilder; + + /** + * Sets the path of the log file the driver should log to. If a log file is + * not specified, the driver will log to stderr. + * @param {string} path Path of the log file to use. + * @return {!ServiceBuilder} A self reference. + */ + loggingTo(path: string): ServiceBuilder; + + /** + * Enables verbose logging. + * @return {!ServiceBuilder} A self reference. + */ + enableVerboseLogging(): ServiceBuilder; + + /** + * Silence sthe drivers output. + * @return {!ServiceBuilder} A self reference. + */ + silent(): ServiceBuilder; + + /** + * Defines the stdio configuration for the driver service. See + * {@code child_process.spawn} for more information. + * @param {(string|!Array)} + * config The configuration to use. + * @return {!ServiceBuilder} A self reference. + */ + setStdio(config: string | Array): ServiceBuilder; + + /** + * Defines the environment to start the server under. This settings will be + * inherited by every browser session started by the server. + * @param {!Object.} env The environment to use. + * @return {!ServiceBuilder} A self reference. + */ + withEnvironment(env: Object): ServiceBuilder; + + /** + * Creates a new DriverService using this instance's current configuration. + * @return {!remote.DriverService} A new driver service using this instance's + * current configuration. + * @throws {Error} If the driver exectuable was not specified and a default + * could not be found on the current PATH. + */ + build(): remote.DriverService; +} + +/** + * Sets the default service to use for new OperaDriver instances. + * @param {!remote.DriverService} service The service to use. + * @throws {Error} If the default service is currently running. + */ +export function setDefaultService(service: remote.DriverService): any; + +/** + * Returns the default OperaDriver service. If such a service has not been + * configured, one will be constructed using the default configuration for + * a OperaDriver executable found on the system PATH. + * @return {!remote.DriverService} The default OperaDriver service. + */ +export function getDefaultService(): remote.DriverService; + +/** + * Class for managing {@linkplain Driver OperaDriver} specific options. + */ +export class Options { + /** + * Extracts the OperaDriver specific options from the given capabilities + * object. + * @param {!capabilities.Capabilities} caps The capabilities object. + * @return {!Options} The OperaDriver options. + */ + static fromCapabilities(caps: webdriver.Capabilities): Options; + + /** + * Add additional command line arguments to use when launching the Opera + * browser. Each argument may be specified with or without the '--' prefix + * (e.g. '--foo' and 'foo'). Arguments with an associated value should be + * delimited by an '=': 'foo=bar'. + * @param {...(string|!Array.)} var_args The arguments to add. + * @return {!Options} A self reference. + */ + addArguments(...var_args: string[]): Options; + + /** + * Add additional extensions to install when launching Opera. Each extension + * should be specified as the path to the packed CRX file, or a Buffer for an + * extension. + * @param {...(string|!Buffer|!Array.<(string|!Buffer)>)} var_args The + * extensions to add. + * @return {!Options} A self reference. + */ + addExtensions(...var_args: any[]): Options; + + /** + * Sets the path to the Opera binary to use. On Mac OS X, this path should + * reference the actual Opera executable, not just the application binary. The + * binary path be absolute or relative to the operadriver server executable, but + * it must exist on the machine that will launch Opera. + * + * @param {string} path The path to the Opera binary to use. + * @return {!Options} A self reference. + */ + setOperaBinaryPath(path: string): Options; + + /** + * Sets the logging preferences for the new session. + * @param {!./lib/logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPrefs(prefs: webdriver.logging.Preferences): Options; + + /** + * Sets the proxy settings for the new session. + * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + /** + * Converts this options instance to a {@link capabilities.Capabilities} + * object. + * @param {capabilities.Capabilities=} opt_capabilities The capabilities to + * merge these options into, if any. + * @return {!capabilities.Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities?: webdriver.Capabilities): webdriver.Capabilities; +} + +export class Driver extends webdriver.WebDriver { + /** + * @param {(capabilities.Capabilities|Options)=} opt_config The configuration + * options. + * @param {remote.DriverService=} opt_service The session to use; will use + * the {@link getDefaultService default service} by default. + * @param {promise.ControlFlow=} opt_flow The control flow to use, + * or {@code null} to use the currently active flow. + */ + constructor(opt_config?: webdriver.Capabilities | Options, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); + + /** + * This function is a no-op as file detectors are not supported by this + * implementation. + * @override + */ + setFileDetector(): void; +} diff --git a/selenium-webdriver/v2/remote.d.ts b/selenium-webdriver/v2/remote.d.ts new file mode 100644 index 0000000000..de31a0fbe7 --- /dev/null +++ b/selenium-webdriver/v2/remote.d.ts @@ -0,0 +1,106 @@ +/* tslint:disable */ +import * as webdriver from './index'; + +/** + * A record object that defines the configuration options for a DriverService + * instance. + * + * @record + */ +interface ServiceOptions { } + +/** + * Manages the life and death of a native executable WebDriver server. + * + * It is expected that the driver server implements the + * https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol. + * Furthermore, the managed server should support multiple concurrent sessions, + * so that this class may be reused for multiple clients. + */ +export class DriverService { + /** + * @param {string} executable Path to the executable to run. + * @param {!ServiceOptions} options Configuration options for the service. + */ + constructor(executable: string, options: ServiceOptions); + + /** + * @return {!promise.Promise} A promise that resolves to + * the server's address. + * @throws {Error} If the server has not been started. + */ + address(): webdriver.promise.Promise; + + /** + * Returns whether the underlying process is still running. This does not take + * into account whether the process is in the process of shutting down. + * @return {boolean} Whether the underlying service process is running. + */ + isRunning(): boolean; + + /** + * Starts the server if it is not already running. + * @param {number=} opt_timeoutMs How long to wait, in milliseconds, for the + * server to start accepting requests. Defaults to 30 seconds. + * @return {!promise.Promise} A promise that will resolve + * to the server's base URL when it has started accepting requests. If the + * timeout expires before the server has started, the promise will be + * rejected. + */ + start(opt_timeoutMs?: number): webdriver.promise.Promise; + + /** + * Stops the service if it is not currently running. This function will kill + * the server immediately. To synchronize with the active control flow, use + * {@link #stop()}. + * @return {!promise.Promise} A promise that will be resolved when + * the server has been stopped. + */ + kill(): webdriver.promise.Promise; + + /** + * Schedules a task in the current control flow to stop the server if it is + * currently running. + * @return {!promise.Promise} A promise that will be resolved when + * the server has been stopped. + */ + stop(): webdriver.promise.Promise; +} + +/** + * A {@link webdriver.FileDetector} that may be used when running + * against a remote + * [Selenium server](http://selenium-release.storage.googleapis.com/index.html). + * + * When a file path on the local machine running this script is entered with + * {@link webdriver.WebElement#sendKeys WebElement#sendKeys}, this file detector + * will transfer the specified file to the Selenium server's host; the sendKeys + * command will be updated to use the transfered file's path. + * + * __Note:__ This class depends on a non-standard command supported on the + * Java Selenium server. The file detector will fail if used with a server that + * only supports standard WebDriver commands (such as the ChromeDriver). + * + * @final + */ +export class FileDetector extends webdriver.FileDetector { + /** + * @constructor + **/ + constructor(); + + /** + * Prepares a `file` for use with the remote browser. If the provided path + * does not reference a normal file (i.e. it does not exist or is a + * directory), then the promise returned by this method will be resolved with + * the original file path. Otherwise, this method will upload the file to the + * remote server, which will return the file's path on the remote system so + * it may be referenced in subsequent commands. + * + * @param {!webdriver.WebDriver} driver The driver for the current browser. + * @param {string} file The path of the file to process. + * @return {!webdriver.promise.Promise} A promise for the processed + * file path. + */ + handleFile(driver: webdriver.WebDriver, file: string): webdriver.promise.Promise; +} diff --git a/selenium-webdriver/v2/safari.d.ts b/selenium-webdriver/v2/safari.d.ts new file mode 100644 index 0000000000..0633f9f782 --- /dev/null +++ b/selenium-webdriver/v2/safari.d.ts @@ -0,0 +1,90 @@ +/* tslint:disable */ +import * as webdriver from './index'; + +export class Server { } + +/** + * @return {!Promise} A promise that will resolve with the path + * to Safari on the current system. + */ +export function findSafariExecutable(): any; + +/** + * @param {string} serverUrl The URL to connect to. + * @return {!Promise} A promise for the path to a file that Safari can + * open on start-up to trigger a new connection to the WebSocket server. + */ +export function createConnectFile(serverUrl: string): any; + +/** + * Deletes all session data files if so desired. + * @param {!Object} desiredCapabilities . + * @return {!Array} A list of promises for the deleted files. + */ +export function cleanSession(desiredCapabilities: webdriver.Capabilities): any[]; + +/** @return {string} . */ +export function getRandomString(): string; + +/** + * @implements {command.Executor} + */ +export class CommandExecutor { +} + +/** + * Configuration options specific to the {@link Driver SafariDriver}. + */ +export class Options { + /** + * Extracts the SafariDriver specific options from the given capabilities + * object. + * @param {!Capabilities} capabilities The capabilities object. + * @return {!Options} The ChromeDriver options. + */ + static fromCapabilities(capabilities: webdriver.Capabilities): Options; + + /** + * Sets whether to force Safari to start with a clean session. Enabling this + * option will cause all global browser data to be deleted. + * @param {boolean} clean Whether to make sure the session has no cookies, + * cache entries, local storage, or databases. + * @return {!Options} A self reference. + */ + setCleanSession(clean: boolean): Options; + + /** + * Sets the logging preferences for the new session. + * @param {!./lib/logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPrefs(prefs: webdriver.logging.Preferences): Options; + + /** + * Converts this options instance to a {@link Capabilities} object. + * @param {Capabilities=} opt_capabilities The capabilities to + * merge these options into, if any. + * @return {!Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; +} + +/** + * A WebDriver client for Safari. This class should never be instantiated + * directly; instead, use the {@linkplain ./builder.Builder Builder}: + * + * var driver = new Builder() + * .forBrowser('safari') + * .build(); + * + */ +export class Driver extends webdriver.WebDriver { + /** + * @param {(Options|Capabilities)=} opt_config The configuration + * options for the new session. + * @param {promise.ControlFlow=} opt_flow The control flow to create + * the driver under. + */ + constructor(opt_config?: Options | webdriver.Capabilities, opt_flow?: webdriver.promise.ControlFlow); + +} diff --git a/selenium-webdriver/v2/test/chrome.ts b/selenium-webdriver/v2/test/chrome.ts new file mode 100644 index 0000000000..f9c896fbee --- /dev/null +++ b/selenium-webdriver/v2/test/chrome.ts @@ -0,0 +1,62 @@ +/* tslint:disable */ +import * as chrome from 'selenium-webdriver/chrome'; +import * as remote from 'selenium-webdriver/remote'; +import * as webdriver from 'selenium-webdriver'; + +function TestChromeDriver() { + var driver: chrome.Driver = new chrome.Driver(); + driver = new chrome.Driver(webdriver.Capabilities.chrome()); + driver = new chrome.Driver(webdriver.Capabilities.chrome(), + new remote.DriverService('executable', new chrome.Options()), + new webdriver.promise.ControlFlow()); + + var baseDriver: webdriver.WebDriver = driver; +} + +function TestChromeOptions() { + var options: chrome.Options = new chrome.Options(); + options = chrome.Options.fromCapabilities(webdriver.Capabilities.chrome()); + + options = options.addArguments('a', 'b', 'c'); + options = options.addExtensions('a', 'b', 'c'); + options = options.excludeSwitches('a', 'b', 'c'); + options = options.detachDriver(true); + options = options.setChromeBinaryPath('path'); + options = options.setChromeLogFile('logfile'); + options = options.setLocalState('state'); + options = options.androidActivity('com.example.Activity'); + options = options.androidDeviceSerial('emulator-5554'); + options = options.androidChrome(); + options = options.androidPackage('com.android.chrome'); + options = options.androidProcess('com.android.chrome'); + options = options.androidUseRunningApp(true); + options = options.setLoggingPrefs(new webdriver.logging.Preferences()); + options = options.setPerfLoggingPrefs({ + enableNetwork: true, enablePage: true, enableTimeline: true, + tracingCategories: 'category', bufferUsageReportingInterval: 1000 }); + options = options.setProxy({ proxyType: 'proxyType' }); + options = options.setUserPreferences('preferences'); + var capabilities: webdriver.Capabilities = options.toCapabilities(); + capabilities = options.toCapabilities(webdriver.Capabilities.chrome()); +} + +function TestServiceBuilder() { + var builder: chrome.ServiceBuilder = new chrome.ServiceBuilder(); + builder = new chrome.ServiceBuilder('exe'); + + var anything: any = builder.build(); + builder = builder.usingPort(8080); + builder = builder.setAdbPort(5037); + builder = builder.loggingTo('path'); + builder = builder.enableVerboseLogging(); + builder = builder.setNumHttpThreads(5); + builder = builder.setUrlBasePath('path'); + builder = builder.setStdio('config'); + builder = builder.setStdio(['A', 'B']); + builder = builder.withEnvironment({ A: 'a', B: 'b' }); +} + +function TestChromeModule() { + var service: any = chrome.getDefaultService(); + chrome.setDefaultService(new remote.DriverService('executable', new chrome.Options())); +} diff --git a/selenium-webdriver/v2/test/firefox.ts b/selenium-webdriver/v2/test/firefox.ts new file mode 100644 index 0000000000..2f3aeb928c --- /dev/null +++ b/selenium-webdriver/v2/test/firefox.ts @@ -0,0 +1,55 @@ +/* tslint:disable */ +import * as firefox from 'selenium-webdriver/firefox'; +import * as remote from 'selenium-webdriver/remote'; +import * as webdriver from 'selenium-webdriver'; + +function TestBinary() { + var binary: firefox.Binary = new firefox.Binary(); + binary = new firefox.Binary('exe'); + + binary.addArguments('A', 'B', 'C'); + var promise: webdriver.promise.Promise = binary.kill(); + binary.launch('profile').then((result: any) => {}); +} + +function TestFirefoxDriver() { + var driver: firefox.Driver = new firefox.Driver(); + driver = new firefox.Driver(webdriver.Capabilities.firefox()); + driver = new firefox.Driver(webdriver.Capabilities.firefox(), new webdriver.promise.ControlFlow()); + + var baseDriver: webdriver.WebDriver = driver; +} + +function TestFirefoxOptions() { + var options: firefox.Options = new firefox.Options(); + + options = options.setBinary('binary'); + options = options.setBinary(new firefox.Binary()); + options = options.setLoggingPreferences(new webdriver.logging.Preferences()); + options = options.setProfile('profile'); + options = options.setProfile(new firefox.Profile()); + options = options.setProxy({ proxyType: 'proxy' }); + var capabilities: webdriver.Capabilities = options.toCapabilities(); +} + +function TestFirefoxProfile() { + var profile: firefox.Profile = new firefox.Profile(); + profile = new firefox.Profile('dir'); + + var bool: boolean = profile.acceptUntrustedCerts(); + profile.addExtension('ext'); + bool = profile.assumeUntrustedCertIssuer(); + profile.encode().then((prof: string) => {}); + var num: number = profile.getPort(); + var anything: any = profile.getPreference('key'); + bool = profile.nativeEventsEnabled(); + profile.setAcceptUntrustedCerts(true); + profile.setAssumeUntrustedCertIssuer(true); + profile.setNativeEventsEnabled(true); + profile.setPort(8080); + profile.setPreference('key', 'value'); + profile.setPreference('key', 5); + profile.setPreference('key', true); + var stringPromise: webdriver.promise.Promise = profile.writeToDisk(); + stringPromise = profile.writeToDisk(true); +} diff --git a/selenium-webdriver/v2/test/index.ts b/selenium-webdriver/v2/test/index.ts new file mode 100644 index 0000000000..ba783f86fc --- /dev/null +++ b/selenium-webdriver/v2/test/index.ts @@ -0,0 +1,1051 @@ +/* tslint:disable */ +import * as webdriver from 'selenium-webdriver'; +import * as chrome from 'selenium-webdriver/chrome'; +import * as firefox from 'selenium-webdriver/firefox'; +import * as remote from 'selenium-webdriver/remote'; +import * as executors from 'selenium-webdriver/executors'; +import * as testing from 'selenium-webdriver/testing'; + +function TestExecutors() { + var exec: webdriver.Executor = executors.createExecutor('url'); + var promise: webdriver.promise.Promise; + exec = executors.createExecutor(promise); +} + +function TestBuilder() { + var builder: webdriver.Builder = new webdriver.Builder(); + + var driver: webdriver.WebDriver = builder.build(); + builder = builder.forBrowser('name'); + builder = builder.forBrowser('name', 'version'); + builder = builder.forBrowser('name', 'version', 'platform'); + + var cap: webdriver.Capabilities = builder.getCapabilities(); + var str: string = builder.getServerUrl(); + + builder = builder.setAlertBehavior('behavior'); + builder = builder.setChromeOptions(new chrome.Options()); + builder = builder.setControlFlow(new webdriver.promise.ControlFlow()); + builder = builder.setEnableNativeEvents(true); + builder = builder.setFirefoxOptions(new firefox.Options()); + builder = builder.setLoggingPrefs(new webdriver.logging.Preferences()); + builder = builder.setLoggingPrefs({ key: 'value' }); + builder = builder.setProxy({ proxyType: 'type' }); + builder = builder.setScrollBehavior(1); + builder = builder.usingServer('http://someserver'); + builder = builder.withCapabilities(new webdriver.Capabilities()); + builder = builder.withCapabilities({ something: true }); +} + +function TestActionSequence() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var sequence: webdriver.ActionSequence = new webdriver.ActionSequence(driver); + var element: webdriver.WebElement = new webdriver.WebElement(driver, 'elementId'); + var promise: webdriver.promise.Promise; + element = new webdriver.WebElement(driver, promise); + + // Click + sequence = sequence.click(); + sequence = sequence.click(webdriver.Button.LEFT); + sequence = sequence.click(element); + sequence = sequence.click(element, webdriver.Button.LEFT); + + // DoubleClick + sequence = sequence.doubleClick(); + sequence = sequence.doubleClick(webdriver.Button.LEFT); + sequence = sequence.doubleClick(element); + sequence = sequence.doubleClick(element, webdriver.Button.LEFT); + + // DragAndDrop + sequence = sequence.dragAndDrop(element, element); + sequence = sequence.dragAndDrop(element, { x: 1, y: 2 }); + + // KeyDown + sequence = sequence.keyDown(webdriver.Key.ADD); + + // KeyUp + sequence = sequence.keyUp(webdriver.Key.ADD); + + // MouseDown + sequence = sequence.mouseDown(); + sequence = sequence.mouseDown(webdriver.Button.LEFT); + sequence = sequence.mouseDown(element); + sequence = sequence.mouseDown(element, webdriver.Button.LEFT); + + // MouseMove + sequence = sequence.mouseMove(element); + sequence = sequence.mouseMove({ x: 1, y: 1 }); + sequence = sequence.mouseMove(element, { x: 1, y: 2 }); + + // MouseUp + sequence = sequence.mouseUp(); + sequence = sequence.mouseUp(webdriver.Button.LEFT); + sequence = sequence.mouseUp(element); + sequence = sequence.mouseUp(element, webdriver.Button.LEFT); + + // SendKeys + sequence = sequence.sendKeys('A', 'B', 'C'); + sequence = sequence.sendKeys('A', webdriver.Key.NULL); + + sequence.perform().then(() => {}); +} + +function TestTouchSequence() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + var element: webdriver.WebElement = new webdriver.WebElement(driver, 'elementId'); + + var sequence: webdriver.TouchSequence = new webdriver.TouchSequence(driver); + + sequence = sequence.tap(element); + sequence = sequence.doubleTap(element); + sequence = sequence.longPress(element); + sequence = sequence.tapAndHold({ x: 100, y: 100 }); + sequence = sequence.move({ x: 100, y: 100 }); + sequence = sequence.release({ x: 100, y: 100 }); + sequence = sequence.scroll({ x: 100, y: 100 }); + sequence = sequence.scrollFromElement(element, { x: 100, y: 100 }); + sequence = sequence.flick({ xspeed: 100, yspeed: 100 }); + sequence = sequence.flickElement(element, { x: 100, y: 100 }, 100); + + sequence.perform().then(() => {}); +} + +function TestAlert() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var alert: webdriver.Alert = driver.switchTo().alert(); + + alert.accept().then(() => {}); + alert.dismiss().then(() => {}); + alert.getText().then((text: string) => {}); + alert.sendKeys('ABC').then(() => {}); +} + +function TestBrowser() { + var browser: string; + + browser = webdriver.Browser.ANDROID; + browser = webdriver.Browser.CHROME; + browser = webdriver.Browser.FIREFOX; + browser = webdriver.Browser.HTMLUNIT; + browser = webdriver.Browser.INTERNET_EXPLORER; + browser = webdriver.Browser.IPAD; + browser = webdriver.Browser.IPHONE; + browser = webdriver.Browser.OPERA; + browser = webdriver.Browser.PHANTOM_JS; + browser = webdriver.Browser.SAFARI; +} + +function TestButton() { + var button: string; + + button = webdriver.Button.LEFT; + button = webdriver.Button.MIDDLE; + button = webdriver.Button.RIGHT; +} + +function TestCapabilities() { + var capabilities: webdriver.Capabilities = new webdriver.Capabilities(); + capabilities = new webdriver.Capabilities(webdriver.Capabilities.chrome()); + var objCapabilities: any = {}; + objCapabilities[webdriver.Capability.BROWSER_NAME] = webdriver.Browser.PHANTOM_JS; + capabilities = new webdriver.Capabilities(objCapabilities); + + var anything: any = capabilities.get(webdriver.Capability.SECURE_SSL); + var check: boolean = capabilities.has(webdriver.Capability.SECURE_SSL); + capabilities = capabilities.merge(capabilities); + capabilities = capabilities.merge(objCapabilities); + capabilities = capabilities.set(webdriver.Capability.VERSION, { abc: 'def' }); + capabilities = capabilities.set(webdriver.Capability.VERSION, null); + capabilities = capabilities.setLoggingPrefs(new webdriver.logging.Preferences()); + capabilities = capabilities.setLoggingPrefs({ key: 'value' }); + capabilities = capabilities.setProxy({ proxyType: 'Type' }); + capabilities = capabilities.setEnableNativeEvents(true); + capabilities = capabilities.setScrollBehavior(1); + capabilities = capabilities.setAlertBehavior('accept'); + + anything = capabilities.toJSON(); + + capabilities = webdriver.Capabilities.android(); + capabilities = webdriver.Capabilities.chrome(); + capabilities = webdriver.Capabilities.firefox(); + capabilities = webdriver.Capabilities.htmlunit(); + capabilities = webdriver.Capabilities.htmlunitwithjs(); + capabilities = webdriver.Capabilities.ie(); + capabilities = webdriver.Capabilities.ipad(); + capabilities = webdriver.Capabilities.iphone(); + capabilities = webdriver.Capabilities.opera(); + capabilities = webdriver.Capabilities.phantomjs(); + capabilities = webdriver.Capabilities.safari(); +} + +function TestCapability() { + var capability: string; + + capability = webdriver.Capability.ACCEPT_SSL_CERTS; + capability = webdriver.Capability.BROWSER_NAME; + capability = webdriver.Capability.ELEMENT_SCROLL_BEHAVIOR; + capability = webdriver.Capability.HANDLES_ALERTS; + capability = webdriver.Capability.LOGGING_PREFS; + capability = webdriver.Capability.NATIVE_EVENTS; + capability = webdriver.Capability.PLATFORM; + capability = webdriver.Capability.PROXY; + capability = webdriver.Capability.ROTATABLE; + capability = webdriver.Capability.SECURE_SSL; + capability = webdriver.Capability.SUPPORTS_APPLICATION_CACHE; + capability = webdriver.Capability.SUPPORTS_CSS_SELECTORS; + capability = webdriver.Capability.SUPPORTS_JAVASCRIPT; + capability = webdriver.Capability.SUPPORTS_LOCATION_CONTEXT; + capability = webdriver.Capability.TAKES_SCREENSHOT; + capability = webdriver.Capability.UNEXPECTED_ALERT_BEHAVIOR; + capability = webdriver.Capability.VERSION; +} + +function TestCommand() { + var command: webdriver.Command = new webdriver.Command(webdriver.CommandName.ADD_COOKIE); + + var name: string = command.getName(); + var param: any = command.getParameter('param'); + + var params: any = command.getParameters(); + + command = command.setParameter('param', 123); + command = command.setParameters({ param: 123 }); +} + +function TestDeferredExecutor() { + var promise: webdriver.promise.Promise; + var executor: webdriver.DeferredExecutor = new webdriver.DeferredExecutor(promise); +} + +function TestCommandName() { + var command: string; + + command = webdriver.CommandName.ACCEPT_ALERT; + command = webdriver.CommandName.ADD_COOKIE; + command = webdriver.CommandName.CLEAR_APP_CACHE; + command = webdriver.CommandName.CLEAR_ELEMENT; + command = webdriver.CommandName.CLEAR_LOCAL_STORAGE; + command = webdriver.CommandName.CLEAR_SESSION_STORAGE; + command = webdriver.CommandName.CLICK; + command = webdriver.CommandName.CLICK_ELEMENT; + command = webdriver.CommandName.CLOSE; + command = webdriver.CommandName.DELETE_ALL_COOKIES; + command = webdriver.CommandName.DELETE_COOKIE; + command = webdriver.CommandName.DESCRIBE_SESSION; + command = webdriver.CommandName.DISMISS_ALERT; + command = webdriver.CommandName.DOUBLE_CLICK; + command = webdriver.CommandName.ELEMENT_EQUALS; + command = webdriver.CommandName.EXECUTE_ASYNC_SCRIPT; + command = webdriver.CommandName.EXECUTE_SCRIPT; + command = webdriver.CommandName.EXECUTE_SQL; + command = webdriver.CommandName.FIND_CHILD_ELEMENT; + command = webdriver.CommandName.FIND_CHILD_ELEMENTS; + command = webdriver.CommandName.FIND_ELEMENT; + command = webdriver.CommandName.FIND_ELEMENTS; + command = webdriver.CommandName.GET; + command = webdriver.CommandName.GET_ACTIVE_ELEMENT; + command = webdriver.CommandName.GET_ALERT_TEXT; + command = webdriver.CommandName.GET_ALL_COOKIES; + command = webdriver.CommandName.GET_APP_CACHE; + command = webdriver.CommandName.GET_APP_CACHE_STATUS; + command = webdriver.CommandName.GET_AVAILABLE_LOG_TYPES; + command = webdriver.CommandName.GET_COOKIE; + command = webdriver.CommandName.GET_CURRENT_URL; + command = webdriver.CommandName.GET_CURRENT_WINDOW_HANDLE; + command = webdriver.CommandName.GET_ELEMENT_ATTRIBUTE; + command = webdriver.CommandName.GET_ELEMENT_LOCATION; + command = webdriver.CommandName.GET_ELEMENT_LOCATION_IN_VIEW; + command = webdriver.CommandName.GET_ELEMENT_SIZE; + command = webdriver.CommandName.GET_ELEMENT_TAG_NAME; + command = webdriver.CommandName.GET_ELEMENT_TEXT; + command = webdriver.CommandName.GET_ELEMENT_VALUE_OF_CSS_PROPERTY; + command = webdriver.CommandName.GET_LOCAL_STORAGE_ITEM; + command = webdriver.CommandName.GET_LOCAL_STORAGE_KEYS; + command = webdriver.CommandName.GET_LOCAL_STORAGE_SIZE; + command = webdriver.CommandName.GET_LOCATION; + command = webdriver.CommandName.GET_LOG; + command = webdriver.CommandName.GET_PAGE_SOURCE; + command = webdriver.CommandName.GET_SCREEN_ORIENTATION; + command = webdriver.CommandName.GET_SERVER_STATUS; + command = webdriver.CommandName.GET_SESSION_LOGS; + command = webdriver.CommandName.GET_SESSION_STORAGE_ITEM; + command = webdriver.CommandName.GET_SESSION_STORAGE_KEYS; + command = webdriver.CommandName.GET_SESSION_STORAGE_SIZE; + command = webdriver.CommandName.GET_SESSIONS; + command = webdriver.CommandName.GET_TITLE; + command = webdriver.CommandName.GET_WINDOW_HANDLES; + command = webdriver.CommandName.GET_WINDOW_POSITION; + command = webdriver.CommandName.GET_WINDOW_SIZE; + command = webdriver.CommandName.GO_BACK; + command = webdriver.CommandName.GO_FORWARD; + command = webdriver.CommandName.IMPLICITLY_WAIT; + command = webdriver.CommandName.IS_BROWSER_ONLINE; + command = webdriver.CommandName.IS_ELEMENT_DISPLAYED; + command = webdriver.CommandName.IS_ELEMENT_ENABLED; + command = webdriver.CommandName.IS_ELEMENT_SELECTED; + command = webdriver.CommandName.MAXIMIZE_WINDOW; + command = webdriver.CommandName.MOUSE_DOWN; + command = webdriver.CommandName.MOUSE_UP; + command = webdriver.CommandName.MOVE_TO; + command = webdriver.CommandName.NEW_SESSION; + command = webdriver.CommandName.QUIT; + command = webdriver.CommandName.REFRESH; + command = webdriver.CommandName.REMOVE_LOCAL_STORAGE_ITEM; + command = webdriver.CommandName.REMOVE_SESSION_STORAGE_ITEM; + command = webdriver.CommandName.SCREENSHOT; + command = webdriver.CommandName.SEND_KEYS_TO_ACTIVE_ELEMENT; + command = webdriver.CommandName.SEND_KEYS_TO_ELEMENT; + command = webdriver.CommandName.SET_ALERT_TEXT; + command = webdriver.CommandName.SET_BROWSER_ONLINE; + command = webdriver.CommandName.SET_LOCAL_STORAGE_ITEM; + command = webdriver.CommandName.SET_LOCATION; + command = webdriver.CommandName.SET_SCREEN_ORIENTATION; + command = webdriver.CommandName.SET_SCRIPT_TIMEOUT; + command = webdriver.CommandName.SET_SESSION_STORAGE_ITEM; + command = webdriver.CommandName.SET_TIMEOUT; + command = webdriver.CommandName.SET_WINDOW_POSITION; + command = webdriver.CommandName.SET_WINDOW_SIZE; + command = webdriver.CommandName.SUBMIT_ELEMENT; + command = webdriver.CommandName.SWITCH_TO_FRAME; + command = webdriver.CommandName.SWITCH_TO_WINDOW; + command = webdriver.CommandName.TOUCH_DOUBLE_TAP; + command = webdriver.CommandName.TOUCH_DOWN; + command = webdriver.CommandName.TOUCH_FLICK; + command = webdriver.CommandName.TOUCH_LONG_PRESS; + command = webdriver.CommandName.TOUCH_MOVE; + command = webdriver.CommandName.TOUCH_SCROLL; + command = webdriver.CommandName.TOUCH_SINGLE_TAP; + command = webdriver.CommandName.TOUCH_UP; +} + +function TestEventEmitter() { + var emitter: webdriver.EventEmitter = new webdriver.EventEmitter(); + + var callback = (a: number, b: number, c: number) => {}; + + emitter = emitter.addListener('ABC', callback); + emitter = emitter.addListener('ABC', callback, this); + + emitter.emit('ABC', 1, 2, 3); + + var listeners = emitter.listeners('ABC'); + if (listeners[0].oneshot) { + listeners[0].fn.apply(listeners[0].scope); + } + var length: number = listeners.length; + var listenerInfo = listeners[0]; + if (listenerInfo.oneshot) { + listenerInfo.fn.apply(listenerInfo.scope, [1, 2, 3]); + } + + emitter = emitter.on('ABC', callback); + emitter = emitter.on('ABC', callback, this); + + emitter = emitter.once('ABC', callback); + emitter = emitter.once('ABC', callback, this); + + emitter = emitter.removeListener('ABC', callback); + + emitter.removeAllListeners('ABC'); + emitter.removeAllListeners(); +} + +function TestKey() { + var key: string; + + key = webdriver.Key.ADD; + key = webdriver.Key.ALT; + key = webdriver.Key.ARROW_DOWN; + key = webdriver.Key.ARROW_LEFT; + key = webdriver.Key.ARROW_RIGHT; + key = webdriver.Key.ARROW_UP; + key = webdriver.Key.BACK_SPACE; + key = webdriver.Key.CANCEL; + key = webdriver.Key.CLEAR; + key = webdriver.Key.COMMAND; + key = webdriver.Key.CONTROL; + key = webdriver.Key.DECIMAL; + key = webdriver.Key.DELETE; + key = webdriver.Key.DIVIDE; + key = webdriver.Key.DOWN; + key = webdriver.Key.END; + key = webdriver.Key.ENTER; + key = webdriver.Key.EQUALS; + key = webdriver.Key.ESCAPE; + key = webdriver.Key.F1; + key = webdriver.Key.F2; + key = webdriver.Key.F3; + key = webdriver.Key.F4; + key = webdriver.Key.F5; + key = webdriver.Key.F6; + key = webdriver.Key.F7; + key = webdriver.Key.F8; + key = webdriver.Key.F9; + key = webdriver.Key.F10; + key = webdriver.Key.F11; + key = webdriver.Key.F12; + key = webdriver.Key.HELP; + key = webdriver.Key.HOME; + key = webdriver.Key.INSERT; + key = webdriver.Key.LEFT; + key = webdriver.Key.META; + key = webdriver.Key.MULTIPLY; + key = webdriver.Key.NULL; + key = webdriver.Key.NUMPAD0; + key = webdriver.Key.NUMPAD1; + key = webdriver.Key.NUMPAD2; + key = webdriver.Key.NUMPAD3; + key = webdriver.Key.NUMPAD4; + key = webdriver.Key.NUMPAD5; + key = webdriver.Key.NUMPAD6; + key = webdriver.Key.NUMPAD7; + key = webdriver.Key.NUMPAD8; + key = webdriver.Key.NUMPAD9; + key = webdriver.Key.PAGE_DOWN; + key = webdriver.Key.PAGE_UP; + key = webdriver.Key.PAUSE; + key = webdriver.Key.RETURN; + key = webdriver.Key.RIGHT; + key = webdriver.Key.SEMICOLON; + key = webdriver.Key.SEPARATOR; + key = webdriver.Key.SHIFT; + key = webdriver.Key.SPACE; + key = webdriver.Key.SUBTRACT; + key = webdriver.Key.TAB; + key = webdriver.Key.UP; +} + +function TestBy() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var locator: webdriver.By = new webdriver.By('class name', 'class'); + + var str: string = locator.toString(); + + locator = webdriver.By.className('class'); + locator = webdriver.By.css('css'); + locator = webdriver.By.id('id'); + locator = webdriver.By.linkText('link'); + locator = webdriver.By.name('name'); + locator = webdriver.By.partialLinkText('text'); + locator = webdriver.By.tagName('tag'); + locator = webdriver.By.xpath('xpath'); + + // Can import 'By' without import declarations + var By = webdriver.By; + + var locatorHash: webdriver.ByHash; + locatorHash = { className: 'class' }; + locatorHash = { css: 'css' }; + locatorHash = { id: 'id' }; + locatorHash = { linkText: 'link' }; + locatorHash = { name: 'name' }; + locatorHash = { partialLinkText: 'text' }; + locatorHash = { tagName: 'tag' }; + locatorHash = { xpath: 'xpath' }; + + webdriver.By.js('script', 1, 2, 3)(driver).then((abc: number) => {}); +} + +function TestSession() { + var session: webdriver.Session = new webdriver.Session('ABC', webdriver.Capabilities.android()); + var capabilitiesObj: any = {}; + capabilitiesObj[webdriver.Capability.BROWSER_NAME] = webdriver.Browser.ANDROID; + capabilitiesObj[webdriver.Capability.PLATFORM] = 'ANDROID'; + session = new webdriver.Session('ABC', capabilitiesObj); + + var capabilities: webdriver.Capabilities = session.getCapabilities(); + var capability: any = session.getCapability(webdriver.Capability.BROWSER_NAME); + var id: string = session.getId(); + var data: string = session.toJSON(); +} + +function TestUnhandledAlertError() { + var someFunc = (error: webdriver.UnhandledAlertError) => { + var baseError: Error = error; + var str: string = error.getAlertText(); + str = error.toString(); + }; +} + +function TestWebDriverFileDetector() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var fileDetector: webdriver.FileDetector = new webdriver.FileDetector(); + + fileDetector.handleFile(driver, 'path/to/file').then((path: string) => {}); +} + +function TestWebDriverLogs() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var logs: webdriver.Logs = new webdriver.Logs(driver); + + logs.get(webdriver.logging.Type.BROWSER).then((entries: webdriver.logging.Entry[]) => {}); + logs.getAvailableLogTypes().then((types: string[]) => {}); +} + +function TestWebDriverNavigation() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var navigation: webdriver.Navigation = new webdriver.Navigation(driver); + + navigation.back().then(() => {}); + navigation.forward().then(() => {}); + navigation.refresh().then(() => {}); + navigation.to('http://google.com').then(() => {}); +} + +function TestWebDriverOptions() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var options: webdriver.Options = new webdriver.Options(driver); + var promise: webdriver.promise.Promise; + + // Add Cookie + promise = options.addCookie('name', 'value'); + promise = options.addCookie('name', 'value', 'path'); + promise = options.addCookie('name', 'value', 'path', 'domain'); + promise = options.addCookie('name', 'value', 'path', 'domain', true); + promise = options.addCookie('name', 'value', 'path', 'domain', true, 123); + promise = options.addCookie('name', 'value', 'path', 'domain', true, Date.now()); + + promise = options.deleteAllCookies(); + promise = options.deleteCookie('name'); + options.getCookie('name').then((cookies: webdriver.IWebDriverOptionsCookie) => {}); + options.getCookies().then((cookies: webdriver.IWebDriverOptionsCookie[]) => {}); + + var logs: webdriver.Logs = options.logs(); + var timeouts: webdriver.Timeouts = options.timeouts(); + var window: webdriver.Window = options.window(); +} + +function TestWebDriverTargetLocator() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var locator: webdriver.TargetLocator = new webdriver.TargetLocator(driver); + var promise: webdriver.promise.Promise; + + var element: webdriver.WebElement = locator.activeElement(); + var alert: webdriver.Alert = locator.alert(); + promise = locator.defaultContent(); + promise = locator.frame(1); + promise = locator.window('nameOrHandle'); +} + +function TestWebDriverTimeouts() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var timeouts: webdriver.Timeouts = new webdriver.Timeouts(driver); + var promise: webdriver.promise.Promise; + + promise = timeouts.implicitlyWait(123); + promise = timeouts.pageLoadTimeout(123); + promise = timeouts.setScriptTimeout(123); +} + +function TestWebDriverWindow() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var window: webdriver.Window = new webdriver.Window(driver); + var locationPromise: webdriver.promise.Promise; + var sizePromise: webdriver.promise.Promise; + var voidPromise: webdriver.promise.Promise; + + locationPromise = window.getPosition(); + sizePromise = window.getSize(); + voidPromise = window.maximize(); + voidPromise = window.setPosition(12, 34); + voidPromise = window.setSize(12, 34); +} + +function TestWebDriver() { + var session: webdriver.Session = new webdriver.Session('ABC', webdriver.Capabilities.android()); + var sessionPromise: webdriver.promise.Promise; + var executor: webdriver.Executor = executors.createExecutor('http://someserver'); + var flow: webdriver.promise.ControlFlow = new webdriver.promise.ControlFlow(); + var driver: webdriver.WebDriver = new webdriver.WebDriver(session, executor); + driver = new webdriver.WebDriver(session, executor, flow); + driver = new webdriver.WebDriver(sessionPromise, executor); + driver = new webdriver.WebDriver(sessionPromise, executor, flow); + + var voidPromise: webdriver.promise.Promise; + var stringPromise: webdriver.promise.Promise; + var booleanPromise: webdriver.promise.Promise; + + var actions: webdriver.ActionSequence = driver.actions(); + var touchActions: webdriver.TouchSequence = driver.touchActions(); + + // call + stringPromise = driver.call(() => 'value'); + stringPromise = driver.call(() => stringPromise); + stringPromise = driver.call(() => { var d: any = this; return 'value'; }, driver); + stringPromise = driver.call((a: number) => 'value', driver, 1); + + voidPromise = driver.close(); + flow = driver.controlFlow(); + + // executeAsyncScript + stringPromise = driver.executeAsyncScript('function(){}'); + stringPromise = driver.executeAsyncScript('function(){}', 1, 2, 3); + stringPromise = driver.executeAsyncScript(() => {}); + stringPromise = driver.executeAsyncScript((a: number) => {}, 1); + + // executeScript + stringPromise = driver.executeScript('function(){}'); + stringPromise = driver.executeScript('function(){}', 1, 2, 3); + stringPromise = driver.executeScript(() => {}); + stringPromise = driver.executeScript((a: number) => {}, 1); + + // findElement + var element: webdriver.WebElement; + element = driver.findElement(webdriver.By.id('ABC')); + element = driver.findElement(webdriver.By.js('function(){}')); + + // findElements + driver.findElements(webdriver.By.className('ABC')).then((elements: webdriver.WebElement[]) => {}); + driver.findElements(webdriver.By.js('function(){}')).then((elements: webdriver.WebElement[]) => {}); + + voidPromise = driver.get('http://www.google.com'); + driver.getAllWindowHandles().then((handles: string[]) => {}); + driver.getCapabilities().then((caps: webdriver.Capabilities) => {}); + stringPromise = driver.getCurrentUrl(); + stringPromise = driver.getPageSource(); + driver.getSession().then((session: webdriver.Session) => {}); + stringPromise = driver.getTitle(); + stringPromise = driver.getWindowHandle(); + + booleanPromise = driver.isElementPresent(webdriver.By.className('ABC')); + booleanPromise = driver.isElementPresent(webdriver.By.js('function(){}')); + + var options: webdriver.Options = driver.manage(); + var navigation: webdriver.Navigation = driver.navigate(); + var locator: webdriver.TargetLocator = driver.switchTo(); + + var fileDetector: webdriver.FileDetector = new webdriver.FileDetector(); + driver.setFileDetector(fileDetector); + + voidPromise = driver.quit(); + voidPromise = driver.schedule(new webdriver.Command(webdriver.CommandName.CLICK), 'ABC'); + voidPromise = driver.sleep(123); + stringPromise = driver.takeScreenshot(); + + var booleanCondition: webdriver.until.Condition; + booleanPromise = driver.wait(booleanPromise); + booleanPromise = driver.wait(booleanCondition); + booleanPromise = driver.wait((driver: webdriver.WebDriver) => true); + let conditionFunction: Function; // tslint:disable-line:prefer-const + booleanPromise = driver.wait(conditionFunction); + booleanPromise = driver.wait(booleanPromise, 123); + booleanPromise = driver.wait(booleanPromise, 123, 'Message'); + + driver = webdriver.WebDriver.attachToSession(executor, 'ABC'); + driver = webdriver.WebDriver.createSession(executor, webdriver.Capabilities.android()); +} + +function TestSerializable() { + var serializable: webdriver.Serializable; + var serial: string | webdriver.promise.IThenable = serializable.serialize(); +} + +function TestWebElement() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var promise: webdriver.promise.Promise; + var element: webdriver.WebElement; + + element = new webdriver.WebElement(driver, 'elementId'); + element = new webdriver.WebElement(driver, promise); + + var voidPromise: webdriver.promise.Promise; + var stringPromise: webdriver.promise.Promise; + var booleanPromise: webdriver.promise.Promise; + + voidPromise = element.clear(); + voidPromise = element.click(); + + element = element.findElement(webdriver.By.id('ABC')); + element.findElements(webdriver.By.className('ABC')).then((elements: webdriver.WebElement[]) => {}); + booleanPromise = element.isElementPresent(webdriver.By.className('ABC')); + + stringPromise = element.getAttribute('class'); + stringPromise = element.getCssValue('display'); + driver = element.getDriver(); + stringPromise = element.getInnerHtml(); + element.getLocation().then((location: webdriver.ILocation) => {}); + stringPromise = element.getOuterHtml(); + element.getSize().then((size: webdriver.ISize) => {}); + stringPromise = element.getTagName(); + stringPromise = element.getText(); + booleanPromise = element.isDisplayed(); + booleanPromise = element.isEnabled(); + booleanPromise = element.isSelected(); + voidPromise = element.sendKeys('A', 'B', 'C'); + voidPromise = element.sendKeys(1, 2, 3); + voidPromise = element.sendKeys(webdriver.Key.BACK_SPACE); + voidPromise = element.sendKeys(stringPromise, stringPromise, stringPromise); + voidPromise = element.sendKeys('A', 1, webdriver.Key.BACK_SPACE, stringPromise); + voidPromise = element.submit(); + element.getId().then((id: string) => {}); + element.getRawId().then((id: string) => {}); + element.serialize().then((id: webdriver.IWebElementId) => {}); + + booleanPromise = webdriver.WebElement.equals(element, new webdriver.WebElement(driver, 'elementId')); +} + +function TestWebElementPromise() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var elementPromise: webdriver.WebElementPromise = driver.findElement(webdriver.By.id('id')); + + elementPromise.cancel(); + elementPromise.cancel('reason'); + + var bool: boolean = elementPromise.isPending(); + + elementPromise.then(); + elementPromise.then((element: webdriver.WebElement) => {}); + elementPromise.then((element: webdriver.WebElement) => {}, (error: any) => {}); + elementPromise.then((element: webdriver.WebElement) => 'foo', (error: any) => {}).then((result: string) => {}); + + elementPromise.thenCatch((error: any) => {}).then((value: any) => {}); + + elementPromise.thenFinally(() => {}); +} + +function TestLogging() { + var preferences: webdriver.logging.Preferences = new webdriver.logging.Preferences(); + preferences.setLevel(webdriver.logging.Type.BROWSER, webdriver.logging.Level.ALL); + var prefs: any = preferences.toJSON(); + + var level: webdriver.logging.Level = webdriver.logging.getLevel('OFF'); + level = webdriver.logging.getLevel(1); + + level = webdriver.logging.Level.ALL; + level = webdriver.logging.Level.DEBUG; + level = webdriver.logging.Level.INFO; + level = webdriver.logging.Level.OFF; + level = webdriver.logging.Level.SEVERE; + level = webdriver.logging.Level.WARNING; + + var name: string = level.name; + var value: number = level.value; + + var type: string; + type = webdriver.logging.Type.BROWSER; + type = webdriver.logging.Type.CLIENT; + type = webdriver.logging.Type.DRIVER; + type = webdriver.logging.Type.PERFORMANCE; + type = webdriver.logging.Type.SERVER; +} + +function TestLoggingEntry() { + var entry: webdriver.logging.Entry; + + entry = new webdriver.logging.Entry(webdriver.logging.Level.ALL, 'ABC'); + entry = new webdriver.logging.Entry('ALL', 'ABC'); + entry = new webdriver.logging.Entry(webdriver.logging.Level.ALL, 'ABC', 123); + entry = new webdriver.logging.Entry('ALL', 'ABC', 123); + entry = new webdriver.logging.Entry(webdriver.logging.Level.ALL, 'ABC', 123, webdriver.logging.Type.BROWSER); + entry = new webdriver.logging.Entry('ALL', 'ABC', 123, webdriver.logging.Type.BROWSER); + + var entryObj: any = entry.toJSON(); + + var message: string = entry.message; + var timestamp: number = entry.timestamp; + var type: string = entry.type; +} + +function TestPromiseModule() { + var cancellationError: webdriver.promise.CancellationError = new webdriver.promise.CancellationError(); + cancellationError = new webdriver.promise.CancellationError('message'); + var str: string = cancellationError.message; + str = cancellationError.name; + + var stringPromise: webdriver.promise.Promise; + var numberPromise: webdriver.promise.Promise; + var booleanPromise: webdriver.promise.Promise; + var voidPromise: webdriver.promise.Promise; + + webdriver.promise.all([stringPromise]).then((values: string[]) => {}); + + webdriver.promise.asap('abc', (value: any) => true); + webdriver.promise.asap('abc', (value: any) => {}, (err: any) => 'ABC'); + + stringPromise = webdriver.promise.checkedNodeCall((err: any, value: any) => 'abc'); + + webdriver.promise.consume(() => { + return 5; + }).then((value: number) => {}); + webdriver.promise.consume(() => { + return 5; + }, this).then((value: number) => {}); + webdriver.promise.consume((a: number, b: number, c: number) => 5, this, 1, 2, 3) + .then((value: number) => {}); + + var numbersPromise: webdriver.promise.Promise = webdriver.promise.filter([1, 2, 3], (element: number, type: any, index: number, arr: number[]) => { + return true; + }); + numbersPromise = webdriver.promise.filter([1, 2, 3], (element: number, type: any, index: number, arr: number[]) => { + return true; + }, this); + numbersPromise = webdriver.promise.filter(numbersPromise, (element: number, type: any, index: number, arr: number[]) => { + return true; + }); + numbersPromise = webdriver.promise.filter(numbersPromise, (element: number, type: any, index: number, arr: number[]) => { + return true; + }, this); + + numbersPromise = webdriver.promise.map([1, 2, 3], (el: number, type: any, index: number, arr: number[]) => { + return true; + }); + numbersPromise = webdriver.promise.map([1, 2, 3], (el: number, type: any, index: number, arr: number[]) => { + return true; + }, this); + numbersPromise = webdriver.promise.map(numbersPromise, (el: number, type: any, index: number, arr: number[]) => { + return true; + }); + numbersPromise = webdriver.promise.map(numbersPromise, (el: number, type: any, index: number, arr: number[]) => { + return true; + }, this); + + var flow: webdriver.promise.ControlFlow = webdriver.promise.controlFlow(); + + stringPromise = webdriver.promise.createFlow((newFlow: webdriver.promise.ControlFlow) => 'ABC'); + + var deferred: webdriver.promise.Deferred; + deferred = webdriver.promise.defer(); + deferred = webdriver.promise.defer(); + + stringPromise = deferred.promise; + + deferred.fulfill('ABC'); + deferred.reject('error'); + + voidPromise = webdriver.promise.delayed(123); + + voidPromise = webdriver.promise.fulfilled(); + stringPromise = webdriver.promise.fulfilled('abc'); + + stringPromise = webdriver.promise.fullyResolved('abc'); + + var bool: boolean = webdriver.promise.isGenerator(() => {}); + var isPromise: boolean = webdriver.promise.isPromise('ABC'); + + stringPromise = webdriver.promise.rejected('{a: 123}'); + + webdriver.promise.setDefaultFlow(new webdriver.promise.ControlFlow()); + + numberPromise = webdriver.promise.when('abc', (value: any) => 123, (err: Error) => 123); +} + +function TestUntilModule() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var conditionB: webdriver.until.Condition = new webdriver.until.Condition('message', (driver: webdriver.WebDriver) => true); + var conditionBBase: webdriver.until.Condition = conditionB; + var conditionWebElement: webdriver.until.Condition; + var conditionWebElements: webdriver.until.Condition; + + conditionB = webdriver.until.ableToSwitchToFrame(5); + var conditionAlert: webdriver.until.Condition = webdriver.until.alertIsPresent(); + var el: webdriver.WebElement = driver.findElement(webdriver.By.id('id')); + conditionB = webdriver.until.elementIsDisabled(el); + conditionB = webdriver.until.elementIsEnabled(el); + conditionB = webdriver.until.elementIsNotSelected(el); + conditionB = webdriver.until.elementIsNotVisible(el); + conditionB = webdriver.until.elementIsSelected(el); + conditionB = webdriver.until.elementIsVisible(el); + conditionB = webdriver.until.elementTextContains(el, 'text'); + conditionB = webdriver.until.elementTextIs(el, 'text'); + conditionB = webdriver.until.elementTextMatches(el, /text/); + conditionB = webdriver.until.stalenessOf(el); + conditionB = webdriver.until.titleContains('text'); + conditionB = webdriver.until.titleIs('text'); + conditionB = webdriver.until.titleMatches(/text/); + + conditionWebElement = webdriver.until.elementLocated(webdriver.By.id('id')); + conditionWebElements = webdriver.until.elementsLocated(webdriver.By.className('class')); +} + +function TestControlFlow() { + var flow: webdriver.promise.ControlFlow; + flow = new webdriver.promise.ControlFlow(); + + var emitter: webdriver.EventEmitter = flow; + + var eventType: string; + + eventType = webdriver.promise.ControlFlow.EventType.IDLE; + eventType = webdriver.promise.ControlFlow.EventType.RESET; + eventType = webdriver.promise.ControlFlow.EventType.SCHEDULE_TASK; + eventType = webdriver.promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION; + + var stringPromise: webdriver.promise.Promise; + stringPromise = flow.execute(() => 'value'); + stringPromise = flow.execute(() => stringPromise); + stringPromise = flow.execute(() => stringPromise, 'Description'); + + var schedule: string; + schedule = flow.toString(); + schedule = flow.getSchedule(); + schedule = flow.getSchedule(true); + + flow.reset(); + + var voidPromise: webdriver.promise.Promise = flow.timeout(123); + voidPromise = flow.timeout(123, 'Description'); + + stringPromise = flow.wait(stringPromise); + + voidPromise = flow.wait(() => true); + voidPromise = flow.wait(() => true, 123); + voidPromise = flow.wait(() => stringPromise, 123, 'Timeout Message'); +} + +function TestDeferred() { + var deferred: webdriver.promise.Deferred; + + deferred = new webdriver.promise.Deferred(); + deferred = new webdriver.promise.Deferred(new webdriver.promise.ControlFlow()); + + var promise: webdriver.promise.Promise = deferred.promise; + + deferred.errback(new Error('Error')); + deferred.errback('Error'); + deferred.fulfill('abc'); + deferred.reject(new Error('Error')); + deferred.reject('Error'); + deferred.removeAll(); +} + +function TestPromiseClass() { + var controlFlow: webdriver.promise.ControlFlow; + var promise: webdriver.promise.Promise; + promise = new webdriver.promise.Promise((resolve: (value: string) => void, reject: () => void) => {}); + promise = new webdriver.promise.Promise((resolve: (value: webdriver.promise.Promise) => void, reject: () => void) => {}); + promise = new webdriver.promise.Promise((resolve: (value: string) => void, reject: () => void) => {}, controlFlow); + + promise.cancel('Abort'); + + var isPending: boolean = promise.isPending(); + + promise = promise.then(); + promise = promise.then((a: string) => 'cde'); + promise = promise.then((a: string) => 'cde', (e: any) => {}); + promise = promise.then((a: string) => 'cde', (e: any) => 123); + + promise = promise.thenCatch((error: any) => {}); + + promise.thenFinally(() => {}); +} + +function TestThenableClass() { + var thenable: webdriver.promise.Promise = new webdriver.promise.Promise((resolve, reject) => { + resolve('a'); + }); + + thenable.cancel('Abort'); + + var isPending: boolean = thenable.isPending(); + + thenable = thenable.then((a: string) => 'cde'); + thenable = thenable.then((a: string) => 'cde', (e: any) => {}); + thenable = thenable.then((a: string) => 'cde', (e: any) => 123); + + thenable = thenable.thenCatch((error: any) => {}); + + thenable.thenFinally(() => {}); +} + +function TestErrorCode() { + var errorCode: number; + + errorCode = new webdriver.error.ElementNotSelectableError().code(); + errorCode = new webdriver.error.ElementNotVisibleError().code(); + errorCode = new webdriver.error.InvalidArgumentError().code(); + errorCode = new webdriver.error.InvalidCookieDomainError().code(); + errorCode = new webdriver.error.InvalidElementCoordinatesError().code(); + errorCode = new webdriver.error.InvalidElementStateError().code(); + errorCode = new webdriver.error.InvalidSelectorError().code(); + errorCode = new webdriver.error.NoSuchSessionError().code(); + errorCode = new webdriver.error.JavascriptError().code(); + errorCode = new webdriver.error.MoveTargetOutOfBoundsError().code(); + errorCode = new webdriver.error.NoSuchAlertError().code(); + errorCode = new webdriver.error.NoSuchElementError().code(); + errorCode = new webdriver.error.NoSuchFrameError().code(); + errorCode = new webdriver.error.NoSuchWindowError().code(); + errorCode = new webdriver.error.ScriptTimeoutError().code(); + errorCode = new webdriver.error.SessionNotCreatedError().code(); + errorCode = new webdriver.error.StaleElementReferenceError().code(); + errorCode = new webdriver.error.TimeoutError().code(); + errorCode = new webdriver.error.UnableToSetCookieError().code(); + errorCode = new webdriver.error.UnableToCaptureScreenError().code(); + errorCode = new webdriver.error.UnexpectedAlertOpenError().code(); + errorCode = new webdriver.error.UnknownCommandError().code(); + errorCode = new webdriver.error.UnknownMethodError().code(); + errorCode = new webdriver.error.UnsupportedOperationError().code(); +} + +async function TestAsyncAwaitable() { + var thenable: webdriver.promise.Promise = new webdriver.promise.Promise((resolve, reject) => resolve('foo')); + var str: string = await thenable; +} + +function TestTestingModule() { + testing.before(() => { + }); + + testing.beforeEach(() => { + }); + + testing.describe('My test suite', () => { + testing.it('My test', () => { + }); + + testing.iit('My exclusive test.', () => { + }); + + }); + + testing.xdescribe('My disabled suite', () => { + testing.xit('My disabled test.', () => { + }); + }); + + testing.after(() => { + }); + + testing.afterEach(() => { + }); +} diff --git a/selenium-webdriver/v2/test/remote.ts b/selenium-webdriver/v2/test/remote.ts new file mode 100644 index 0000000000..08722d5b1f --- /dev/null +++ b/selenium-webdriver/v2/test/remote.ts @@ -0,0 +1,13 @@ +/* tslint:disable */ + +import * as remote from "selenium-webdriver/remote"; +import * as webdriver from "selenium-webdriver"; + +function TestRemoteFileDetector() { + const driver: webdriver.WebDriver = new webdriver.Builder() + .withCapabilities(webdriver.Capabilities.chrome()) + .build(); + + const fileDetector: remote.FileDetector = new remote.FileDetector(); + fileDetector.handleFile(driver, 'path/to/file').then((path: string) => { /* empty */ }); +} diff --git a/selenium-webdriver/v2/testing.d.ts b/selenium-webdriver/v2/testing.d.ts new file mode 100644 index 0000000000..ec8e7123d7 --- /dev/null +++ b/selenium-webdriver/v2/testing.d.ts @@ -0,0 +1,60 @@ +/* tslint:disable */ +/** +* Registers a new test suite. +* @param name The suite name. +* @param fn The suite function, or {@code undefined} to define a pending test suite. +*/ +export function describe(name: string, fn: Function): void; + +/** + * Defines a suppressed test suite. + * @param name The suite name. + * @param fn The suite function, or {@code undefined} to define a pending test suite. + */ +export function xdescribe(name: string, fn: Function): void; + +/** + * Register a function to call after the current suite finishes. + * @param fn + */ +export function after(fn: Function): void; + +/** + * Register a function to call after each test in a suite. + * @param fn + */ +export function afterEach(fn: Function): void; + +/** + * Register a function to call before the current suite starts. + * @param fn + */ +export function before(fn: Function): void; + +/** + * Register a function to call before each test in a suite. + * @param fn + */ +export function beforeEach(fn: Function): void; + +/** + * Add a test to the current suite. + * @param name The test name. + * @param fn The test function, or {@code undefined} to define a pending test case. + */ +export function it(name: string, fn: Function): void; + +/** + * An alias for {@link #it()} that flags the test as the only one that should + * be run within the current suite. + * @param name The test name. + * @param fn The test function, or {@code undefined} to define a pending test case. + */ +export function iit(name: string, fn: Function): void; + +/** + * Adds a test to the current suite while suppressing it so it is not run. + * @param name The test name. + * @param fn The test function, or {@code undefined} to define a pending test case. + */ +export function xit(name: string, fn: Function): void; diff --git a/selenium-webdriver/v2/tsconfig.json b/selenium-webdriver/v2/tsconfig.json new file mode 100644 index 0000000000..2849e3669b --- /dev/null +++ b/selenium-webdriver/v2/tsconfig.json @@ -0,0 +1,40 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": false, + "strictNullChecks": false, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "selenium-webdriver": ["selenium-webdriver/v2"], + "selenium-webdriver/*": ["selenium-webdriver/v2/*"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "chrome.d.ts", + "edge.d.ts", + "executors.d.ts", + "firefox.d.ts", + "http.d.ts", + "ie.d.ts", + "opera.d.ts", + "remote.d.ts", + "safari.d.ts", + "testing.d.ts", + "test/index.ts", + "test/chrome.ts", + "test/firefox.ts", + "test/remote.ts" + ] +} \ No newline at end of file diff --git a/selenium-webdriver/v2/tslint.json b/selenium-webdriver/v2/tslint.json new file mode 100644 index 0000000000..ad51895c20 --- /dev/null +++ b/selenium-webdriver/v2/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "../tslint.json", + "rules": { + "dt-header": false + } +} diff --git a/sequelize/index.d.ts b/sequelize/index.d.ts index fda7cad2f5..ec41863261 100644 --- a/sequelize/index.d.ts +++ b/sequelize/index.d.ts @@ -3183,7 +3183,7 @@ declare namespace sequelize { /** * A hash of attributes to describe your search. See above for examples. */ - where?: WhereOptions | Array
; + where?: WhereOptions | fn | Array; /** * A list of the attributes that you want to select. To rename an attribute, you can pass an array, with @@ -4876,6 +4876,11 @@ declare namespace sequelize { */ underscoredAll?: boolean; + /** + * Indicates if the model's table has a trigger associated with it. Default false. + */ + hasTrigger?: boolean; + /** * If freezeTableName is true, sequelize will not try to alter the DAO name to get the table name. * Otherwise, the dao name will be pluralized. Default false. diff --git a/sequelize/sequelize-tests.ts b/sequelize/sequelize-tests.ts index 20af1246d4..71e6203a82 100644 --- a/sequelize/sequelize-tests.ts +++ b/sequelize/sequelize-tests.ts @@ -905,6 +905,7 @@ User.findAll( { attributes: [[s.fn('count', Sequelize.col('*')), 'count']] }); User.findAll( { attributes: [[s.fn('count', Sequelize.col('*')), 'count']], group: ['sex'] }); User.findAll( { attributes: [s.cast(s.fn('count', Sequelize.col('*')), 'INTEGER')] }); User.findAll( { attributes: [[s.cast(s.fn('count', Sequelize.col('*')), 'INTEGER'), 'count']] }); +User.findAll( { where : s.fn('count', [0, 10]) } ); User.findById( 'a string' ); @@ -925,6 +926,7 @@ User.findOne( { where : { name : 'worker' }, include : [User] } ); User.findOne( { where : { name : 'Boris' }, include : [User, { model : User, as : 'Photos' }] } ); User.findOne( { where : { username : 'someone' }, include : [User] } ); User.findOne( { where : { username : 'barfooz' }, raw : true } ); +User.findOne( { where : s.fn('count', []) } ); /* NOTE https://github.com/DefinitelyTyped/DefinitelyTyped/pull/5590 User.findOne( { updatedAt : { ne : null } } ); */ @@ -1534,6 +1536,27 @@ s.define( 'User', { paranoid : true } ); +s.define( 'TriggerTest', { + id : { + type : Sequelize.INTEGER, + field : 'test_id', + autoIncrement : true, + primaryKey : true, + validate : { + min : 1 + } + }, + title : { + allowNull : false, + type : Sequelize.STRING( 255 ), + field : 'test_title' + } +}, { + timestamps : false, + underscored : true, + hasTrigger : true +} ); + // // Transaction // ~~~~~~~~~~~~~ diff --git a/sequelize/v3/index.d.ts b/sequelize/v3/index.d.ts index 9142dc9a6c..fb73cd94bf 100644 --- a/sequelize/v3/index.d.ts +++ b/sequelize/v3/index.d.ts @@ -4843,6 +4843,11 @@ declare namespace sequelize { */ underscoredAll?: boolean; + /** + * Indicates if the model's table has a trigger associated with it. Default false. + */ + hasTrigger?: boolean; + /** * If freezeTableName is true, sequelize will not try to alter the DAO name to get the table name. * Otherwise, the dao name will be pluralized. Default false. diff --git a/sequelize/v3/sequelize-tests.ts b/sequelize/v3/sequelize-tests.ts index 04a55062c8..ef90600e91 100644 --- a/sequelize/v3/sequelize-tests.ts +++ b/sequelize/v3/sequelize-tests.ts @@ -1515,6 +1515,27 @@ s.define( 'User', { paranoid : true } ); +s.define( 'TriggerTest', { + id : { + type : Sequelize.INTEGER, + field : 'test_id', + autoIncrement : true, + primaryKey : true, + validate : { + min : 1 + } + }, + title : { + allowNull : false, + type : Sequelize.STRING( 255 ), + field : 'test_title' + } +}, { + timestamps : false, + underscored : true, + hasTrigger : true +} ); + // // Transaction // ~~~~~~~~~~~~~ diff --git a/service_worker_api/index.d.ts b/service_worker_api/index.d.ts index 715fc4efbe..3f7e07acaa 100644 --- a/service_worker_api/index.d.ts +++ b/service_worker_api/index.d.ts @@ -576,12 +576,90 @@ interface ServiceWorkerRegistration extends EventTarget { * before it is unregistered. */ unregister(): Promise; + + /** + * Returns a Promise that resolves to an array of Notification objects. + * @param [options] An options object that can contain options to filter the notifications returned. + */ + getNotifications(options?: ServiceWorkerGetNotificationOptions): Promise; // need to be replaced with `Notification[]` when possible + + /** + * Displays the notification with the requested title. + * @param [title] The title that must be shown within the notification + * @param [options] An object that allows to configure the notification. + */ + showNotification(title: string, options?: ServiceWorkerNotificationOptions): Promise; } +/** + * An options object to provide options upon a ServiceWorkerRegistration. + * @param [scope] A USVString representing a URL that defines a service worker's registration scope; what range of + * URLs a service worker can control. This is usually a relative URL, and it defaults to '/' when not specified. + */ interface ServiceWorkerRegisterOptions { scope: string; } +/** + * Action to display in a notification. + * @param [action] A DOMString identifying a user action to be displayed on the notification. + * @param [title] A DOMString containing action text to be shown to the user. + * @param [icon] A USVString containg the URL of an icon to display with the action. + */ +interface NotificationAction { // TODO: Maybe need to moved if NotificationApi types are defined + action: string; + title: string; + icon?: string; +} + +/** + * Object that allows to configure a notification. + * @param [actions] An array of actions to display in the notification. + * Appropriate responses are built using event.action within the notificationclick event. + * @param [badge] The URL of an image to represent the notification when there is not enough space to display the + * notification itself such as, for example, the Android Notification Bar. On Android devices, the badge should + * accommodate devices up to 4x resolution, about 96 by 96 px, and the image will be automatically masked. + * @param [body] A string representing an extra content to display within the notification. + * @param [dir] The direction of the notification; it can be auto, ltr, or rtl. + * @param [icon] The URL of an image to be used as an icon by the notification. + * @param [image] A USVSTring containing the URL of an image to be displayed in the notification. + * @param [lang] Specify the lang used within the notification. This string must be a valid BCP 47 language tag. + * @param [renotify] A boolean that indicates whether to supress vibrations and audible alerts when resusing a tag + * value. The default is false. + * @param [requireInteraction] Indicates that on devices with sufficiently large screens, a notification should remain + * active until the user clicks or dismisses it. If this value is absent or false, the desktop version of Chrome + * will auto-minimize notifications after approximately twenty seconds. The default value is false. + * @param [tag] An ID for a given notification that allows you to find, replace, or remove the notification using + * script if necessary. + * @param [vibrate] A vibration pattern to run with the display of the notification. A vibration pattern can be an + * array with as few as one member. The values are times in milliseconds where the even indices (0, 2, 4, etc.) indicate + * how long to vibrate and the odd indices indicate how long to pause. For example [300, 100, 400] would vibrate + * 300ms, pause 100ms, then vibrate 400ms. + * @param [data] Arbitrary data that you want associated with the notification. This can be of any data type. + */ +interface ServiceWorkerNotificationOptions { + actions?: NotificationAction[]; + badge?: string; + body?: string; + dir?: 'auto' | 'ltr' | 'rtl'; + icon?: string; + lang?: string; + renotify?: boolean; + requireInteraction?: boolean; + tag?: string; + vibrate?: number[]; + data?: any; +} + +/** + * An options object that can contain options to filter notifications. + * @param [tag] A DOMString representing a notification tag. If specified, only notifications that have this tag + * will be returned. + */ +interface ServiceWorkerGetNotificationOptions { + tag: string; +} + /** * Provides an object representing the service worker as an overall unit in the * network ecosystem, including facilities to register, unregister and update @@ -629,10 +707,6 @@ interface ServiceWorkerContainer extends EventTarget { * * @param scriptURL The URL of the service worker script. * @param [options] An options object to provide options upon registration. - * Currently available options are: scope: A USVString representing a URL - * that defines a service worker's registration scope; what range of URLs a - * service worker can control. This is usually a relative URL, and it - * defaults to '/' when not specified. */ register(scriptURL: string, options?: ServiceWorkerRegisterOptions): Promise; diff --git a/service_worker_api/service_worker_api-tests.ts b/service_worker_api/service_worker_api-tests.ts index 5cfae785cc..27c2b85c20 100644 --- a/service_worker_api/service_worker_api-tests.ts +++ b/service_worker_api/service_worker_api-tests.ts @@ -191,3 +191,16 @@ self.addEventListener('notificationclick', (event: NotificationEvent) => { return self.clients.openWindow('/'); })); }); + +navigator.serviceWorker.ready.then(function(registration) { + registration.showNotification('Notification Sample', { + body: 'This is a sample notification!', + icon: '/sw-test/star-wars-logo.jpg', + tag: 'notification-sample' + }); +}); + +self.registration.getNotifications({tag: 'notification-sample'}) + .then(function(notifications) { + console.log(notifications); + }); diff --git a/stream-buffers/index.d.ts b/stream-buffers/index.d.ts new file mode 100644 index 0000000000..d3871b1efa --- /dev/null +++ b/stream-buffers/index.d.ts @@ -0,0 +1,40 @@ +// Type definitions for stream-buffers 3.0 +// Project: https://github.com/samcday/node-stream-buffer#readme +// Definitions by: Jason Dent +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +import * as stream from 'stream'; + +export interface WritableStreamBufferOptions extends stream.WritableOptions { + initialSize?: number; + incrementAmount?: number; +} + +export declare class WritableStreamBuffer extends stream.Writable { + constructor(options?: WritableStreamBufferOptions); + size(): number; + maxSize(): number; + getContents(length?: number): any; + getContentsAsString(encoding?: string, length?: number): string; +} + +export interface ReadableStreamBufferOptions extends stream.ReadableOptions { + frequency?: number; + chunkSize?: number; + initialSize?: number; + incrementAmount?: number; +} + +export declare class ReadableStreamBuffer extends stream.Readable { + constructor(options?: ReadableStreamBufferOptions); + put(data: string | Buffer, encoding?: string): void; + stop(): void; + size(): number; + maxSize(): number; +} + +export declare const DEFAULT_INITIAL_SIZE: number; +export declare const DEFAULT_INCREMENT_AMOUNT: number; +export declare const DEFAULT_FREQUENCY: number; +export declare const DEFAULT_CHUNK_SIZE: number; diff --git a/stream-buffers/stream-buffers-tests.ts b/stream-buffers/stream-buffers-tests.ts new file mode 100644 index 0000000000..2a1a1f35f8 --- /dev/null +++ b/stream-buffers/stream-buffers-tests.ts @@ -0,0 +1,48 @@ +import * as streamBuffers from 'stream-buffers'; + +// The following are examples from README.md +// https://github.com/samcday/node-stream-buffer + +var myWritableStreamBuffer = new streamBuffers.WritableStreamBuffer({ + initialSize: (100 * 1024), // start at 100 kilobytes. + incrementAmount: (10 * 1024) // grow by 10 kilobytes each time buffer overflows. +}); + +var a = streamBuffers.DEFAULT_INITIAL_SIZE; // (8 * 1024) +var b = streamBuffers.DEFAULT_INCREMENT_AMOUNT; // (8 * 1024) +var c = streamBuffers.DEFAULT_CHUNK_SIZE; // (1024) +var d = streamBuffers.DEFAULT_FREQUENCY; // (1) + +const buffer = new Buffer('ASDF'); +myWritableStreamBuffer.write('ASDF'); +myWritableStreamBuffer.write(buffer); +myWritableStreamBuffer.size(); +myWritableStreamBuffer.maxSize(); + +// Gets all held data as a Buffer. +myWritableStreamBuffer.getContents(); + +// Gets all held data as a utf8 string. +myWritableStreamBuffer.getContentsAsString('utf8'); + +// Gets first 5 bytes as a Buffer. +myWritableStreamBuffer.getContents(5); + +// Gets first 5 bytes as a utf8 string. +myWritableStreamBuffer.getContentsAsString('utf8', 5); + +var myReadableStreamBuffer = new streamBuffers.ReadableStreamBuffer({ + frequency: 10, // in milliseconds. + chunkSize: 2048 // in bytes. +}); + +myReadableStreamBuffer.put('A String', 'utf8'); +myReadableStreamBuffer.put(buffer); + +myReadableStreamBuffer.on('data', function(data) { + // streams1.x style data + // assert.isTrue(data instanceof Buffer); +}); + +myReadableStreamBuffer.put('the last data this stream will ever see'); +myReadableStreamBuffer.stop(); diff --git a/stream-buffers/tsconfig.json b/stream-buffers/tsconfig.json new file mode 100644 index 0000000000..827ea2a3fe --- /dev/null +++ b/stream-buffers/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "stream-buffers-tests.ts" + ] +} diff --git a/stream-buffers/tslint.json b/stream-buffers/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/stream-buffers/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/stringify-object/index.d.ts b/stringify-object/index.d.ts new file mode 100644 index 0000000000..bfccb83300 --- /dev/null +++ b/stringify-object/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for stringify-object 3.1 +// Project: https://github.com/yeoman/stringify-object +// Definitions by: Chris Khoo +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace stringifyObject { } + +declare function stringifyObject(o: any, options?: { + indent?: string, + singleQuotes?: boolean, + filter?: (o: any, prop: string) => boolean, + inlineCharacterLimit?: number +}): string; + +export = stringifyObject; diff --git a/stringify-object/stringify-object-tests.ts b/stringify-object/stringify-object-tests.ts new file mode 100644 index 0000000000..a00be6f1c0 --- /dev/null +++ b/stringify-object/stringify-object-tests.ts @@ -0,0 +1,26 @@ +import * as stringifyObject from 'stringify-object'; + +stringifyObject({ a: 1, b: 2, c: 3 }); + +stringifyObject('abc', { + indent: ' ' +}); + +stringifyObject('123', { + indent: ' ' +}); + +stringifyObject(123, { + indent: ' ', + singleQuotes: false +}); + +stringifyObject([1, 2, 3], { + indent: ' ', + singleQuotes: false, + inlineCharacterLimit: 12 +}); + +stringifyObject([1, 2, 3], { + filter: (o, prop) => prop !== '_hidden_' +}); diff --git a/stringify-object/tsconfig.json b/stringify-object/tsconfig.json new file mode 100644 index 0000000000..00574d2429 --- /dev/null +++ b/stringify-object/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "stringify-object-tests.ts" + ] +} diff --git a/stringify-object/tslint.json b/stringify-object/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/stringify-object/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/supertest-as-promised/supertest-as-promised-tests.ts b/supertest-as-promised/supertest-as-promised-tests.ts index c20f9a92b6..35cbc68388 100644 --- a/supertest-as-promised/supertest-as-promised-tests.ts +++ b/supertest-as-promised/supertest-as-promised-tests.ts @@ -1,9 +1,9 @@ - -/// - import * as request from 'supertest-as-promised'; import * as express from 'express'; +declare function describe(desc: string, f: () => void): void; +declare function it(desc: string, f: () => void): void; + var app = express(); // chain your requests like you were promised: diff --git a/tcomb/tcomb-tests.ts b/tcomb/tcomb-tests.ts index 02982faae7..7aa7d9a786 100644 --- a/tcomb/tcomb-tests.ts +++ b/tcomb/tcomb-tests.ts @@ -1,8 +1,7 @@ -// ReSharper disable InconsistentNaming -// ReSharper disable WrongExpressionStatement - /// -/// + +declare function describe(desc: string, f: () => void): void; +declare function it(desc: string, f: () => void): void; // tests adapted from/for tcomb's test folder diff --git a/tedious-connection-pool/index.d.ts b/tedious-connection-pool/index.d.ts index d9334f74cd..7d144bfc22 100644 --- a/tedious-connection-pool/index.d.ts +++ b/tedious-connection-pool/index.d.ts @@ -1,14 +1,14 @@ -// Type definitions for tedious-connection-pool +// Type definitions for tedious-connection-pool 1.0 // Project: https://github.com/pekim/tedious-connection-pool // Definitions by: Cyprien Autexier // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// +import events = require('events'); import tedious = require('tedious'); declare namespace tcp { - /** * Extends Tedious Connection with release function */ @@ -20,22 +20,16 @@ declare namespace tcp { } /** - * Acquire function callback signature + * Provides a connection or an error + * @param err error if any + * @param connection issued from the pool */ - export interface ConnectionCallback { - /** - * Provides a connection or an error - * @param err error if any - * @param connection issued from the pool - */ - (err: Error, connection: PooledConnection): void; - } + export type ConnectionCallback = (err: Error, connection: PooledConnection) => void; /** * Pool Configuration interface */ export interface PoolConfig { - /** * Minimum concurrent connections */ @@ -66,15 +60,12 @@ declare namespace tcp { */ acquireTimeout?: number; } - - } /** * Tedious Connection Pool Class */ -declare class tcp { - +declare class tcp extends events.EventEmitter { /** * Connection Pool constructor * @param poolConfig the pool configuration @@ -88,20 +79,10 @@ declare class tcp { */ acquire(callback: tcp.ConnectionCallback): void; - /** - * listens for a specific connection pool event - * @param event the event name - * @param callback invoked when the event is raised - */ - on(event: string, callback: Function): void; - /** * closes opened connections */ drain(): void; } - - - export = tcp; diff --git a/tedious-connection-pool/tedious-connection-pool-tests.ts b/tedious-connection-pool/tedious-connection-pool-tests.ts index 31715e2090..0a2ec38be6 100644 --- a/tedious-connection-pool/tedious-connection-pool-tests.ts +++ b/tedious-connection-pool/tedious-connection-pool-tests.ts @@ -1,11 +1,3 @@ -// Type definitions for tedious-connection-pool -// Project: https://github.com/pekim/tedious-connection-pool -// Definitions by: Cyprien Autexier -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - - -"use strict"; - import ConnectionPool = require("tedious-connection-pool"); import tedious = require("tedious"); @@ -30,7 +22,13 @@ pool.on('error', (err: Error) => { console.error(err); }); -pool.acquire((err: Error, connection: ConnectionPool.PooledConnection) =>{ +pool.once('error', (err: Error) => { + console.error(err); +}); + +pool.removeAllListeners(); + +pool.acquire((err: Error, connection: ConnectionPool.PooledConnection) => { console.log("hurray"); connection.beginTransaction((error: Error): void => {}, "some name"); connection.rollbackTransaction((error: Error): void => {}); diff --git a/tedious-connection-pool/tslint.json b/tedious-connection-pool/tslint.json new file mode 100644 index 0000000000..f9e30021f4 --- /dev/null +++ b/tedious-connection-pool/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "../tslint.json" +} diff --git a/three/index.d.ts b/three/index.d.ts index 7b76100c17..8700df1cbe 100644 --- a/three/index.d.ts +++ b/three/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for three.js 0.83 +// Type definitions for three.js 0.84 // Project: http://mrdoob.github.com/three.js/ -// Definitions by: Kon , Satoru Kimura , Florent Poujol , SereznoKot , HouChunlei +// Definitions by: Kon , Satoru Kimura , Florent Poujol , SereznoKot , HouChunlei , Ivo , David Asmuth // Definitions: https://github.com/borisyankov/DefinitelyTyped /// @@ -1027,9 +1027,6 @@ declare namespace THREE { * @param type The type of event that gets fired. */ dispatchEvent(event: { type: string; [attachment: string]: any; }): void; - - // deprecated - apply(target: any): void; } export interface Event { @@ -2161,14 +2158,18 @@ declare namespace THREE { setPath(path: string): CubeTextureLoader; } - export class BinaryTextureLoader { + export class DataTextureLoader { constructor(manager?: LoadingManager); manager: LoadingManager; load(url: string, onLoad: (dataTexture: DataTexture) => void, onProgress?: (event: ProgressEvent) => void, onError?: (event: ErrorEvent) => void): void; } - export class DataTextureLoader extends BinaryTextureLoader {} + + /** + * @deprecated since 0.84.0. Use DataTextureLoader (renamed) + */ + export class BinaryTextureLoader extends DataTextureLoader {} export class CompressedTextureLoader { constructor(manager?: LoadingManager); @@ -2493,7 +2494,7 @@ declare namespace THREE { constructor(parameters?: MeshLambertMaterialParameters); color: Color; - emissive: number|string; + emissive: Color; emissiveIntensity: number; emissiveMap: Texture; map: Texture; @@ -2847,6 +2848,7 @@ declare namespace THREE { expandByPoint(point: Vector3): Box3; expandByVector(vector: Vector3): Box3; expandByScalar(scalar: number): Box3; + expandByObject(object: Object3D): Box3; containsPoint(point: Vector3): boolean; containsBox(box: Box3): boolean; getParameter(point: Vector3): Vector3; @@ -3343,7 +3345,6 @@ declare namespace THREE { clone(): this; copy(m: this): this; setFromMatrix4(m: Matrix4): Matrix3; - applyToVector3Array(array: ArrayLike, offset?: number, length?: number): ArrayLike; applyToBuffer(buffer: BufferAttribute, offset?: number, length?: number): BufferAttribute; multiplyScalar(s: number): Matrix3; determinant(): number; @@ -3443,7 +3444,6 @@ declare namespace THREE { * Multiplies this matrix by s. */ multiplyScalar(s: number): Matrix4; - applyToVector3Array(array: ArrayLike, offset?: number, length?: number): ArrayLike; applyToBuffer( buffer: BufferAttribute, offset?: number, length?: number): BufferAttribute; /** * Computes determinant of this matrix. @@ -3530,7 +3530,7 @@ declare namespace THREE { /** * Creates a frustum matrix. */ - makeFrustum(left: number, right: number, bottom: number, top: number, near: number, far: number): Matrix4; + makePerspective(left: number, right: number, bottom: number, top: number, near: number, far: number): Matrix4; /** * Creates a perspective projection matrix. @@ -3771,53 +3771,6 @@ declare namespace THREE { z: number; } - /** - * Represents a spline. - * - * @see src/math/Spline.js - */ - export class Spline { - /** - * Initialises the spline with points, which are the places through which the spline will go. - */ - constructor(points: SplineControlPoint[]); - - points: SplineControlPoint[]; - - /** - * Initialises using the data in the array as a series of points. Each value in a must be another array with three values, where a[n] is v, the value for the nth point, and v[0], v[1] and v[2] are the x, y and z coordinates of that point n, respectively. - * - * @param a array of triplets containing x, y, z coordinates - */ - initFromArray(a: number[][]): void; - - /** - * Return the interpolated point at k. - * - * @param k point index - */ - getPoint(k: number): SplineControlPoint; - - /** - * Returns an array with triplets of x, y, z coordinates that correspond to the current control points. - */ - getControlPointsArray(): number[][]; - - /** - * Returns the length of the spline when using nSubDivisions. - * @param nSubDivisions number of subdivisions between control points. Default is 100. - */ - getLength(nSubDivisions?: number): { chunks: number[]; total: number; }; - - /** - * Modifies the spline so that it looks similar to the original but has its points distributed in such way that moving along the spline it's done at a more or less constant speed. The points should also appear more uniformly spread along the curve. - * This is done by resampling the original spline, with the density of sampling controlled by samplingCoef. Here it's interesting to note that denser sampling is not necessarily better: if sampling is too high, you may get weird kinks in curvature. - * - * @param samplingCoef how many intermediate values to use between spline points - */ - reparametrizeByArcLength(samplingCoef: number): void; - } - class Triangle { constructor(a?: Vector3, b?: Vector3, c?: Vector3); @@ -4107,7 +4060,7 @@ declare namespace THREE { toArray(xy?: number[], offset?: number): number[]; - fromAttribute( attribute: BufferAttribute, index: number, offset?: number): Vector2; + fromBufferAttribute( attribute: BufferAttribute, index: number, offset?: number): Vector2; rotateAround( center: Vector2, angle: number ): Vector2; } @@ -4202,7 +4155,6 @@ declare namespace THREE { applyAxisAngle(axis: Vector3, angle: number): Vector3; applyMatrix3(m: Matrix3): Vector3; applyMatrix4(m: Matrix4): Vector3; - applyProjection(m: Matrix4): Vector3; applyQuaternion(q: Quaternion): Vector3; project(camrea: Camera): Vector3; unproject(camera: Camera): Vector3; @@ -4300,7 +4252,7 @@ declare namespace THREE { fromArray(xyz: number[], offset?: number): Vector3; toArray(xyz?: number[], offset?: number): number[]; - fromAttribute( attribute: BufferAttribute, index: number, offset?: number): Vector3; + fromBufferAttribute( attribute: BufferAttribute, index: number, offset?: number): Vector3; // deprecated getPositionFromMatrix(m: Matrix4): Vector3; @@ -4466,7 +4418,7 @@ declare namespace THREE { toArray(xyzw?: number[], offset?: number): number[]; - fromAttribute( attribute: BufferAttribute, index: number, offset?: number): Vector4; + fromBufferAttribute( attribute: BufferAttribute, index: number, offset?: number): Vector4; } export abstract class Interpolant { @@ -5761,12 +5713,6 @@ declare namespace THREE { } // Extras ///////////////////////////////////////////////////////////////////// - export namespace CurveUtils { - export function tangentQuadraticBezier(t: number, p0: number, p1: number, p2: number): number; - export function tangentCubicBezier(t: number, p0: number, p1: number, p2: number, p3: number): number; - export function tangentSpline(t: number, p0: number, p1: number, p2: number, p3: number): number; - export function interpolate(p0: number, p1: number, p2: number, p3: number, t: number): number; - } export namespace ImageUtils { // deprecated export let crossOrigin: string; @@ -5786,8 +5732,6 @@ declare namespace THREE { export function triangulate(contour: number[], indices: boolean): number[]; export function triangulateShape(contour: number[], holes: any[]): number[]; export function isClockWise(pts: number[]): boolean; - export function b2(t: number, p0: number, p1: number, p2: number): number; - export function b3(t: number, p0: number, p1: number, p2: number, p3: number): number; } // Extras / Audio ///////////////////////////////////////////////////////////////////// @@ -5948,6 +5892,9 @@ declare namespace THREE { */ getTangentAt(u: number): T; + /** + * @deprecated since r84. + */ static create(constructorFunc: Function, getPointFunc: Function): Function; } @@ -6039,6 +5986,13 @@ declare namespace THREE { } // Extras / Curves ///////////////////////////////////////////////////////////////////// + export namespace CurveUtils { + export function tangentQuadraticBezier(t: number, p0: number, p1: number, p2: number): number; + export function tangentCubicBezier(t: number, p0: number, p1: number, p2: number, p3: number): number; + export function tangentSpline(t: number, p0: number, p1: number, p2: number, p3: number): number; + export function interpolate(p0: number, p1: number, p2: number, p3: number, t: number): number; + } + export class CatmullRomCurve3 extends Curve { constructor(points?: Vector3[]); @@ -6047,9 +6001,6 @@ declare namespace THREE { getPoint(t: number): Vector3; } - export class ClosedSplineCurve3 extends CatmullRomCurve3 {} // deprecated, use CatmullRomCurve3 - export class SplineCurve3 extends CatmullRomCurve3 {} // will be deprecated, use CatmullRomCurve3 - export class CubicBezierCurve extends Curve { constructor(v0: Vector2, v1: Vector2, v2: Vector2, v3: Vector2); @@ -6416,13 +6367,13 @@ declare namespace THREE { } export interface TextGeometryParameters { - font: Font; - size: number; - height: number; - curveSegments: number; - bevelEnabled: boolean; - bevelThickness: number; - bevelSize: number; + font?: Font; + size?: number; + height?: number; + curveSegments?: number; + bevelEnabled?: boolean; + bevelThickness?: number; + bevelSize?: number; } export class TextGeometry extends ExtrudeGeometry { diff --git a/three/test/canvas/canvas_camera_orthographic.ts b/three/test/canvas/canvas_camera_orthographic.ts index d6f094f03f..78476a95b5 100644 --- a/three/test/canvas/canvas_camera_orthographic.ts +++ b/three/test/canvas/canvas_camera_orthographic.ts @@ -4,8 +4,8 @@ // https://github.com/mrdoob/three.js/blob/master/examples/canvas_camera_orthographic.html () => { - var container, stats; - var camera, scene, renderer; + var container: HTMLDivElement, stats: Stats; + var camera: THREE.OrthographicCamera, scene: THREE.Scene, renderer: THREE.CanvasRenderer; init(); animate(); diff --git a/three/test/canvas/canvas_geometry_cube.ts b/three/test/canvas/canvas_geometry_cube.ts index 006ee8149c..46f26b10c5 100644 --- a/three/test/canvas/canvas_geometry_cube.ts +++ b/three/test/canvas/canvas_geometry_cube.ts @@ -4,11 +4,11 @@ // https://github.com/mrdoob/three.js/blob/master/examples/canvas_geometry_cube.html () => { - var container, stats; + var container: HTMLDivElement, stats: Stats; - var camera, scene, renderer; + var camera: THREE.PerspectiveCamera, scene: THREE.Scene, renderer: THREE.CanvasRenderer; - var cube, plane; + var cube: THREE.Mesh, plane: THREE.Mesh; var targetRotation = 0; var targetRotationOnMouseDown = 0; @@ -104,7 +104,7 @@ // - function onDocumentMouseDown(event) { + function onDocumentMouseDown(event: MouseEvent) { event.preventDefault(); @@ -117,7 +117,7 @@ } - function onDocumentMouseMove(event) { + function onDocumentMouseMove(event: MouseEvent) { mouseX = event.clientX - windowHalfX; @@ -125,7 +125,7 @@ } - function onDocumentMouseUp(event) { + function onDocumentMouseUp(event: MouseEvent) { document.removeEventListener('mousemove', onDocumentMouseMove, false); document.removeEventListener('mouseup', onDocumentMouseUp, false); @@ -133,7 +133,7 @@ } - function onDocumentMouseOut(event) { + function onDocumentMouseOut(event: MouseEvent) { document.removeEventListener('mousemove', onDocumentMouseMove, false); document.removeEventListener('mouseup', onDocumentMouseUp, false); @@ -141,7 +141,7 @@ } - function onDocumentTouchStart(event) { + function onDocumentTouchStart(event: TouchEvent) { if (event.touches.length === 1) { @@ -154,7 +154,7 @@ } - function onDocumentTouchMove(event) { + function onDocumentTouchMove(event: TouchEvent) { if (event.touches.length === 1) { diff --git a/three/test/canvas/canvas_interactive_cubes_tween.ts b/three/test/canvas/canvas_interactive_cubes_tween.ts index a8d318be5b..6d4cd3fce1 100644 --- a/three/test/canvas/canvas_interactive_cubes_tween.ts +++ b/three/test/canvas/canvas_interactive_cubes_tween.ts @@ -5,11 +5,11 @@ // https://github.com/mrdoob/three.js/blob/master/examples/canvas_interactive_cubes_tween.html () => { - var container, stats; - var camera, scene, renderer; + var container: HTMLDivElement, stats: Stats; + var camera: THREE.PerspectiveCamera, scene: THREE.Scene, renderer: THREE.CanvasRenderer; - var raycaster; - var mouse; + var raycaster: THREE.Raycaster; + var mouse: THREE.Vector2; init(); animate(); @@ -85,17 +85,17 @@ } - function onDocumentTouchStart(event) { + function onDocumentTouchStart(event: TouchEvent) { event.preventDefault(); - - event.clientX = event.touches[0].clientX; - event.clientY = event.touches[0].clientY; - onDocumentMouseDown(event); + let usurpedEvent = event as any; + usurpedEvent.clientX = event.touches[0].clientX; + usurpedEvent.clientY = event.touches[0].clientY; + onDocumentMouseDown(usurpedEvent); } - function onDocumentMouseDown(event) { + function onDocumentMouseDown(event: MouseEvent) { event.preventDefault(); diff --git a/three/test/canvas/canvas_lights_pointlights.ts b/three/test/canvas/canvas_lights_pointlights.ts index 16fc02cc2f..6c028abcf8 100644 --- a/three/test/canvas/canvas_lights_pointlights.ts +++ b/three/test/canvas/canvas_lights_pointlights.ts @@ -6,9 +6,9 @@ () => { // ------- variable definitions that does not exist in the original code. These are for typescript. // ------- - var camera, scene, renderer, - light1, light2, light3, - loader, mesh; + var camera: THREE.PerspectiveCamera, scene: THREE.Scene, renderer: THREE.CanvasRenderer, + light1: THREE.PointLight, light2: THREE.PointLight, light3: THREE.PointLight, + loader: THREE.JSONLoader, mesh: THREE.Mesh; init(); animate(); @@ -34,7 +34,7 @@ scene.add(light3); var PI2 = Math.PI * 2; - var program = function (context) { + var program = function (context: CanvasRenderingContext2D) { context.beginPath(); context.arc(0, 0, 0.5, 0, PI2, true); diff --git a/three/test/canvas/canvas_materials.ts b/three/test/canvas/canvas_materials.ts index 24d5b7d8d9..21ca2b3ee1 100644 --- a/three/test/canvas/canvas_materials.ts +++ b/three/test/canvas/canvas_materials.ts @@ -5,10 +5,10 @@ () => { // ------- variable definitions that does not exist in the original code. These are for typescript. - var container, stats; + var container: HTMLDivElement, stats: Stats; - var camera, scene, renderer, objects; - var pointLight; + var camera: THREE.PerspectiveCamera, scene: THREE.Scene, renderer: THREE.CanvasRenderer, objects: THREE.Mesh[]; + var pointLight: THREE.PointLight; init(); animate(); @@ -90,7 +90,7 @@ } var PI2 = Math.PI * 2; - var program = function (context) { + var program = function (context: CanvasRenderingContext2D) { context.beginPath(); context.arc(0, 0, 0.5, 0, PI2, true); @@ -98,9 +98,9 @@ } - // Lights + // Lights - scene.add(new THREE.AmbientLight(Math.random() * 0x202020)); + scene.add(new THREE.AmbientLight(Math.random() * 0x202020)); var directionalLight = new THREE.DirectionalLight(Math.random() * 0xffffff); directionalLight.position.x = Math.random() - 0.5; @@ -154,12 +154,12 @@ } - function loadImage(path) { + function loadImage(path: string) { var image = document.createElement('img'); var texture = new THREE.Texture(image, THREE.UVMapping) - image.onload = function () { texture.needsUpdate = true; }; + image.onload = function () { texture.needsUpdate = true; }; image.src = path; return texture; diff --git a/three/test/canvas/canvas_particles_floor.ts b/three/test/canvas/canvas_particles_floor.ts index a69dac462d..71e121e8d0 100644 --- a/three/test/canvas/canvas_particles_floor.ts +++ b/three/test/canvas/canvas_particles_floor.ts @@ -10,8 +10,8 @@ var AMOUNTX = 50; var AMOUNTY = 50; - var container, stats; - var camera, scene, renderer, particle; + var container: HTMLDivElement, stats: Stats; + var camera: THREE.PerspectiveCamera, scene: THREE.Scene, renderer: THREE.CanvasRenderer, particle: THREE.Sprite; var mouseX = 0, mouseY = 0; var windowHalfX = window.innerWidth / 2; @@ -80,13 +80,13 @@ // - function onDocumentMouseMove(event) { + function onDocumentMouseMove(event: MouseEvent) { mouseX = event.clientX - windowHalfX; mouseY = event.clientY - windowHalfY; } - function onDocumentTouchStart(event) { + function onDocumentTouchStart(event: TouchEvent) { if (event.touches.length > 1) { @@ -97,7 +97,7 @@ } } - function onDocumentTouchMove(event) { + function onDocumentTouchMove(event: TouchEvent) { if (event.touches.length == 1) { diff --git a/three/test/css3d/css3d_periodictable.ts b/three/test/css3d/css3d_periodictable.ts index 5083fd4329..342455ff48 100644 --- a/three/test/css3d/css3d_periodictable.ts +++ b/three/test/css3d/css3d_periodictable.ts @@ -128,11 +128,18 @@ "Uuo", "Ununoctium", "(294)", 18, 7 ]; - var camera, scene, renderer; - var controls; + var camera: THREE.PerspectiveCamera, scene: THREE.Scene, renderer: THREE.CSS3DRenderer; + var controls: THREE.TrackballControls; - var objects = []; - var targets = { table: [], sphere: [], helix: [], grid: [] }; + var objects: THREE.CSS3DObject[] = []; + class Targets { + constructor() {} + public table: THREE.Object3D[] = []; + public sphere: THREE.Object3D[] = []; + public helix: THREE.Object3D[] = []; + public grid: THREE.Object3D[] = []; + } + let targets = new Targets(); init(); animate(); @@ -262,28 +269,28 @@ controls.addEventListener('change', render); var button = document.getElementById('table'); - button.addEventListener('click', function (event) { + button.addEventListener('click', function (event: MouseEvent) { transform(targets.table, 2000); }, false); var button = document.getElementById('sphere'); - button.addEventListener('click', function (event) { + button.addEventListener('click', function (event: MouseEvent) { transform(targets.sphere, 2000); }, false); var button = document.getElementById('helix'); - button.addEventListener('click', function (event) { + button.addEventListener('click', function (event: MouseEvent) { transform(targets.helix, 2000); }, false); var button = document.getElementById('grid'); - button.addEventListener('click', function (event) { + button.addEventListener('click', function (event: MouseEvent) { transform(targets.grid, 2000); @@ -297,7 +304,7 @@ } - function transform(targets, duration) { + function transform(targets: THREE.Object3D[], duration: number) { TWEEN.removeAll(); diff --git a/three/test/css3d/css3d_sprites.ts b/three/test/css3d/css3d_sprites.ts index 50ec5a219c..49177a9453 100644 --- a/three/test/css3d/css3d_sprites.ts +++ b/three/test/css3d/css3d_sprites.ts @@ -8,12 +8,12 @@ // ------- variable definitions that does not exist in the original code. These are for typescript. // ------- - var camera, scene, renderer; - var controls; + var camera: THREE.PerspectiveCamera, scene: THREE.Scene, renderer: THREE.CSS3DRenderer; + var controls: THREE.TrackballControls; var particlesTotal = 512; - var positions = []; - var objects = []; + var positions: number[] = []; + var objects: THREE.CSS3DSprite[] = []; var current = 0; init(); @@ -28,7 +28,7 @@ scene = new THREE.Scene(); var image = document.createElement('img'); - image.addEventListener('load', function (event) { + image.addEventListener('load', function (event: Event) { for (var i = 0; i < particlesTotal; i++) { @@ -36,7 +36,7 @@ object.position.x = Math.random() * 4000 - 2000, object.position.y = Math.random() * 4000 - 2000, object.position.z = Math.random() * 4000 - 2000 - scene.add(object); + scene.add(object); objects.push(object); diff --git a/three/test/math/test_unit_math.ts b/three/test/math/test_unit_math.ts index 91f656b8e5..c70868b3d8 100644 --- a/three/test/math/test_unit_math.ts +++ b/three/test/math/test_unit_math.ts @@ -524,7 +524,7 @@ declare function equal(a: T, b: T, desc?: string): void; ok( b.clone().union( c ).equals( c ), "Passed!" ); }); - var compareBox = function ( a, b, threshold? ) { + var compareBox = function ( a: THREE.Box3, b: THREE.Box3, threshold?: number ) { threshold = threshold || 0.0001; return ( a.min.distanceTo( b.min ) < threshold && a.max.distanceTo( b.max ) < threshold ); @@ -768,7 +768,7 @@ declare function equal(a: T, b: T, desc?: string): void; var eulerAxyz = new THREE.Euler( 1, 0, 0, "XYZ" ); var eulerAzyx = new THREE.Euler( 0, 1, 0, "ZYX" ); - var matrixEquals4 = function( a, b ) { + var matrixEquals4 = function( a: THREE.Matrix4, b: THREE.Matrix4 ) { var tolerance = 0.0001; if( a.elements.length != b.elements.length ) { return false; @@ -782,14 +782,14 @@ declare function equal(a: T, b: T, desc?: string): void; return true; }; - var eulerEquals = function (a, b, tolerance?: any) { + var eulerEquals = function (a: THREE.Euler, b: THREE.Euler, tolerance?: number) { tolerance = tolerance || 0.0001; var diff = Math.abs(a.x - b.x) + Math.abs(a.y - b.y) + Math.abs(a.z - b.z); return (diff < tolerance); }; - var quatEquals = function (a, b, tolerance?: any) { + var quatEquals = function (a: THREE.Quaternion, b: THREE.Quaternion, tolerance?: number) { tolerance = tolerance || 0.0001; var diff = Math.abs(a.x - b.x) + Math.abs(a.y - b.y) + Math.abs(a.z - b.z) + Math.abs(a.w - b.w); return (diff < tolerance); @@ -843,7 +843,7 @@ declare function equal(a: T, b: T, desc?: string): void; var v2 = new THREE.Euler().setFromQuaternion( q, v.order ); var q2 = new THREE.Quaternion().setFromEuler( v2 ); - ok(eulerEquals(q, q2), "Passed!"); + ok(quatEquals(q, q2), "Passed!"); } }); @@ -899,7 +899,7 @@ declare function equal(a: T, b: T, desc?: string): void; var unit3 = new THREE.Vector3( 1, 0, 0 ); - var planeEquals = function ( a, b, tolerance ) { + var planeEquals = function ( a: THREE.Plane, b: THREE.Plane, tolerance: number ) { tolerance = tolerance || 0.0001; if( a.normal.distanceTo( b.normal ) > tolerance ) { return false; @@ -981,7 +981,7 @@ declare function equal(a: T, b: T, desc?: string): void; }); test( "setFromMatrix/makeFrustum/containsPoint", function() { - var m = new THREE.Matrix4().makeFrustum( -1, 1, -1, 1, 1, 100 ) + var m = new THREE.Matrix4().makePerspective( -1, 1, -1, 1, 1, 100 ) var a = new THREE.Frustum().setFromMatrix( m ); ok( ! a.containsPoint( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" ); @@ -1000,7 +1000,7 @@ declare function equal(a: T, b: T, desc?: string): void; }); test( "setFromMatrix/makeFrustum/intersectsSphere", function() { - var m = new THREE.Matrix4().makeFrustum( -1, 1, -1, 1, 1, 100 ) + var m = new THREE.Matrix4().makePerspective( -1, 1, -1, 1, 1, 100 ) var a = new THREE.Frustum().setFromMatrix( m ); ok( ! a.intersectsSphere( new THREE.Sphere( new THREE.Vector3( 0, 0, 0 ), 0 ) ), "Passed!" ); @@ -1116,7 +1116,7 @@ declare function equal(a: T, b: T, desc?: string): void; // -------------------------------------------- Matrix3 - var matrixEquals3 = function( a, b, tolerance? ) { + var matrixEquals3 = function( a: THREE.Matrix, b: THREE.Matrix, tolerance?: number ) { tolerance = tolerance || 0.0001; if( a.elements.length != b.elements.length ) { return false; @@ -1131,7 +1131,7 @@ declare function equal(a: T, b: T, desc?: string): void; }; - var toMatrix4 = function( m3 ) { + var toMatrix4 = function( m3: THREE.Matrix3 ) { var result = new THREE.Matrix4(); var re = result.elements; var me = m3.elements; @@ -1330,20 +1330,6 @@ declare function equal(a: T, b: T, desc?: string): void; // -------------------------------------------- Matrix4 - var matrixEquals4 = function (a, b) { - var tolerance = 0.0001; - if( a.elements.length != b.elements.length ) { - return false; - } - for( var i = 0, il = a.elements.length; i < il; i ++ ) { - var delta = a.elements[i] - b.elements[i]; - if( delta > tolerance ) { - return false; - } - } - return true; - }; - test( "constructor", function() { var a = new THREE.Matrix4(); ok( a.determinant() == 1, "Passed!" ); @@ -1514,8 +1500,8 @@ declare function equal(a: T, b: T, desc?: string): void; new THREE.Matrix4().makeRotationZ( -0.3 ), new THREE.Matrix4().makeScale( 1, 2, 3 ), new THREE.Matrix4().makeScale( 1/8, 1/2, 1/3 ), - new THREE.Matrix4().makeFrustum( -1, 1, -1, 1, 1, 1000 ), - new THREE.Matrix4().makeFrustum( -16, 16, -9, 9, 0.1, 10000 ), + new THREE.Matrix4().makePerspective( -1, 1, -1, 1, 1, 1000 ), + new THREE.Matrix4().makePerspective( -16, 16, -9, 9, 0.1, 10000 ), new THREE.Matrix4().makeTranslation( 1, 2, 3 ) ]; @@ -1662,7 +1648,7 @@ declare function equal(a: T, b: T, desc?: string): void; // -------------------------------------------- Plane - var comparePlane = function ( a, b, threshold? ) { + var comparePlane = function ( a: THREE.Plane, b: THREE.Plane, threshold?: number ) { threshold = threshold || 0.0001; return ( a.normal.distanceTo( b.normal ) < threshold && Math.abs( a.constant - b.constant ) < threshold ); @@ -1861,7 +1847,7 @@ declare function equal(a: T, b: T, desc?: string): void; - var qSub = function ( a, b ) { + var qSub = function ( a: THREE.Quaternion, b: THREE.Quaternion ) { var result = new THREE.Quaternion(); result.copy( a ); diff --git a/three/test/webgl/webgl_animation_cloth.ts b/three/test/webgl/webgl_animation_cloth.ts index 52e36bb04b..fff733c9c0 100644 --- a/three/test/webgl/webgl_animation_cloth.ts +++ b/three/test/webgl/webgl_animation_cloth.ts @@ -15,8 +15,8 @@ // ------- /* testing cloth simulation */ - var pinsFormation = []; - var pins = [6]; + var pinsFormation: number[][] = []; + var pins: number[] = [6]; pinsFormation.push(pins); @@ -52,7 +52,7 @@ var sphere: THREE.Mesh; var object: THREE.Mesh; var arrow: THREE.ArrowHelper; - var light: THREE.DirectionalLight, materials; + var light: THREE.DirectionalLight; var rotate = true; init(); diff --git a/three/test/webgl/webgl_animation_skinning_morph.ts b/three/test/webgl/webgl_animation_skinning_morph.ts index 167a98d4d2..df085e9ac4 100644 --- a/three/test/webgl/webgl_animation_skinning_morph.ts +++ b/three/test/webgl/webgl_animation_skinning_morph.ts @@ -107,7 +107,7 @@ var loader = new THREE.JSONLoader(); loader.load( "models/skinned/knight.js", function ( geometry, materials ) { - createScene( geometry, materials, 0, FLOOR, -300, 60 ) + createScene( geometry, materials as THREE.MeshPhongMaterial[], 0, FLOOR, -300, 60 ) } ); @@ -133,7 +133,7 @@ } - function createScene( geometry, materials, x, y, z, s ) { + function createScene( geometry: THREE.Geometry, materials: THREE.MeshPhongMaterial[], x: number, y: number, z: number, s: number ) { //ensureLoop( geometry.animation ); @@ -203,7 +203,7 @@ } - function onDocumentMouseMove( event ) { + function onDocumentMouseMove( event: MouseEvent ) { mouseX = ( event.clientX - windowHalfX ); mouseY = ( event.clientY - windowHalfY ); diff --git a/three/test/webgl/webgl_camera.ts b/three/test/webgl/webgl_camera.ts index ed695084a2..66b60a7826 100644 --- a/three/test/webgl/webgl_camera.ts +++ b/three/test/webgl/webgl_camera.ts @@ -14,9 +14,9 @@ var renderer: THREE.WebGLRenderer; var mesh: THREE.Mesh; - var cameraRig, activeCamera, activeHelper; - var cameraPerspective, cameraOrtho; - var cameraPerspectiveHelper, cameraOrthoHelper; + var cameraRig: THREE.Group, activeCamera: THREE.PerspectiveCamera | THREE.OrthographicCamera, activeHelper: THREE.CameraHelper; + var cameraPerspective: THREE.PerspectiveCamera, cameraOrtho: THREE.OrthographicCamera; + var cameraPerspectiveHelper: THREE.CameraHelper, cameraOrthoHelper: THREE.CameraHelper; init(); animate(); @@ -128,7 +128,7 @@ // - function onKeyDown ( event ) { + function onKeyDown ( event: KeyboardEvent ) { switch( event.keyCode ) { @@ -152,7 +152,7 @@ // - function onWindowResize( event ) { + function onWindowResize( event: Event ) { SCREEN_WIDTH = window.innerWidth; SCREEN_HEIGHT = window.innerHeight; diff --git a/three/test/webgl/webgl_custom_attributes.ts b/three/test/webgl/webgl_custom_attributes.ts index 38732c2f67..89c25e62cf 100644 --- a/three/test/webgl/webgl_custom_attributes.ts +++ b/three/test/webgl/webgl_custom_attributes.ts @@ -6,11 +6,11 @@ () => { if (!Detector.webgl) Detector.addGetWebGLMessage(); - var renderer, scene, camera, stats; + var renderer: THREE.WebGLRenderer, scene: THREE.Scene, camera: THREE.PerspectiveCamera, stats: Stats; - var sphere, uniforms; + var sphere: THREE.Mesh, uniforms: { amplitude: { type: string; value: number; }; color: { type: string; value: THREE.Color; }; texture: { type: string; value: THREE.Texture; }; }; - var displacement, noise; + var displacement: Float32Array, noise: Float32Array; init(); animate(); @@ -45,8 +45,8 @@ var geometry = new THREE.SphereBufferGeometry( radius, segments, rings ); - displacement = new Float32Array( geometry.attributes["position"].count ); - noise = new Float32Array( geometry.attributes["position"].count ); + displacement = new Float32Array( geometry.getAttribute('position').count ); + noise = new Float32Array( geometry.getAttribute('position').count ); for ( var i = 0; i < displacement.length; i ++ ) { @@ -116,7 +116,7 @@ } - sphere.geometry.attributes.displacement.needsUpdate = true; + ((sphere.geometry as THREE.BufferGeometry).getAttribute('displacement')as THREE.BufferAttribute).needsUpdate = true; renderer.render(scene, camera); diff --git a/three/test/webgl/webgl_geometries.ts b/three/test/webgl/webgl_geometries.ts index e21e0e99c0..9b23dcfa1f 100644 --- a/three/test/webgl/webgl_geometries.ts +++ b/three/test/webgl/webgl_geometries.ts @@ -6,9 +6,9 @@ () => { if (!Detector.webgl) Detector.addGetWebGLMessage(); - var container, stats; + var container: HTMLDivElement, stats: Stats; - var camera, scene, renderer; + var camera: THREE.PerspectiveCamera, scene: THREE.Scene, renderer: THREE.WebGLRenderer; init(); animate(); @@ -23,7 +23,7 @@ scene = new THREE.Scene(); - var light, object; + var light: THREE.DirectionalLight, object: THREE.Mesh | THREE.AxisHelper | THREE.ArrowHelper; scene.add(new THREE.AmbientLight(0x404040)); @@ -79,7 +79,7 @@ // - var points = []; + var points: THREE.Vector3[] = []; for (var i = 0; i < 50; i++) { diff --git a/three/test/webgl/webgl_helpers.ts b/three/test/webgl/webgl_helpers.ts index 13ed1f4dc0..db8cba89a7 100644 --- a/three/test/webgl/webgl_helpers.ts +++ b/three/test/webgl/webgl_helpers.ts @@ -4,8 +4,8 @@ // https://github.com/mrdoob/three.js/blob/master/examples/webgl_helpers.html () => { - var scene, renderer; - var camera, light; + var scene: THREE.Scene, renderer: THREE.WebGLRenderer; + var camera: THREE.PerspectiveCamera, light: THREE.PointLight; init(); animate(); diff --git a/three/test/webgl/webgl_interactive_cubes.ts b/three/test/webgl/webgl_interactive_cubes.ts index 952239b626..74493a5285 100644 --- a/three/test/webgl/webgl_interactive_cubes.ts +++ b/three/test/webgl/webgl_interactive_cubes.ts @@ -4,10 +4,10 @@ // https://github.com/mrdoob/three.js/blob/master/examples/webgl_interactive_cubes.html () => { - var container, stats; - var camera, scene, raycaster, renderer; + var container: HTMLDivElement, stats: Stats; + var camera: THREE.PerspectiveCamera, scene: THREE.Scene, raycaster: THREE.Raycaster, renderer: THREE.WebGLRenderer; - var mouse = new THREE.Vector2(), INTERSECTED; + var mouse = new THREE.Vector2(), INTERSECTED: THREE.Mesh | null; var radius = 100, theta = 0; init(); @@ -87,7 +87,7 @@ } - function onDocumentMouseMove(event) { + function onDocumentMouseMove(event: MouseEvent) { event.preventDefault(); @@ -107,6 +107,8 @@ } + let INTERSECTED_currentHex = 0; + function render() { theta += 0.1; @@ -116,7 +118,7 @@ camera.position.z = radius * Math.cos(THREE.Math.degToRad(theta)); camera.lookAt(scene.position); - camera.updateMatrixWorld(); + camera.updateMatrixWorld(false); // find intersections @@ -128,17 +130,17 @@ if (INTERSECTED != intersects[0].object) { - if (INTERSECTED) INTERSECTED.material.emissive.setHex(INTERSECTED.currentHex); + if (INTERSECTED) (INTERSECTED.material as THREE.MeshLambertMaterial).emissive.setHex(INTERSECTED_currentHex); - INTERSECTED = intersects[0].object; - INTERSECTED.currentHex = INTERSECTED.material.emissive.getHex(); - INTERSECTED.material.emissive.setHex(0xff0000); + INTERSECTED = intersects[0].object as THREE.Mesh; + INTERSECTED_currentHex = (INTERSECTED.material as THREE.MeshLambertMaterial).emissive.getHex(); + (INTERSECTED.material as THREE.MeshLambertMaterial).emissive.setHex(0xff0000); } } else { - if (INTERSECTED) INTERSECTED.material.emissive.setHex(INTERSECTED.currentHex); + if (INTERSECTED) (INTERSECTED.material as THREE.MeshLambertMaterial).emissive.setHex(INTERSECTED_currentHex); INTERSECTED = null; diff --git a/three/test/webgl/webgl_interactive_raycasting_points.ts b/three/test/webgl/webgl_interactive_raycasting_points.ts index 4c1f5ec2c6..6fdb24b6cc 100644 --- a/three/test/webgl/webgl_interactive_raycasting_points.ts +++ b/three/test/webgl/webgl_interactive_raycasting_points.ts @@ -13,14 +13,14 @@ if (!Detector.webgl) Detector.addGetWebGLMessage(); - var renderer, scene, camera, stats; - var pointclouds; - var raycaster; + var renderer: THREE.WebGLRenderer, scene: THREE.Scene, camera: THREE.PerspectiveCamera, stats: Stats; + var pointclouds: THREE.Points[]; + var raycaster: THREE.Raycaster; var mouse = new THREE.Vector2(); - var intersection = null; - var spheres = []; + var intersection: THREE.Intersection | null = null; + var spheres: THREE.Mesh[] = []; var spheresIndex = 0; - var clock; + var clock: THREE.Clock; var threshold = 0.1; var pointSize = 0.05; @@ -31,7 +31,7 @@ init(); animate(); - function generatePointCloudGeometry(color, width, length) { + function generatePointCloudGeometry(color: THREE.Color, width: number, length: number) { var geometry = new THREE.BufferGeometry(); var numPoints = width * length; @@ -74,7 +74,7 @@ } - function generatePointcloud(color, width, length) { + function generatePointcloud(color: THREE.Color, width: number, length: number) { var geometry = generatePointCloudGeometry(color, width, length); @@ -85,7 +85,7 @@ } - function generateIndexedPointcloud(color, width, length) { + function generateIndexedPointcloud(color: THREE.Color, width: number, length: number) { var geometry = generatePointCloudGeometry(color, width, length); var numPoints = width * length; @@ -113,7 +113,7 @@ } - function generateIndexedWithOffsetPointcloud(color, width, length) { + function generateIndexedWithOffsetPointcloud(color: THREE.Color, width: number, length: number) { var geometry = generatePointCloudGeometry(color, width, length); var numPoints = width * length; @@ -142,11 +142,11 @@ } - function generateRegularPointcloud(color, width, length) { + function generateRegularPointcloud(color: THREE.Color, width: number, length: number) { var geometry = new THREE.Geometry(); - var colors = []; + var colors: THREE.Color[] = []; var k = 0; @@ -160,15 +160,9 @@ var y = ( Math.cos(u * Math.PI * 8) + Math.sin(v * Math.PI * 8) ) / 20; var z = v - 0.5; var v2 = new THREE.Vector3(x, y, z); - - var intensity = ( y + 0.1 ) * 7; - colors[3 * k] = color.r * intensity; - colors[3 * k + 1] = color.g * intensity; - colors[3 * k + 2] = color.b * intensity; - geometry.vertices.push(v2); + var intensity = ( y + 0.1 ) * 7; colors[k] = ( color.clone().multiplyScalar(intensity) ); - k++; } @@ -260,7 +254,7 @@ } - function onDocumentMouseMove(event) { + function onDocumentMouseMove(event: MouseEvent) { event.preventDefault(); @@ -292,7 +286,7 @@ function render() { camera.applyMatrix(rotateY); - camera.updateMatrixWorld(); + camera.updateMatrixWorld(false); raycaster.setFromCamera(mouse, camera); diff --git a/three/test/webgl/webgl_lensflares.ts b/three/test/webgl/webgl_lensflares.ts index 1223a0dc7c..1d100507a0 100644 --- a/three/test/webgl/webgl_lensflares.ts +++ b/three/test/webgl/webgl_lensflares.ts @@ -8,14 +8,12 @@ var controls: any; // ------- - var container, stats; + var container: HTMLDivElement, stats: Stats; - var camera, scene, renderer; + var camera: THREE.PerspectiveCamera, scene: THREE.Scene, renderer: THREE.WebGLRenderer; var clock = new THREE.Clock(); - var composer; - init(); animate(); @@ -37,9 +35,9 @@ controls.autoForward = false; controls.dragToLook = false - // scene + // scene - scene = new THREE.Scene(); + scene = new THREE.Scene(); scene.fog = new THREE.Fog(0x000000, 3500, 15000); scene.fog.color.setHSL(0.51, 0.4, 0.01); @@ -94,7 +92,7 @@ addLight(0.08, 0.8, 0.5, 0, 0, -1000); addLight(0.995, 0.5, 0.9, 5000, 5000, -1000); - function addLight(h, s, l, x, y, z) { + function addLight(h: number, s: number, l: number, x: number, y: number, z: number) { var light = new THREE.PointLight(0xffffff, 1.5, 4500); light.color.setHSL(h, s, l); @@ -148,10 +146,10 @@ // - function lensFlareUpdateCallback(object) { + function lensFlareUpdateCallback(object: THREE.LensFlare) { - var f, fl = object.lensFlares.length; - var flare; + var f: number, fl = object.lensFlares.length; + var flare: THREE.LensFlareProperty; var vecX = -object.positionScreen.x * 2; var vecY = -object.positionScreen.y * 2; @@ -174,7 +172,7 @@ // - function onWindowResize(event) { + function onWindowResize(event: Event) { renderer.setSize(window.innerWidth, window.innerHeight); diff --git a/three/test/webgl/webgl_lights_hemisphere.ts b/three/test/webgl/webgl_lights_hemisphere.ts index 95c7aa914b..46dd9f7157 100644 --- a/three/test/webgl/webgl_lights_hemisphere.ts +++ b/three/test/webgl/webgl_lights_hemisphere.ts @@ -10,9 +10,9 @@ if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - var camera, scene, renderer, dirLight, hemiLight; - var mixers = []; - var stats; + var camera: THREE.PerspectiveCamera, scene: THREE.Scene, renderer: THREE.WebGLRenderer, dirLight: THREE.DirectionalLight, hemiLight: THREE.HemisphereLight; + var mixers: THREE.AnimationMixer[] = []; + var stats: Stats; var clock = new THREE.Clock(); @@ -169,7 +169,7 @@ } - function onKeyDown ( event ) { + function onKeyDown ( event: KeyboardEvent ) { switch ( event.keyCode ) { diff --git a/three/test/webgl/webgl_lines_colors.ts b/three/test/webgl/webgl_lines_colors.ts index bb54df8208..6b359b2d65 100644 --- a/three/test/webgl/webgl_lines_colors.ts +++ b/three/test/webgl/webgl_lines_colors.ts @@ -11,21 +11,21 @@ if (!Detector.webgl) Detector.addGetWebGLMessage(); - var effectFXAA; + var effectFXAA: THREE.ShaderPass; var mouseX = 0, mouseY = 0, windowHalfX = window.innerWidth / 2, windowHalfY = window.innerHeight / 2, - camera, scene, renderer, material, composer; + camera: THREE.PerspectiveCamera, scene: THREE.Scene, renderer: THREE.WebGLRenderer, material: THREE.LineBasicMaterial, composer: THREE.EffectComposer; init(); animate(); function init() { - var i, container; + var i: number, container: HTMLDivElement; container = document.createElement('div'); document.body.appendChild(container); @@ -46,7 +46,9 @@ geometry2 = new THREE.Geometry(), geometry3 = new THREE.Geometry(), points = hilbert3D(new THREE.Vector3(0, 0, 0), 200.0, 2, 0, 1, 2, 3, 4, 5, 6, 7), - colors = [], colors2 = [], colors3 = []; + colors: THREE.Color[] = [], + colors2: THREE.Color[] = [], + colors3: THREE.Color[] = []; for (i = 0; i < points.length; i++) { @@ -73,7 +75,7 @@ material = new THREE.LineBasicMaterial({ color: 0xffffff, opacity: 1, linewidth: 3, vertexColors: THREE.VertexColors }); - var line, scale = 0.3, d = 225; + var line: THREE.Line, scale = 0.3, d = 225; var parameters : [THREE.LineBasicMaterial, number, [number, number, number], THREE.Geometry][] = [ [material, scale * 1.5, [-d, 0, 0], geometry], [material, scale * 1.5, [0, 0, 0], geometry2], @@ -146,14 +148,14 @@ // - function onDocumentMouseMove(event) { + function onDocumentMouseMove(event: MouseEvent) { mouseX = event.clientX - windowHalfX; mouseY = event.clientY - windowHalfY; } - function onDocumentTouchStart(event) { + function onDocumentTouchStart(event: TouchEvent) { if (event.touches.length > 1) { @@ -166,7 +168,7 @@ } - function onDocumentTouchMove(event) { + function onDocumentTouchMove(event: TouchEvent) { if (event.touches.length == 1) { diff --git a/three/test/webgl/webgl_loader_awd.ts b/three/test/webgl/webgl_loader_awd.ts index 94c7e73a9b..01f21a985e 100644 --- a/three/test/webgl/webgl_loader_awd.ts +++ b/three/test/webgl/webgl_loader_awd.ts @@ -10,16 +10,16 @@ if (!Detector.webgl) Detector.addGetWebGLMessage(); - var container, stats; + var container: HTMLDivElement, stats: Stats; - var camera, scene, renderer, objects, controls; - var particleLight, pointLight; - var trunk; + var camera: THREE.PerspectiveCamera, scene: THREE.Scene, renderer: THREE.WebGLRenderer, controls: THREE.OrbitControls; + var pointLight: THREE.PointLight; + var trunk: THREE.Object3D; var loader = new THREE.AWDLoader(); loader.materialFactory = createMaterial; - loader.load('./models/awd/simple/simple.awd', function (_trunk) { + loader.load('./models/awd/simple/simple.awd', function (_trunk: THREE.Object3D) { trunk = _trunk; @@ -29,15 +29,13 @@ }); - function createMaterial(name) { - // console.log( name ); - // var mat = new THREE.MeshPhongMaterial({ - // color: 0xaaaaaa, - // shininess: 20 - - // }); - // return mat; - return null; + function createMaterial(name: string) { + console.log( name ); + var mat = new THREE.MeshPhongMaterial({ + color: 0xaaaaaa, + shininess: 20 + }); + return mat; } @@ -106,7 +104,7 @@ pointLight.position.x = Math.sin(timer * 4) * 3000; pointLight.position.y = 600 - pointLight.position.z = Math.cos(timer * 4) * 3000; + pointLight.position.z = Math.cos(timer * 4) * 3000; renderer.render(scene, camera); diff --git a/three/test/webgl/webgl_materials.ts b/three/test/webgl/webgl_materials.ts index 1c6302ea84..f60da797ce 100644 --- a/three/test/webgl/webgl_materials.ts +++ b/three/test/webgl/webgl_materials.ts @@ -9,12 +9,16 @@ if (!Detector.webgl) Detector.addGetWebGLMessage(); - var container, stats; + var container: HTMLDivElement, stats: Stats; - var camera, scene, renderer, objects; - var particleLight; - - var materials = []; + var camera: THREE.PerspectiveCamera, scene: THREE.Scene, renderer: THREE.WebGLRenderer, objects: THREE.Mesh[]; + var particleLight: THREE.Mesh; + var materials: ( THREE.MeshBasicMaterial | + THREE.MeshPhongMaterial | + THREE.MeshNormalMaterial | + THREE.MeshLambertMaterial | + THREE.MeshFaceMaterial | + THREE.MeshDepthMaterial ) [] = []; init(); animate(); @@ -92,11 +96,11 @@ objects = []; - var sphere, geometry: THREE.Geometry, material; + var sphere: THREE.Mesh, geometry: THREE.Geometry; for (var i = 0, l = materials.length; i < l; i++) { - material = materials[i]; + let material = materials[i]; geometry = material instanceof THREE.MeshFaceMaterial ? geometry_pieces : (material.shading == THREE.FlatShading ? geometry_flat : geometry_smooth); @@ -224,8 +228,8 @@ } - materials[materials.length - 3].emissive.setHSL(0.54, 1, 0.35 * (0.5 + 0.5 * Math.sin(35 * timer))); - materials[materials.length - 4].emissive.setHSL(0.04, 1, 0.35 * (0.5 + 0.5 * Math.cos(35 * timer))); + (materials[materials.length - 3] as THREE.MeshPhongMaterial).emissive.setHSL(0.54, 1, 0.35 * (0.5 + 0.5 * Math.sin(35 * timer))); + (materials[materials.length - 4] as THREE.MeshLambertMaterial).emissive.setHSL(0.04, 1, 0.35 * (0.5 + 0.5 * Math.cos(35 * timer))); particleLight.position.x = Math.sin(timer * 7) * 300; particleLight.position.y = Math.cos(timer * 5) * 400; diff --git a/three/test/webgl/webgl_morphtargets.ts b/three/test/webgl/webgl_morphtargets.ts index 9045f5b201..5368dccb91 100644 --- a/three/test/webgl/webgl_morphtargets.ts +++ b/three/test/webgl/webgl_morphtargets.ts @@ -6,15 +6,13 @@ () => { if (!Detector.webgl) Detector.addGetWebGLMessage(); - var container, stats; + var container: HTMLDivElement; - var camera, scene, renderer; - - var geometry, objects; + var camera: THREE.PerspectiveCamera, scene: THREE.Scene, renderer: THREE.WebGLRenderer; var mouseX = 0, mouseY = 0; - var mesh; + var mesh: THREE.Mesh; var windowHalfX = window.innerWidth / 2; var windowHalfY = window.innerHeight / 2; @@ -49,7 +47,7 @@ for (var i = 0; i < geometry.vertices.length; i++) { - var vertices = []; + var vertices: THREE.Vector3[] = []; for (var v = 0; v < geometry.vertices.length; v++) { @@ -100,7 +98,7 @@ } - function onDocumentMouseMove(event) { + function onDocumentMouseMove(event: MouseEvent) { mouseX = (event.clientX - windowHalfX); mouseY = (event.clientY - windowHalfY) * 2; diff --git a/three/test/webgl/webgl_points_billboards.ts b/three/test/webgl/webgl_points_billboards.ts index 93474493c8..11aa04270b 100644 --- a/three/test/webgl/webgl_points_billboards.ts +++ b/three/test/webgl/webgl_points_billboards.ts @@ -6,8 +6,17 @@ () => { if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); - var container, stats; - var camera, scene, renderer, particles, geometry, material, i, h, color, sprite, size; + var container: HTMLDivElement, stats: Stats; + var camera: THREE.PerspectiveCamera, + scene: THREE.Scene, + renderer: THREE.WebGLRenderer, + particles: THREE.Points, + geometry: THREE.Geometry, + material: THREE.PointsMaterial, + i: number, + h: number, + color: THREE.Color, + sprite: THREE.Texture; var mouseX = 0, mouseY = 0; var windowHalfX = window.innerWidth / 2; @@ -86,14 +95,14 @@ } - function onDocumentMouseMove( event ) { + function onDocumentMouseMove( event: MouseEvent ) { mouseX = event.clientX - windowHalfX; mouseY = event.clientY - windowHalfY; } - function onDocumentTouchStart( event ) { + function onDocumentTouchStart( event: TouchEvent ) { if ( event.touches.length == 1 ) { @@ -105,7 +114,7 @@ } } - function onDocumentTouchMove( event ) { + function onDocumentTouchMove( event: TouchEvent ) { if ( event.touches.length == 1 ) { diff --git a/three/test/webgl/webgl_postprocessing.ts b/three/test/webgl/webgl_postprocessing.ts index cf0b3ffffe..8c298d66a6 100644 --- a/three/test/webgl/webgl_postprocessing.ts +++ b/three/test/webgl/webgl_postprocessing.ts @@ -4,8 +4,8 @@ // https://github.com/mrdoob/three.js/blob/master/examples/webgl_postprocessing.html () => { - var camera, scene, renderer, composer; - var object, light; + var camera: THREE.PerspectiveCamera, scene: THREE.Scene, renderer: THREE.WebGLRenderer, composer: THREE.EffectComposer; + var object: THREE.Object3D, light: THREE.DirectionalLight; init(); animate(); diff --git a/three/test/webgl/webgl_shader.ts b/three/test/webgl/webgl_shader.ts index b43044b8f1..249851d534 100644 --- a/three/test/webgl/webgl_shader.ts +++ b/three/test/webgl/webgl_shader.ts @@ -6,11 +6,11 @@ () => { if (!Detector.webgl) Detector.addGetWebGLMessage(); - var container, stats; + var container: HTMLElement, stats: Stats; - var camera, scene, renderer; + var camera: THREE.Camera, scene: THREE.Scene, renderer: THREE.WebGLRenderer; - var uniforms; + var uniforms: { time: { type: string; value: number; }; resolution: { type: string; value: THREE.Vector2; }; }; init(); animate(); diff --git a/three/test/webgl/webgl_sprites.ts b/three/test/webgl/webgl_sprites.ts index bb7139f5ab..8e71285fac 100644 --- a/three/test/webgl/webgl_sprites.ts +++ b/three/test/webgl/webgl_sprites.ts @@ -8,14 +8,14 @@ var material: THREE.SpriteMaterial; // ------- - var camera, scene, renderer; - var cameraOrtho, sceneOrtho; + var camera: THREE.PerspectiveCamera, scene: THREE.Scene, renderer: THREE.WebGLRenderer; + var cameraOrtho: THREE.OrthographicCamera, sceneOrtho: THREE.Scene; - var spriteTL, spriteTR, spriteBL, spriteBR, spriteC; + var spriteTL: THREE.Sprite, spriteTR: THREE.Sprite, spriteBL: THREE.Sprite, spriteBR: THREE.Sprite, spriteC: THREE.Sprite; - var mapC; + var mapC: THREE.Texture; - var group; + var group: THREE.Group; init(); animate(); @@ -96,7 +96,7 @@ } - function createHUDSprites ( texture ) { + function createHUDSprites ( texture: THREE.Texture ) { var material = new THREE.SpriteMaterial( { map: texture } ); @@ -178,7 +178,7 @@ for ( var i = 0, l = group.children.length; i < l; i ++ ) { - var sprite = group.children[ i ]; + var sprite = group.children[ i ] as THREE.Sprite; var material = sprite.material; var scale = Math.sin( time + sprite.position.x * 0.01 ) * 0.3 + 1.0; diff --git a/three/three-canvasrenderer.d.ts b/three/three-canvasrenderer.d.ts index c37f223c56..3560963a47 100644 --- a/three/three-canvasrenderer.d.ts +++ b/three/three-canvasrenderer.d.ts @@ -6,7 +6,7 @@ declare namespace THREE { export interface SpriteCanvasMaterialParameters extends MaterialParameters { color?: number; - program?: (context: any, color: Color) => void; + program?: (context: CanvasRenderingContext2D, color: Color) => void; } export class SpriteCanvasMaterial extends Material { @@ -14,7 +14,7 @@ declare namespace THREE { color: Color; - program(context: any, color: Color): void; + program(context: CanvasRenderingContext2D, color: Color): void; } export interface CanvasRendererParameters { diff --git a/three/tsconfig.json b/three/tsconfig.json index 37a325d404..1eac096ec9 100644 --- a/three/tsconfig.json +++ b/three/tsconfig.json @@ -5,7 +5,7 @@ "es6", "dom" ], - "noImplicitAny": false, + "noImplicitAny": true, "noImplicitThis": false, "strictNullChecks": false, "baseUrl": "../", diff --git a/tstl/index.d.ts b/tstl/index.d.ts new file mode 100644 index 0000000000..c1bd7d7aeb --- /dev/null +++ b/tstl/index.d.ts @@ -0,0 +1,11136 @@ +// Type definitions for TSTL v1.3.10 +// Project: https://github.com/samchon/tstl +// Definitions by: Jeongho Nam +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "tstl" +{ + export = std; +} + +/** + * # TypeScript-STL + * + * + * + * + * STL (Standard Template Library) Containers and Algorithms for TypeScript. + * + * **T**ypeScript-**STL** is a TypeScript's Standard Template Library who is migrated from C++ STL. Most of classes + * and functions of STL have implemented. Just enjoy it. + * + * @git https://github.com/samchon/tstl + * @author Jeongho Nam + */ +declare namespace std { +} +/** + * Base classes composing STL in background. + * + * @author Jeongho Nam + */ +declare namespace std.base { +} +declare namespace std { + /** + * Apply function to range. + * + * Applies function fn to each of the elements in the range [first, last). + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), + * which contains all the elements between first and last, including the element pointed by + * first but not the element pointed by last. + * @param fn Unary function that accepts an element in the range as argument. This can either be a function p + * ointer or a move constructible function object. Its return value, if any, is ignored. + */ + function for_each, Func extends (val: T) => any>(first: InputIterator, last: InputIterator, fn: Func): Func; + /** + * Apply function to range. + * + * Applies function *fn* to each of the elements in the range [*first*, *first + n*). + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param n the number of elements to apply the function to + * @param fn Unary function that accepts an element in the range as argument. This can either be a function p + * ointer or a move constructible function object. Its return value, if any, is ignored. + * + * @return first + n + */ + function for_each_n>(first: InputIterator, n: number, fn: (val: T) => any): InputIterator; + /** + * Test condition on all elements in range. + * + * Returns true if pred returns true for all the elements in the range + * [first, last) or if the range is {@link Container.empty empty}, and false otherwise. + * + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), + * which contains all the elements between first and last, including the element pointed by + * first but not the element pointed by last. + * @param pred Unary function that accepts an element in the range as argument and returns a value convertible to + * boolean. The value returned indicates whether the element fulfills the condition + * checked by this function. The function shall not modify its argument. + * + * @return true if pred returns true for all the elements in the range or if the range is + * {@link Container.empty empty}, and false otherwise. + */ + function all_of>(first: InputIterator, last: InputIterator, pred: (val: T) => boolean): boolean; + /** + * Test if any element in range fulfills condition. + * + * Returns true if pred returns true for any of the elements in the range + * [first, last), and false otherwise. + * + * If [first, last) is an {@link Container.empty empty} range, the function returns + * false. + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), + * which contains all the elements between first and last, including the element pointed by + * first but not the element pointed by last. + * @param pred Unary function that accepts an element in the range as argument and returns a value convertible to + * boolean. The value returned indicates whether the element fulfills the condition + * checked by this function. The function shall not modify its argument. + * + * @return true if pred returns true for any of the elements in the range + * [first, last), and false otherwise. If [first, last) is an + * {@link Container.empty empty} range, the function returns false. + */ + function any_of>(first: InputIterator, last: InputIterator, pred: (val: T) => boolean): boolean; + /** + * Test if no elements fulfill condition. + * + * Returns true if pred returns false for all the elements in the range + * [first, last) or if the range is {@link Container.empty empty}, and false otherwise. + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), + * which contains all the elements between first and last, including the element pointed by + * first but not the element pointed by last. + * @param pred Unary function that accepts an element in the range as argument and returns a value convertible to + * boolean. The value returned indicates whether the element fulfills the condition + * checked by this function. The function shall not modify its argument. + * + * @return true if pred returns false for all the elements in the range + * [first, last) or if the range is {@link Container.empty empty}, and false + * otherwise. + */ + function none_of>(first: InputIterator, last: InputIterator, pred: (val: T) => boolean): boolean; + /** + * Test whether the elements in two ranges are equal. + * + * Compares the elements in the range [first1, last1) with those in the range beginning at + * first2, and returns true if all of the elements in both ranges match. + * + * @param first1 An {@link Iterator} to the initial position of the first sequence. + * @param last1 An {@link Iterator} to the final position in a sequence. The range used is + * [first1, last1), including the element pointed by first1, but not the element + * pointed by last1. + * @param first2 An {@link Iterator} to the initial position of the second sequence. The comparison includes up to + * as many elements of this sequence as those in the range [first1, last1). + * + * @return true if all the elements in the range [first1, last1) compare equal to those + * of the range starting at first2, and false otherwise. + */ + function equal>(first1: InputIterator, last1: InputIterator, first2: Iterator): boolean; + /** + * Test whether the elements in two ranges are equal. + * + * Compares the elements in the range [first1, last1) with those in the range beginning at + * first2, and returns true if all of the elements in both ranges match. + * + * @param first1 An {@link Iterator} to the initial position of the first sequence. + * @param last1 An {@link Iterator} to the final position in a sequence. The range used is + * [first1, last1), including the element pointed by first1, but not the element + * pointed by last1. + * @param first2 An {@link Iterator} to the initial position of the second sequence. The comparison includes up to + * as many elements of this sequence as those in the range [first1, last1). + * @param pred Binary function that accepts two elements as argument (one of each of the two sequences, in the same + * order), and returns a value convertible to bool. The value returned indicates whether + * the elements are considered to match in the context of this function. + * + * @return true if all the elements in the range [first1, last1) compare equal to those + * of the range starting at first2, and false otherwise. + */ + function equal>(first1: InputIterator, last1: InputIterator, first2: Iterator, pred: (x: T, y: T) => boolean): boolean; + /** + * Lexicographical less-than comparison. + * + * Returns true if the range [first1, last1) compares lexicographically less + * than the range [first2, last2). + * + * A lexicographical comparison is the kind of comparison generally used to sort words alphabetically in + * dictionaries; It involves comparing sequentially the elements that have the same position in both ranges against + * each other until one element is not equivalent to the other. The result of comparing these first non-matching + * elements is the result of the lexicographical comparison. + * + * If both sequences compare equal until one of them ends, the shorter sequence is lexicographically less + * than the longer one. + * + * @param first1 An {@link Iterator} to the initial position of the first sequence. + * @param last1 An {@link Iterator} to the final position in a sequence. The range used is + * [first1, last1), including the element pointed by first1, but not the element + * pointed by last1. + * @param first2 An {@link Iterator} to the initial position of the second sequence. + * @param last2 An {@link Iterator} to the final position of the second sequence. The ranged used is + * [first2, last2). + * + * @return true if the first range compares lexicographically less than than the second. + * false otherwise (including when all the elements of both ranges are equivalent). + */ + function lexicographical_compare, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, last2: Iterator2): boolean; + /** + * Lexicographical comparison. + * + * Returns true if the range [first1, last1) compares lexicographically + * relationship than the range [first2, last2). + * + * A lexicographical comparison is the kind of comparison generally used to sort words alphabetically in + * dictionaries; It involves comparing sequentially the elements that have the same position in both ranges against + * each other until one element is not equivalent to the other. The result of comparing these first non-matching + * elements is the result of the lexicographical comparison. + * + * If both sequences compare equal until one of them ends, the shorter sequence is lexicographically + * relationship than the longer one. + * + * @param first1 An {@link Iterator} to the initial position of the first sequence. + * @param last1 An {@link Iterator} to the final position in a sequence. The range used is + * [first1, last1), including the element pointed by first1, but not the element + * pointed by last1. + * @param first2 An {@link Iterator} to the initial position of the second sequence. + * @param last2 An {@link Iterator} to the final position of the second sequence. The ranged used is + * [first2, last2). + * @param compare Binary function that accepts two arguments of the types pointed by the iterators, and returns a + * value convertible to bool. The value returned indicates whether the first argument is + * considered to go before the second in the specific strict weak ordering it defines. + * + * @return true if the first range compares lexicographically relationship than than the + * second. false otherwise (including when all the elements of both ranges are equivalent). + */ + function lexicographical_compare, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, last2: Iterator2, compare: (x: T, y: T) => boolean): boolean; + /** + * Find value in range. + * + * Returns an iterator to the first element in the range [first, last) that compares equal to + * val. If no such element is found, the function returns last. + * + * The function uses {@link equal_to equal_to} to compare the individual elements to val. + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), + * which contains all the elements between first and last, including the element pointed by + * first but not the element pointed by last. + * @param val Value to search for in the range. + * + * @return An {@link Iterator} to the first element in the range that compares equal to val. If no elements + * match, the function returns last. + */ + function find>(first: InputIterator, last: InputIterator, val: T): InputIterator; + /** + * Find element in range. + * + * Returns an iterator to the first element in the range [first, last) for which pred returns + * true. If no such element is found, the function returns last. + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), + * which contains all the elements between first and last, including the element pointed by + * first but not the element pointed by last. + * @param pred Unary function that accepts an element in the range as argument and returns a value convertible + * to bool. The value returned indicates whether the element is considered a match in + * the context of this function. The function shall not modify its argument. + * + * @return An {@link Iterator} to the first element in the range for which pred does not return + * false. If pred is false for all elements, the function returns + * last. + */ + function find_if>(first: InputIterator, last: InputIterator, pred: (val: T) => boolean): InputIterator; + /** + * Find element in range. + * + * Returns an iterator to the first element in the range [first, last) for which pred returns + * true. If no such element is found, the function returns last. + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), + * which contains all the elements between first and last, including the element pointed by + * first but not the element pointed by last. + * @param pred Unary function that accepts an element in the range as argument and returns a value convertible + * to bool. The value returned indicates whether the element is considered a match in + * the context of this function. The function shall not modify its argument. + * + * @return An {@link Iterator} to the first element in the range for which pred returns false. + * If pred is true for all elements, the function returns last. + */ + function find_if_not>(first: InputIterator, last: InputIterator, pred: (val: T) => boolean): InputIterator; + /** + * Find last subsequence in range. + * + * Searches the range [first1, last1) for the last occurrence of the sequence defined by + * [first2, last2), and returns an {@link Iterator} to its first element, or last1,/i> if no + * occurrences are found. + * + * The elements in both ranges are compared sequentially using {@link equal_to}: A subsequence of + * [first1, last1) is considered a match only when this is true for all the elements of + * [first2, last2). + * + * This function returns the last of such occurrences. For an algorithm that returns the first instead, see + * {@link search}. + * + * @param first1 An {@link Iterator} to the initial position of the first sequence. + * @param last1 An {@link Iterator} to the final position in a sequence. The range used is + * [first1, last1), including the element pointed by first1, but not the element + * pointed by last1. + * @param first2 An {@link Iterator} to the initial position of the element values to be searched for. + * @param last2 An {@link Iterator} to the final position of the element values to be searched for. The range used + * is [first2, last2). + * @param pred Binary function that accepts two elements as arguments (one of each of the two sequences, in the + * same order), and returns a value convertible to bool. The value returned indicates + * whether the elements are considered to match in the context of this function. + * + * @return An {@link Iterator} to the first element of the last occurrence of [first2, last2) in + * [first1, last1). If the sequence is not found, the function returns ,i>last1. Otherwise + * [first2, last2) is an empty range, the function returns last1. + */ + function find_end, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, last2: Iterator2): Iterator1; + /** + * Find last subsequence in range. + * + * Searches the range [first1, last1) for the last occurrence of the sequence defined by + * [first2, last2), and returns an {@link Iterator} to its first element, or last1,/i> if no + * occurrences are found. + * + * The elements in both ranges are compared sequentially using pred: A subsequence of + * [first1, last1) is considered a match only when this is true for all the elements of + * [first2, last2). + * + * This function returns the last of such occurrences. For an algorithm that returns the first instead, see + * {@link search}. + * + * @param first1 An {@link Iterator} to the initial position of the first sequence. + * @param last1 An {@link Iterator} to the final position in a sequence. The range used is + * [first1, last1), including the element pointed by first1, but not the element + * pointed by last1. + * @param first2 An {@link Iterator} to the initial position of the element values to be searched for. + * @param last2 An {@link Iterator} to the final position of the element values to be searched for. The range used + * is [first2, last2). + * @param pred Binary function that accepts two elements as arguments (one of each of the two sequences, in the + * same order), and returns a value convertible to bool. The value returned indicates + * whether the elements are considered to match in the context of this function. + * + * @return An {@link Iterator} to the first element of the last occurrence of [first2, last2) in + * [first1, last1). If the sequence is not found, the function returns ,i>last1. Otherwise + * [first2, last2) is an empty range, the function returns last1. + */ + function find_end, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, last2: Iterator2, pred: (x: T, y: T) => boolean): Iterator1; + /** + * Find element from set in range. + * + * Returns an iterator to the first element in the range [first1, last1) that matches any of the + * elements in [first2, last2). If no such element is found, the function returns last1. + * + * The elements in [first1, last1) are sequentially compared to each of the values in + * [first2, last2) using {@link equal_to}, until a pair matches. + * + * @param first1 An {@link Iterator} to the initial position of the first sequence. + * @param last1 An {@link Iterator} to the final position in a sequence. The range used is + * [first1, last1), including the element pointed by first1, but not the element + * pointed by last1. + * @param first2 An {@link Iterator} to the initial position of the element values to be searched for. + * @param last2 An {@link Iterator} to the final position of the element values to be searched for. The range used + * is [first2, last2). + * + * @return An {@link Iterator} to the first element in [first1, last1) that is part of + * [first2, last2). If no matches are found, the function returns last1. + */ + function find_first_of, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, last2: Iterator2): Iterator1; + /** + * Find element from set in range. + * + * Returns an iterator to the first element in the range [first1, last1) that matches any of the + * elements in [first2, last2). If no such element is found, the function returns last1. + * + * The elements in [first1, last1) are sequentially compared to each of the values in + * [first2, last2) using pred, until a pair matches. + * + * @param first1 An {@link Iterator} to the initial position of the first sequence. + * @param last1 An {@link Iterator} to the final position in a sequence. The range used is + * [first1, last1), including the element pointed by first1, but not the element + * pointed by last1. + * @param first2 An {@link Iterator} to the initial position of the element values to be searched for. + * @param last2 An {@link Iterator} to the final position of the element values to be searched for. The range used + * is [first2, last2). + * @param pred Binary function that accepts two elements as arguments (one of each of the two sequences, in the + * same order), and returns a value convertible to bool. The value returned indicates + * whether the elements are considered to match in the context of this function. + * + * @return An {@link Iterator} to the first element in [first1, last1) that is part of + * [first2, last2). If no matches are found, the function returns last1. + */ + function find_first_of, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, last2: Iterator2, pred: (x: T, y: T) => boolean): Iterator1; + /** + * Find equal adjacent elements in range. + * + * Searches the range [first, last) for the first occurrence of two consecutive elements that match, + * and returns an {@link Iterator} to the first of these two elements, or last if no such pair is found. + * + * Two elements match if they compare equal using {@link equal_to}. + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), + * which contains all the elements between first and last, including the element pointed by + * first but not the element pointed by last. + * + * @return An {@link Iterator} to the first element of the first pair of matching consecutive elements in the range + * [first, last). If no such pair is found, the function returns last. + */ + function adjacent_find>(first: InputIterator, last: InputIterator): InputIterator; + /** + * Find equal adjacent elements in range. + * + * Searches the range [first, last) for the first occurrence of two consecutive elements that match, + * and returns an {@link Iterator} to the first of these two elements, or last if no such pair is found. + * + * Two elements match if they compare equal using pred. + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), + * which contains all the elements between first and last, including the element pointed by + * first but not the element pointed by last. + * @param pred Unary function that accepts an element in the range as argument and returns a value convertible to + * bool. The value returned indicates whether the element is considered a match in the + * context of this function. The function shall not modify its argument. + * + * @return An {@link Iterator} to the first element of the first pair of matching consecutive elements in the range + * [first, last). If no such pair is found, the function returns last. + */ + function adjacent_find>(first: InputIterator, last: InputIterator, pred: (x: T, y: T) => boolean): InputIterator; + /** + * Search range for subsequence. + * + * Searches the range [first1, last1) for the first occurrence of the sequence defined by + * [first2, last2), and returns an iterator to its first element, or last1 if no occurrences are + * found. + * + * The elements in both ranges are compared sequentially using {@link equal_to}: A subsequence of + * [first1, last1) is considered a match only when this is true for all the elements of + * [first2, last2). + * + * This function returns the first of such occurrences. For an algorithm that returns the last instead, see + * {@link find_end}. + * + * @param first1 {@link Iterator Forward iterator} to the initial position of the searched sequence. + * @param last1 {@link Iterator Forward iterator} to the final position of the searched sequence. The range used is + * [first1, last1), which contains all the elements between first1 and last1, + * including the element pointed by first1 but not the element pointed by last1. + * @param first2 {@link Iterator Forward iterator} to the initial position of the sequence to be searched for. + * @param last2 {@link Iterator Forward iterator} to the final position of the sequence to be searched for. The range + * used is [first2, last2). + * + * @return An iterator to the first element of the first occurrence of [first2, last2) in first1 + * and last1. If the sequence is not found, the function returns last1. Otherwise + * [first2, last2) is an empty range, the function returns first1. + */ + function search, ForwardIterator2 extends Iterator>(first1: ForwardIterator1, last1: ForwardIterator1, first2: ForwardIterator2, last2: ForwardIterator2): ForwardIterator1; + /** + * Search range for subsequence. + * + * Searches the range [first1, last1) for the first occurrence of the sequence defined by + * [first2, last2), and returns an iterator to its first element, or last1 if no occurrences are + * found. + * + * The elements in both ranges are compared sequentially using pred: A subsequence of + * [first1, last1) is considered a match only when this is true for all the elements of + * [first2, last2). + * + * This function returns the first of such occurrences. For an algorithm that returns the last instead, see + * {@link find_end}. + * + * @param first1 {@link Iterator Forward iterator} to the initial position of the searched sequence. + * @param last1 {@link Iterator Forward iterator} to the final position of the searched sequence. The range used is + * [first1, last1), which contains all the elements between first1 and last1, + * including the element pointed by first1 but not the element pointed by last1. + * @param first2 {@link Iterator Forward iterator} to the initial position of the sequence to be searched for. + * @param last2 {@link Iterator Forward iterator} to the final position of the sequence to be searched for. The range + * used is [first2, last2). + * @param pred Binary function that accepts two elements as arguments (one of each of the two sequences, in the same + * order), and returns a value convertible to bool. The returned value indicates whether the elements are + * considered to match in the context of this function. The function shall not modify any of its + * arguments. + * + * @return An iterator to the first element of the first occurrence of [first2, last2) in + * [first1, last1). If the sequence is not found, the function returns last1. Otherwise + * [first2, last2) is an empty range, the function returns first1. + */ + function search, ForwardIterator2 extends Iterator>(first1: ForwardIterator1, last1: ForwardIterator1, first2: ForwardIterator2, last2: ForwardIterator2, pred: (x: T, y: T) => boolean): ForwardIterator1; + /** + * Search range for elements. + * + * Searches the range [first, last) for a sequence of count elements, each comparing equal to + * val. + * + * The function returns an iterator to the first of such elements, or last if no such sequence is found. + * + * @param first {@link Iterator Forward iterator} to the initial position of the searched sequence. + * @param last {@link Iterator Forward iterator} to the final position of the searched sequence. The range used is + * [first, last), which contains all the elements between first and last, + * including the element pointed by first but not the element pointed by last. + * @param count Minimum number of successive elements to match. + * @param val Individual value to be compared, or to be used as argument for {@link equal_to}. + * + * @return An iterator to the first element of the sequence. If no such sequence is found, the function returns + * last. + */ + function search_n>(first: ForwardIterator, last: ForwardIterator, count: number, val: T): ForwardIterator; + /** + * Search range for elements. + * + * Searches the range [first, last) for a sequence of count elements, each comparing equal to + * val. + * + * The function returns an iterator to the first of such elements, or last if no such sequence is found. + * + * + * @param first {@link Iterator Forward iterator} to the initial position of the searched sequence. + * @param last {@link Iterator Forward iterator} to the final position of the searched sequence. The range used is + * [first, last), which contains all the elements between first and last, + * including the element pointed by first but not the element pointed by last. + * @param count Minimum number of successive elements to match. + * @param val Individual value to be compared, or to be used as argument for pred. + * @param pred Binary function that accepts two arguments (one element from the sequence as first, and val as + * second), and returns a value convertible to bool. The value returned indicates whether the + * element is considered a match in the context of this function. The function shall not modify any of its + * arguments. + * + * @return An {@link Iterator} to the first element of the sequence. If no such sequence is found, the function + * returns last. + */ + function search_n>(first: ForwardIterator, last: ForwardIterator, count: number, val: T, pred: (x: T, y: T) => boolean): ForwardIterator; + /** + * Return first position where two ranges differ. + * + * Compares the elements in the range [first1, last1) with those in the range beginning at + * first2, and returns the first element of both sequences that does not match. + * + * The function returns a {@link Pair} of {@link iterators Iterator} to the first element in each range that + * does not match. + * + * @param first1 An {@link Iterator} to the initial position of the first sequence. + * @param last1 An {@link Iterator} to the final position in a sequence. The range used is + * [first1, last1), including the element pointed by first1, but not the element + * pointed by last1. + * @param first2 An {@link Iterator} to the initial position of the second sequence. The comparison includes up to + * as many elements of this sequence as those in the range [first1, last1). + * + * @return A {@link Pair}, where its members {@link Pair.first first} and {@link Pair.second second} point to the + * first element in both sequences that did not compare equal to each other. If the elements compared in + * both sequences have all matched, the function returns a {@link Pair} with {@link Pair.first first} set + * to last1 and {@link Pair.second second} set to the element in that same relative position in the + * second sequence. If none matched, it returns {@link make_pair}(first1, first2). + */ + function mismatch, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2): Pair; + /** + * Return first position where two ranges differ. + * + * Compares the elements in the range [first1, last1) with those in the range beginning at + * first2, and returns the first element of both sequences that does not match. + * + * The function returns a {@link Pair} of {@link iterators Iterator} to the first element in each range that + * does not match. + * + * @param first1 An {@link Iterator} to the initial position of the first sequence. + * @param last1 An {@link Iterator} to the final position in a sequence. The range used is + * [first1, last1), including the element pointed by first1, but not the element + * pointed by last1. + * @param first2 An {@link Iterator} to the initial position of the second sequence. The comparison includes up to + * as many elements of this sequence as those in the range [first1, last1). + * @param pred Binary function that accepts two elements as argument (one of each of the two sequences, in the same + * order), and returns a value convertible to bool. The value returned indicates whether + * the elements are considered to match in the context of this function. + * + * @return A {@link Pair}, where its members {@link Pair.first first} and {@link Pair.second second} point to the + * first element in both sequences that did not compare equal to each other. If the elements compared in + * both sequences have all matched, the function returns a {@link Pair} with {@link Pair.first first} set + * to last1 and {@link Pair.second second} set to the element in that same relative position in the + * second sequence. If none matched, it returns {@link make_pair}(first1, first2). + */ + function mismatch, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, compare: (x: T, y: T) => boolean): Pair; + /** + * Count appearances of value in range. + * + * Returns the number of elements in the range [first, last) that compare equal to val. + * + * The function uses {@link equal_to} to compare the individual elements to val. + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), + * which contains all the elements between first and last, including the element pointed by + * first but not the element pointed by last. + * @param val Value to match. + * + * @return The number of elements in the range [first, last) that compare equal to val. + */ + function count>(first: InputIterator, last: InputIterator, val: T): number; + /** + * Return number of elements in range satisfying condition. + * + * Returns the number of elements in the range [first, last) for which pred is true. + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), + * which contains all the elements between first and last, including the element pointed by + * first but not the element pointed by last. + * @param pred Unary function that accepts an element in the range as argument, and returns a value convertible + * to bool. The value returned indicates whether the element is counted by this function. + * The function shall not modify its argument. This can either be a function pointer or a function + * object. + */ + function count_if>(first: InputIterator, last: InputIterator, pred: (val: T) => boolean): number; +} +declare namespace std { + /** + * Copy range of elements. + * + * Copies the elements in the range [first, last) into the range beginning at result. + * + * The function returns an iterator to the end of the destination range (which points to the element following the + * last element copied). + * + * The ranges shall not overlap in such a way that result points to an element in the range + * [first, last). For such cases, see {@link copy_backward}. + * + * @param first {@link Iterator Input iterator} to the initial position in a sequence to be copied. + * @param last {@link Iterator Input iterator} to the initial position in a sequence to be copied. The range used is + * [first, last), which contains all the elements between first and last, + * including the element pointed by first but not the element pointed by last. + * @param result {@link Iterator Output iterator} to the initial position in the destination sequence. This shall not + * point to any element in the range [first, last). + * + * @return An iterator to the end of the destination range where elements have been copied. + */ + function copy, OutputIterator extends base.ILinearIterator>(first: InputIterator, last: InputIterator, result: OutputIterator): OutputIterator; + /** + * Copy elements. + * + * Copies the first n elements from the range beginning at first into the range beginning at + * result. + * + * The function returns an iterator to the end of the destination range (which points to one past the last element + * copied). + * + * If n is negative, the function does nothing. + * + * If the ranges overlap, some of the elements in the range pointed by result may have undefined but valid values. + * + * @param first {@link Iterator Input iterator} to the initial position in a sequence of at least n elements to + * be copied. InputIterator shall point to a type assignable to the elements pointed by + * OutputIterator. + * @param n Number of elements to copy. If this value is negative, the function does nothing. + * @param result {@link Iterator Output iterator} to the initial position in the destination sequence of at least + * n elements. This shall not point to any element in the range [first, last]. + * + * @return An iterator to the end of the destination range where elements have been copied. + */ + function copy_n, OutputIterator extends base.ILinearIterator>(first: InputIterator, n: number, result: OutputIterator): OutputIterator; + /** + * Copy certain elements of range. + * + * Copies the elements in the range [first, last) for which pred returns true to the + * range beginning at result. + * + * @param first {@link Iterator Input iterator} to the initial position in a sequence to be copied. + * @param last {@link Iterator Input iterator} to the initial position in a sequence to be copied. The range used is + * [first, last), which contains all the elements between first and last, + * including the element pointed by first but not the element pointed by last. + * @param result {@link Iterator Output iterator} to the initial position in the destination sequence. This shall not + * point to any element in the range [first, last). + * @param pred Unary function that accepts an element in the range as argument, and returns a value convertible to + * bool. The value returned indicates whether the element is to be copied (if + * true, it is copied). The function shall not modify any of its arguments. + * + * @return An iterator to the end of the destination range where elements have been copied. + */ + function copy_if, OutputIterator extends base.ILinearIterator>(first: InputIterator, last: InputIterator, result: OutputIterator, pred: (x: T) => boolean): OutputIterator; + /** + * Copy range of elements backward. + * + * Copies the elements in the range [first, last) starting from the end into the range terminating + * at result. + * + * The function returns an iterator to the first element in the destination range. + * + * The resulting range has the elements in the exact same order as [first, last). To reverse their + * order, see {@link reverse_copy}. + * + * The function begins by copying *(last-1) into *(result-1), and then follows backward + * by the elements preceding these, until first is reached (and including it). + * + * The ranges shall not overlap in such a way that result (which is the past-the-end element in the + * destination range) points to an element in the range (first,last]. For such cases, see {@link copy}. + * + * @param first {@link Iterator Bidirectional iterator} to the initial position in a sequence to be copied. + * @param last {@link Iterator Bidirectional iterator} to the initial position in a sequence to be copied. The range + * used is [first, last), which contains all the elements between first and + * last, including the element pointed by first but not the element pointed by last. + * @param result {@link Iterator Bidirectional iterator} to the initial position in the destination sequence. This + * shall not point to any element in the range [first, last). + * + * @return An iterator to the first element of the destination sequence where elements have been copied. + */ + function copy_backward, BidirectionalIterator2 extends base.ILinearIterator>(first: BidirectionalIterator1, last: BidirectionalIterator1, result: BidirectionalIterator2): BidirectionalIterator2; + /** + * Fill range with value. + * + * Assigns val to all the elements in the range [first, last). + * + * @param first {@link Iterator Forward iterator} to the initial position in a sequence of elements that support being + * assigned a value of type T. + * @param last {@link Iterator Forward iterator} to the final position in a sequence of elements that support being + * assigned a value of type T.. The range filled is [first, last), which contains + * all the elements between first and last, including the element pointed by first + * but not the element pointed by last. + * @param val Value to assign to the elements in the filled range. + */ + function fill>(first: ForwardIterator, last: ForwardIterator, val: T): void; + /** + * Fill sequence with value. + * + * Assigns val to the first n elements of the sequence pointed by first. + * + * @param first {@link Iterator Output iterator} to the initial position in a sequence of elements that support being + * assigned a value of type T. + * @param n Number of elements to fill. If negative, the function does nothing. + * @param val Value to be used to fill the range. + * + * @return An iterator pointing to the element that follows the last element filled. + */ + function fill_n>(first: OutputIterator, n: number, val: T): OutputIterator; + /** + * Transform range. + * + * Applies op to each of the elements in the range [first, last) and stores the value returned + * by each operation in the range that begins at result. + * + * @param first {@link Iterator Input iterator} to the initial position in a sequence to be transformed. + * @param last {@link Iterator Input iterator} to the initial position in a sequence to be transformed. The range + * used is [first, last), which contains all the elements between first and + * last, including the element pointed by first but not the element pointed by last. + * @param result {@link Iterator Output} iterator to the initial position of the range where the operation results are + * stored. The range includes as many elements as [first, last). + * @param op Unary function that accepts one element of the type pointed to by InputIterator as argument, and + * returns some result value convertible to the type pointed to by OutputIterator. + * + * @return An iterator pointing to the element that follows the last element written in the result sequence. + */ + function transform, OutputIterator extends base.ILinearIterator>(first: InputIterator, last: InputIterator, result: OutputIterator, op: (val: T) => T): OutputIterator; + /** + * Transform range. + * + * Calls binary_op using each of the elements in the range [first1, last1) as first argument, + * and the respective argument in the range that begins at first2 as second argument. The value returned by + * each call is stored in the range that begins at result. + * + * @param first1 {@link Iterator Input iterator} to the initial position of the first sequence. + * @param last1 {@link Iterator Input iterator} to the final position of the first sequence. The range used is + * [first1, last1), including the element pointed by first1, but not the element + * pointed by last1. + * @param first2 {@link Iterator Input iterator} to the initial position of the second range. The range includes as + * many elements as [first1, last1). + * @param result {@link Iterator Output} iterator to the initial position of the range where the operation results are + * stored. The range includes as many elements as [first1, last1). + * @param binary_op Binary function that accepts two elements as argument (one of each of the two sequences), and + * returns some result value convertible to the type pointed to by OutputIterator. + * + * @return An iterator pointing to the element that follows the last element written in the result sequence. + */ + function transform, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, result: OutputIterator, binary_op: (x: T, y: T) => T): OutputIterator; + /** + * Generate values for range with function. + * + * Assigns the value returned by successive calls to gen to the elements in the range [first, last). + * + * @param first {@link Iterator Forward iterator} to the initial position in a sequence. + * @param last {@link Iterator Forward iterator} to the final position in a sequence. The range affected is + * [first, last), which contains all the elements between first and last, + * including the element pointed by first but not the element pointed by last. + * @param gen Generator function that is called with no arguments and returns some value of a type convertible to + * those pointed by the iterators. + */ + function generate>(first: ForwardIterator, last: ForwardIterator, gen: () => T): void; + /** + * Generate values for sequence with function. + * + * Assigns the value returned by successive calls to gen to the first n elements of the sequence + * pointed by first. + * + * @param first {@link Iterator Output iterator} to the initial position in a sequence of at least n elements + * that support being assigned a value of the type returned by gen. + * @param n Number of values to generate. If negative, the function does nothing. + * @param gen Generator function that is called with no arguments and returns some value of a type convertible to + * those pointed by the iterators. + * + * @return An iterator pointing to the element that follows the last element whose value has been generated. + */ + function generate_n>(first: ForwardIterator, n: number, gen: () => T): ForwardIterator; + /** + * Remove consecutive duplicates in range. + * + * Removes all but the first element from every consecutive group of equivalent elements in the range + * [first, last). + * + * The function cannot alter the properties of the object containing the range of elements (i.e., it cannot + * alter the size of an array or a container): The removal is done by replacing the duplicate elements by the next + * element that is not a duplicate, and signaling the new size of the shortened range by returning an iterator to + * the element that should be considered its new past-the-last element. + * + * The relative order of the elements not removed is preserved, while the elements between the returned + * iterator and last are left in a valid but unspecified state. + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), + * which contains all the elements between first and last, including the element pointed by + * first but not the element pointed by last. + * + * @return An iterator to the element that follows the last element not removed. The range between first and + * this iterator includes all the elements in the sequence that were not considered duplicates. + */ + function unique>(first: InputIterator, last: InputIterator): InputIterator; + /** + * Remove consecutive duplicates in range. + * + * Removes all but the first element from every consecutive group of equivalent elements in the range + * [first, last). + * + * The function cannot alter the properties of the object containing the range of elements (i.e., it cannot + * alter the size of an array or a container): The removal is done by replacing the duplicate elements by the next + * element that is not a duplicate, and signaling the new size of the shortened range by returning an iterator to + * the element that should be considered its new past-the-last element. + * + * The relative order of the elements not removed is preserved, while the elements between the returned + * iterator and last are left in a valid but unspecified state. + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), + * which contains all the elements between first and last, including the element pointed by + * first but not the element pointed by last. + * @param pred Binary function that accepts two elements in the range as argument, and returns a value convertible + * to bool. The value returned indicates whether both arguments are considered equivalent + * (if true, they are equivalent and one of them is removed). The function shall not modify + * any of its arguments. + * + * @return An iterator to the element that follows the last element not removed. The range between first and + * this iterator includes all the elements in the sequence that were not considered duplicates. + */ + function unique>(first: InputIterator, last: InputIterator, pred: (left: t, right: t) => boolean): InputIterator; + /** + * Copy range removing duplicates. + * + * Copies the elements in the range [first, last) to the range beginning at result, except + * consecutive duplicates (elements that compare equal to the element preceding). + * + * Only the first element from every consecutive group of equivalent elements in the range + * [first, last) is copied. + * + * The comparison between elements is performed by applying {@lnk equal_to}. + * + * @param first {@link Iterator Forward iterator} to the initial position in a sequence. + * @param last {@link Iterator Forward iterator} to the final position in a sequence. The range used is + * [first, last), which contains all the elements between first and last, + * including the element pointed by first but not the element pointed by last. + * @param result Output iterator to the initial position of the range where the resulting range of values is stored. + * The pointed type shall support being assigned the value of an element in the range + * [first, last). + * + * @return An iterator pointing to the end of the copied range, which contains no consecutive duplicates. + */ + function unique_copy, OutputIterator extends base.ILinearIterator>(first: InputIterator, last: InputIterator, result: OutputIterator): OutputIterator; + /** + * Copy range removing duplicates. + * + * Copies the elements in the range [first, last) to the range beginning at result, except + * consecutive duplicates (elements that compare equal to the element preceding). + * + * Only the first element from every consecutive group of equivalent elements in the range + * [first, last) is copied. + * + * The comparison between elements is performed by applying pred. + * + * @param first {@link Iterator Forward iterator} to the initial position in a sequence. + * @param last {@link Iterator Forward iterator} to the final position in a sequence. The range used is + * [first, last), which contains all the elements between first and last, + * including the element pointed by first but not the element pointed by last. + * @param result Output iterator to the initial position of the range where the resulting range of values is stored. + * The pointed type shall support being assigned the value of an element in the range + * [first, last). + * @param pred Binary function that accepts two elements in the range as argument, and returns a value convertible to + * bool. The value returned indicates whether both arguments are considered equivalent (if + * true, they are equivalent and one of them is removed). The function shall not modify any + * of its arguments. + * + * @return An iterator pointing to the end of the copied range, which contains no consecutive duplicates. + */ + function unique_copy, OutputIterator extends base.ILinearIterator>(first: InputIterator, last: InputIterator, result: OutputIterator, pred: (x: T, y: T) => boolean): OutputIterator; + /** + * Remove value from range. + * + * Transforms the range [first, last) into a range with all the elements that compare equal to + * val removed, and returns an iterator to the new last of that range. + * + * The function cannot alter the properties of the object containing the range of elements (i.e., it cannot alter + * the size of an array or a container): The removal is done by replacing the elements that compare equal to + * val by the next element that does not, and signaling the new size of the shortened range by returning an + * iterator to the element that should be considered its new past-the-last element. + * + * The relative order of the elements not removed is preserved, while the elements between the returned iterator + * and last are left in a valid but unspecified state. + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), + * which contains all the elements between first and last, including the element pointed by + * first but not the element pointed by last. + * @param val Value to be removed. + */ + function remove>(first: InputIterator, last: InputIterator, val: T): InputIterator; + /** + * Remove elements from range. + * + * Transforms the range [first, last) into a range with all the elements for which pred returns + * true removed, and returns an iterator to the new last of that range. + * + * The function cannot alter the properties of the object containing the range of elements (i.e., it cannot + * alter the size of an array or a container): The removal is done by replacing the elements for which pred returns + * true by the next element for which it does not, and signaling the new size of the shortened range + * by returning an iterator to the element that should be considered its new past-the-last element. + * + * The relative order of the elements not removed is preserved, while the elements between the returned + * iterator and last are left in a valid but unspecified state. + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), + * which contains all the elements between first and last, including the element pointed by + * first but not the element pointed by last. + * @param pred Unary function that accepts an element in the range as argument, and returns a value convertible to + * bool. The value returned indicates whether the element is to be removed (if + * true, it is removed). The function shall not modify its argument. + */ + function remove_if>(first: InputIterator, last: InputIterator, pred: (left: T) => boolean): InputIterator; + /** + * Copy range removing value. + * + * Copies the elements in the range [first, last) to the range beginning at result, except + * those elements that compare equal to val. + * + * The resulting range is shorter than [first, last) by as many elements as matches in the sequence, + * which are "removed". + * + * The function uses {@link equal_to} to compare the individual elements to val. + * + * @param first {@link Iterator InputIterator} to the initial position in a sequence. + * @param last {@link Iterator InputIterator} to the final position in a sequence. The range used is + * [first, last), which contains all the elements between first and last, + * including the element pointed by first but not the element pointed by last. + * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is + * stored. The pointed type shall support being assigned the value of an element in the range + * [first, last). + * @param val Value to be removed. + * + * @return An iterator pointing to the end of the copied range, which includes all the elements in + * [first, last) except those that compare equal to val. + */ + function remove_copy, OutputIterator extends base.ILinearIterator>(first: InputIterator, last: InputIterator, result: OutputIterator, val: T): OutputIterator; + /** + * Copy range removing values. + * + * Copies the elements in the range [first, last) to the range beginning at result, except + * those elements for which pred returns true. + * + * The resulting range is shorter than [first, last) by as many elements as matches, which are + * "removed". + * + * @param first {@link Iterator InputIterator} to the initial position in a sequence. + * @param last {@link Iterator InputIterator} to the final position in a sequence. The range used is + * [first, last), which contains all the elements between first and last, + * including the element pointed by first but not the element pointed by last. + * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is + * stored. The pointed type shall support being assigned the value of an element in the range + * [first, last). + * @param pred Unary function that accepts an element in the range as argument, and returns a value convertible to + * bool. The value returned indicates whether the element is to be removed from the copy (if + * true, it is not copied). The function shall not modify its argument. + * + * @return An iterator pointing to the end of the copied range, which includes all the elements in + * [first, last) except those for which pred returns true. + */ + function remove_copy_if, OutputIterator extends base.ILinearIterator>(first: InputIterator, last: InputIterator, result: OutputIterator, pred: (val: T) => boolean): OutputIterator; + /** + * Replace value in range. + * + * Assigns new_val to all the elements in the range [first, last) that compare equal to + * old_val. + * + * The function uses {@link equal_to} to compare the individual elements to old_val. + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), + * which contains all the elements between first and last, including the element pointed by + * first but not the element pointed by last. + * @param old_val Value to be replaced. + * @param new_val Replacement value. + */ + function replace>(first: InputIterator, last: InputIterator, old_val: T, new_val: T): void; + /** + * Replace value in range. + * + * Assigns new_val to all the elements in the range [first, last) for which pred returns + * true. + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), + * which contains all the elements between first and last, including the element pointed by + * first but not the element pointed by last. + * @param pred Unary function that accepts an element in the range as argument, and returns a value convertible to + * bool. The value returned indicates whether the element is to be replaced (if + * true, it is replaced). The function shall not modify its argument. + * @param new_val Value to assign to replaced elements. + */ + function replace_if>(first: InputIterator, last: InputIterator, pred: (val: T) => boolean, new_val: T): void; + /** + * Copy range replacing value. + * + * Copies the elements in the range [first, last) to the range beginning at result, replacing + * the appearances of old_value by new_value. + * + * The function uses {@link equal_to} to compare the individual elements to old_value. + * + * The ranges shall not overlap in such a way that result points to an element in the range + * [first, last). + * + * @param first {@link Iterator InputIterator} to the initial position in a sequence. + * @param last {@link Iterator InputIterator} to the final position in a sequence. The range used is + * [first, last), which contains all the elements between first and last, + * including the element pointed by first but not the element pointed by last. + * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is + * stored. The pointed type shall support being assigned the value of an element in the range + * [first, last). + * @param old_val Value to be replaced. + * @param new_val Replacement value. + * + * @return An iterator pointing to the element that follows the last element written in the result sequence. + */ + function replace_copy, OutputIterator extends base.ILinearIterator>(first: InputIterator, last: InputIterator, result: OutputIterator, old_val: T, new_val: T): OutputIterator; + /** + * Copy range replacing value. + * + * Copies the elements in the range [first, last) to the range beginning at result, replacing + * those for which pred returns true by new_value. + * + * @param first {@link Iterator InputIterator} to the initial position in a sequence. + * @param last {@link Iterator InputIterator} to the final position in a sequence. The range used is + * [first, last), which contains all the elements between first and last, + * including the element pointed by first but not the element pointed by last. + * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is + * stored. The pointed type shall support being assigned the value of an element in the range + * [first, last). + * @param pred Unary function that accepts an element in the range as argument, and returns a value convertible to + * bool. The value returned indicates whether the element is to be removed from the copy (if + * true, it is not copied). The function shall not modify its argument. + * @param new_val Value to assign to replaced values. + * + * @return An iterator pointing to the element that follows the last element written in the result sequence. + */ + function replace_copy_if, OutputIterator extends base.ILinearIterator>(first: InputIterator, last: InputIterator, result: OutputIterator, pred: (val: T) => boolean, new_val: T): OutputIterator; + /** + * Exchange values of objects pointed to by two iterators. + * + * Swaps the elements pointed to by x and y. + * + * The function calls {@link Iterator.swap} to exchange the elements. + * + * @param x {@link Iterator Forward iterator} to the objects to swap. + * @param y {@link Iterator Forward iterator} to the objects to swap. + */ + function iter_swap(x: Iterator, y: Iterator): void; + /** + * Exchange values of two ranges. + * + * Exchanges the values of each of the elements in the range [first1, last1) with those of their + * respective elements in the range beginning at first2. + * + * The function calls {@link Iterator.swap} to exchange the elements. + * + * @param first1 {@link Iterator Forward iterator} to the initial position of the first sequence. + * @param last1 {@link Iterator Forward iterator} to the final position of the first sequence. The range used is + * [first1, last1), including the element pointed by first1, but not the element + * pointed by last1. + * @param first2 {@link Iterator Forward iterator} to the initial position of the second range. The range includes as + * many elements as [first1, last1). The two ranges shall not overlap. + * + * @return An iterator to the last element swapped in the second sequence. + */ + function swap_ranges, ForwardIterator2 extends Iterator>(first1: ForwardIterator1, last1: ForwardIterator1, first2: ForwardIterator2): ForwardIterator2; + /** + * Reverse range. + * + * Reverses the order of the elements in the range [first, last). + * + * The function calls {@link iter_swap} to swap the elements to their new locations. + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), + * which contains all the elements between first and last, including the element pointed by + * first but not the element pointed by last. + */ + function reverse>(first: InputIterator, last: InputIterator): void; + /** + * Copy range reversed. + * + * Copies the elements in the range [first, last) to the range beginning at result, but in + * reverse order. + * + * @param first {@link Iterator Bidirectional iterator} to the initial position in a sequence to be copied. + * @param last {@link Iterator Bidirectional iterator} to the initial position in a sequence to be copied. The range + * used is [first, last), which contains all the elements between first and + * last, including the element pointed by first but not the element pointed by last. + * @param result {@link Iterator Output iterator} to the initial position of the range where the reserved range is + * stored. The pointed type shall support being assigned the value of an element in the range + * [first, last). + * + * @return An output iterator pointing to the end of the copied range, which contains the same elements in reverse + * order. + */ + function reverse_copy, OutputIterator extends base.ILinearIterator>(first: BidirectionalIterator, last: BidirectionalIterator, result: OutputIterator): OutputIterator; + /** + * Rotate left the elements in range. + * + * Rotates the order of the elements in the range [first, last), in such a way that the element + * pointed by middle becomes the new first element. + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param middle An {@link Iterator} pointing to the element within the range [first, last) that is + * moved to the first position in the range. + * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), + * which contains all the elements between first and last, including the element pointed by + * first but not the element pointed by last. + * + * @return An iterator pointing to the element that now contains the value previously pointed by first. + */ + function rotate>(first: InputIterator, middle: InputIterator, last: InputIterator): InputIterator; + /** + * Copy range rotated left. + * + * Copies the elements in the range [first, last) to the range beginning at result, but + * rotating the order of the elements in such a way that the element pointed by middle becomes the first + * element in the resulting range. + * + * @param first {@link Iterator Forward iterator} to the initial position of the range to be copy-rotated. + * @param middle Forward iterator pointing to the element within the range [first, last) that is copied as the first element in the resulting range. + * @param last {@link Iterator Forward iterator} to the final positions of the range to be copy-rotated. The range + * used is [first, last), which contains all the elements between first and + * last, including the element pointed by first but not the element pointed by last. + * Notice that in this function, these are not consecutive parameters, but the first and third ones. + * @param result {@link Iterator Output iterator} to the initial position of the range where the reserved range is + * stored. The pointed type shall support being assigned the value of an element in the range + * [first, last). + * + * @return An output iterator pointing to the end of the copied range. + */ + function rotate_copy, OutputIterator extends base.ILinearIterator>(first: ForwardIterator, middle: ForwardIterator, last: ForwardIterator, result: OutputIterator): OutputIterator; + /** + * Randomly rearrange elements in range. + * + * Rearranges the elements in the range [first, last) randomly. + * + * The function swaps the value of each element with that of some other randomly picked element. When provided, + * the function gen determines which element is picked in every case. Otherwise, the function uses some unspecified + * source of randomness. + * + * To specify a uniform random generator, see {@link shuffle}. + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), + * which contains all the elements between first and last, including the element pointed by + * first but not the element pointed by last. + */ + function random_shuffle>(first: RandomAccessIterator, last: RandomAccessIterator): void; + /** + * Randomly rearrange elements in range using generator. + * + * Rearranges the elements in the range [first, last) randomly, using g as uniform random + * number generator. + * + * The function swaps the value of each element with that of some other randomly picked element. The function + * determines the element picked by calling g(). + * + * To shuffle the elements of the range without such a generator, see {@link random_shuffle} instead. + * + *
Note
+ * Using random generator engine is not implemented yet. + * + * @param first An {@link Iterator} to the initial position in a sequence. + * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), + * which contains all the elements between first and last, including the element pointed by + * first but not the element pointed by last. + */ + function shuffle>(first: RandomAccessIterator, last: RandomAccessIterator): void; +} +declare namespace std { + /** + * Sort elements in range. + * + * Sorts the elements in the range [first, last) into ascending order. The elements are compared + * using {@link less}. + * + * @param first {@link IArrayIterator Random-access iterator} to the initial position of the sequence to be sorted. + * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence to be sorted. + * The range used is [first, last), which contains all the elements between first + * and last, including the element pointed by first but not the element pointed by + * last. {@link IArrayIterator RandomAccessIterator} shall point to a type for which + * {@link Iterator.swap swap} is properly defined. + */ + function sort>(first: RandomAccessIterator, last: RandomAccessIterator): void; + /** + * Sort elements in range. + * + * Sorts the elements in the range [first, last) into specific order. The elements are compared + * using compare. + * + * @param first {@link IArrayIterator Random-access iterator} to the initial position of the sequence to be sorted. + * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence to be sorted. + * The range used is [first, last), which contains all the elements between first + * and last, including the element pointed by first but not the element pointed by + * last. {@link IArrayIterator RandomAccessIterator} shall point to a type for which + * {@link Iterator.swap swap} is properly defined. + * @param compare Binary function that accepts two elements in the range as arguments, and returns a value + * convertible to boolean. The value returned indicates whether the element passed as first + * argument is considered to go before the second in the specific strict weak ordering it defines. The + * function shall not modify any of its arguments. This can either be a function pointer or a function + * object. + */ + function sort>(first: RandomAccessIterator, last: RandomAccessIterator, compare: (left: T, right: T) => boolean): void; + /** + * Partially sort elements in range. + * + * Rearranges the elements in the range [first, last), in such a way that the elements before + * middle are the smallest elements in the entire range and are sorted in ascending order, while the remaining + * elements are left without any specific order. + * + * The elements are compared using {@link less}. + * + * @param last {@link IArrayIterator Random-access iterator} to the first position of the sequence to be sorted. + * @param middle {@link IArrayIterator Random-access iterator} pointing to the element within the range [first, last) that is used as the upper boundary of the elements that are fully sorted. + * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence to be sorted. + * The range used is [first, last), which contains all the elements between first + * and last, including the element pointed by first but not the element pointed by + * last. + */ + function partial_sort>(first: RandomAccessIterator, middle: RandomAccessIterator, last: RandomAccessIterator): void; + /** + * Partially sort elements in range. + * + * Rearranges the elements in the range [first, last), in such a way that the elements before + * middle are the smallest elements in the entire range and are sorted in ascending order, while the remaining + * elements are left without any specific order. + * + * The elements are compared using comp. + * + * @param last {@link IArrayIterator Random-access iterator} to the first position of the sequence to be sorted. + * @param middle {@link IArrayIterator Random-access iterator} pointing to the element within the range [first, last) that is used as the upper boundary of the elements that are fully sorted. + * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence to be sorted. + * The range used is [first, last), which contains all the elements between first + * and last, including the element pointed by first but not the element pointed by + * last. + * @param compare Binary function that accepts two elements in the range as arguments, and returns a value + * convertible to boolean. The value returned indicates whether the element passed as + * first argument is considered to go before the second in the specific strict weak ordering it + * defines. The function shall not modify any of its arguments. + */ + function partial_sort>(first: RandomAccessIterator, middle: RandomAccessIterator, last: RandomAccessIterator, compare: (x: T, y: T) => boolean): void; + /** + * Copy and partially sort range. + * + * Copies the smallest elements in the range [first, last) to + * [result_first, result_last), sorting the elements copied. The number of elements copied is the same + * as the {@link distance} between result_first and result_last (unless this is more than the amount of + * elements in [first, last)). + * + * The range [first, last) is not modified. + * + * The elements are compared using {@link less}. + * + * @param first {@link Iterator Input iterator} to the initial position of the sequence to copy from. + * @param last {@link Iterator Input iterator} to the final position of the sequence to copy from. The range used is + * [first, last), which contains all the elements between first and last, + * including the element pointed by first but not the element pointed by last. + * InputIterator shall point to a type assignable to the elements pointed by + * RandomAccessIterator. + * @param result_first {@link Iterator Random-access iterator} to the initial position of the destination sequence. + * @param result_last {@link Iterator Random-access iterator} to the final position of the destination sequence. + * The range used is [result_first, result_last). + * @param compare Binary function that accepts two elements in the result range as arguments, and returns a value + * convertible to bool. The value returned indicates whether the element passed as first + * argument is considered to go before the second in the specific strict weak ordering it + * defines. The function shall not modify any of its arguments. + * + * @return An iterator pointing to the element that follows the last element written in the result sequence. + */ + function partial_sort_copy, RandomAccessIterator extends Iterator>(first: InputIterator, last: InputIterator, result_first: RandomAccessIterator, result_last: RandomAccessIterator): RandomAccessIterator; + /** + * Copy and partially sort range. + * + * Copies the smallest (or largest) elements in the range [first, last) to + * [result_first, result_last), sorting the elements copied. The number of elements copied is the same + * as the {@link distance} between result_first and result_last (unless this is more than the amount of + * elements in [first, last)). + * + * The range [first, last) is not modified. + * + * The elements are compared using compare. + * + * @param first {@link Iterator Input iterator} to the initial position of the sequence to copy from. + * @param last {@link Iterator Input iterator} to the final position of the sequence to copy from. The range used is + * [first, last), which contains all the elements between first and last, + * including the element pointed by first but not the element pointed by last. + * InputIterator shall point to a type assignable to the elements pointed by + * RandomAccessIterator. + * @param result_first {@link Iterator Random-access iterator} to the initial position of the destination sequence. + * @param result_last {@link Iterator Random-access iterator} to the final position of the destination sequence. + * The range used is [result_first, result_last). + * @param compare Binary function that accepts two elements in the result range as arguments, and returns a value + * convertible to bool. The value returned indicates whether the element passed as first + * argument is considered to go before the second in the specific strict weak ordering it + * defines. The function shall not modify any of its arguments. + * + * @return An iterator pointing to the element that follows the last element written in the result sequence. + */ + function partial_sort_copy, RandomAccessIterator extends Iterator>(first: InputIterator, last: InputIterator, result_first: RandomAccessIterator, result_last: RandomAccessIterator, compare: (x: T, y: T) => boolean): RandomAccessIterator; + /** + * Check whether range is sorted. + * + * Returns true if the range [first, last) is sorted into ascending order. + * + * The elements are compared using {@link less}. + * + * @param first {@link Iterator Forward iterator} to the initial position of the sequence. + * @param last {@link Iterator Forward iterator} to the final position of the sequence. The range checked is + * [first, last), which contains all the elements between first and last, + * including the element pointed by first but not the element pointed by last. + * + * @return true if the range [first, last) is sorted into ascending order, + * false otherwise. If the range [first, last) contains less than two elements, + * the function always returns true. + */ + function is_sorted>(first: ForwardIterator, last: ForwardIterator): boolean; + /** + * Check whether range is sorted. + * + * Returns true if the range [first, last) is sorted into ascending order. + * + * The elements are compared using compare. + * + * @param first {@link Iterator Forward iterator} to the initial position of the sequence. + * @param last {@link Iterator Forward iterator} to the final position of the sequence. The range checked is + * [first, last), which contains all the elements between first and last, + * including the element pointed by first but not the element pointed by last. + * @param compare Binary function that accepts two elements in the range as arguments, and returns a value convertible + * to bool. The value returned indicates whether the element passed as first argument is + * considered to go before the second in the specific strict weak ordering it defines. The function + * shall not modify any of its arguments. + * + * @return true if the range [first, last) is sorted into ascending order, + * false otherwise. If the range [first, last) contains less than two elements, + * the function always returns true. + */ + function is_sorted>(first: ForwardIterator, last: ForwardIterator, compare: (x: T, y: T) => boolean): boolean; + /** + * Find first unsorted element in range. + * + * Returns an iterator to the first element in the range [first, last) which does not follow an + * ascending order. + * + * The range between first and the iterator returned {@link is_sorted is sorted}. + * + * If the entire range is sorted, the function returns last. + * + * The elements are compared using {@link equal_to}. + * + * @param first {@link Iterator Forward iterator} to the initial position of the sequence. + * @param last {@link Iterator Forward iterator} to the final position of the sequence. The range checked is + * [first, last), which contains all the elements between first and last, + * including the element pointed by first but not the element pointed by last. + * @param compare Binary function that accepts two elements in the range as arguments, and returns a value convertible + * to bool. The value returned indicates whether the element passed as first argument is + * considered to go before the second in the specific strict weak ordering it defines. The function + * shall not modify any of its arguments. + * + * @return An iterator to the first element in the range which does not follow an ascending order, or last if + * all elements are sorted or if the range contains less than two elements. + */ + function is_sorted_until>(first: ForwardIterator, last: ForwardIterator): ForwardIterator; + /** + * Find first unsorted element in range. + * + * Returns an iterator to the first element in the range [first, last) which does not follow an + * ascending order. + * + * The range between first and the iterator returned {@link is_sorted is sorted}. + * + * If the entire range is sorted, the function returns last. + * + * The elements are compared using compare. + * + * @param first {@link Iterator Forward iterator} to the initial position of the sequence. + * @param last {@link Iterator Forward iterator} to the final position of the sequence. The range checked is + * [first, last), which contains all the elements between first and last, + * including the element pointed by first but not the element pointed by last. + * @param compare Binary function that accepts two elements in the range as arguments, and returns a value convertible + * to bool. The value returned indicates whether the element passed as first argument is + * considered to go before the second in the specific strict weak ordering it defines. The function + * shall not modify any of its arguments. + * + * @return An iterator to the first element in the range which does not follow an ascending order, or last if + * all elements are sorted or if the range contains less than two elements. + */ + function is_sorted_until>(first: ForwardIterator, last: ForwardIterator, compare: (x: T, y: T) => boolean): ForwardIterator; +} +declare namespace std { + /** + * Make heap from range. + * + * Rearranges the elements in the range [first, last) in such a way that they form a heap. + * + * A heap is a way to organize the elements of a range that allows for fast retrieval of the element with the + * highest value at any moment (with {@link pop_heap}), even repeatedly, while allowing for fast insertion of new + * elements (with {@link push_heap}). + * + * The element with the highest value is always pointed by first. The order of the other elements depends on the + * particular implementation, but it is consistent throughout all heap-related functions of this header. + * + * The elements are compared using {@link less}: The element with the highest value is an element for which this + * would return false when compared to every other element in the range. + * + * The standard container adaptor {@link PriorityQueue} calls {@link make_heap}, {@link push_heap} and + * {@link pop_heap} automatically to maintain heap properties for a container. + * + * @param first {@link IArrayIterator Random-access iterator} to the initial position of the sequence to be + * transformed into a heap. + * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence to be transformed + * into a heap. The range used is [first, last), which contains all the elements between + * first and last, including the element pointed by first but not the element pointed + * by last. {@link IArrayIterator RandomAccessIterator} shall point to a type for which + * {@link Iterator.swap swap} is properly defined. + */ + function make_heap>(first: RandomAccessIterator, last: RandomAccessIterator): void; + /** + * Make heap from range. + * + * Rearranges the elements in the range [first, last) in such a way that they form a heap. + * + * A heap is a way to organize the elements of a range that allows for fast retrieval of the element with the + * highest value at any moment (with {@link pop_heap}), even repeatedly, while allowing for fast insertion of new + * elements (with {@link push_heap}). + * + * The element with the highest value is always pointed by first. The order of the other elements depends on the + * particular implementation, but it is consistent throughout all heap-related functions of this header. + * + * The elements are compared using compare: The element with the highest value is an element for which this + * would return false when compared to every other element in the range. + * + * The standard container adaptor {@link PriorityQueue} calls {@link make_heap}, {@link push_heap} and + * {@link pop_heap} automatically to maintain heap properties for a container. + * + * @param first {@link IArrayIterator Random-access iterator} to the initial position of the sequence to be + * transformed into a heap. + * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence to be transformed + * into a heap. The range used is [first, last), which contains all the elements between + * first and last, including the element pointed by first but not the element pointed + * by last. {@link IArrayIterator RandomAccessIterator} shall point to a type for which + * {@link Iterator.swap swap} is properly defined. + * @param compare Binary function that accepts two elements in the range as arguments, and returns a value + * convertible to boolean. The value returned indicates whether the element passed as + * first argument is considered to go before the second in the specific strict weak ordering it defines. + * The function shall not modify any of its arguments. This can either be a function pointer or a + * function object. + */ + function make_heap>(first: RandomAccessIterator, last: RandomAccessIterator, compare: (x: T, y: T) => boolean): void; + /** + * Push element into heap range. + * + * Given a heap in the range [first, last - 1), this function extends the range considered a heap to + * [first, last) by placing the value in (last - 1) into its corresponding location within it. + * + * + * A range can be organized into a heap by calling {@link make_heap}. After that, its heap properties are + * preserved if elements are added and removed from it using {@link push_heap} and {@link pop_heap}, respectively. + * + * + * @param first {@link IArrayIterator Random-access iterator} to the initial position of the new heap range, including + * the pushed element. + * @param last {@link IArrayIterator Random-access iterator} to the final position of the new heap range, including + * the pushed element. The range used is [first, last), which contains all the elements + * between first and last, including the element pointed by first but not the element + * pointed by last. {@link IArrayIterator RandomAccessIterator} shall point to a type for which + * {@link Iterator.swap swap} is properly defined. + */ + function push_heap>(first: RandomAccessIterator, last: RandomAccessIterator): void; + /** + * Push element into heap range. + * + * Given a heap in the range [first, last - 1), this function extends the range considered a heap to + * [first, last) by placing the value in (last - 1) into its corresponding location within it. + * + * A range can be organized into a heap by calling {@link make_heap}. After that, its heap properties are + * preserved if elements are added and removed from it using {@link push_heap} and {@link pop_heap}, respectively. + * + * + * @param first {@link IArrayIterator Random-access iterator} to the initial position of the new heap range, including + * the pushed element. + * @param last {@link IArrayIterator Random-access iterator} to the final position of the new heap range, including + * the pushed element. The range used is [first, last), which contains all the elements + * between first and last, including the element pointed by first but not the element + * pointed by last. {@link IArrayIterator RandomAccessIterator} shall point to a type for which + * {@link Iterator.swap swap} is properly defined. + * @param compare Binary function that accepts two elements in the range as arguments, and returns a value + * convertible to boolean. The value returned indicates whether the element passed as + * first argument is considered to go before the second in the specific strict weak ordering it defines. + * The function shall not modify any of its arguments. This can either be a function pointer or a + * function object. + */ + function push_heap>(first: RandomAccessIterator, last: RandomAccessIterator, compare: (x: T, y: T) => boolean): void; + /** + * Pop element from heap range. + * + * Rearranges the elements in the heap range [first, last) in such a way that the part considered a + * heap is shortened by one: The element with the highest value is moved to (last - 1). + * + * While the element with the highest value is moved from first to (last - 1) (which now is out of the + * heap), the other elements are reorganized in such a way that the range [first, last - 1) preserves + * the properties of a heap. + * + * A range can be organized into a heap by calling {@link make_heap}. After that, its heap properties are + * preserved if elements are added and removed from it using {@link push_heap} and {@link pop_heap}, respectively. + * + * @param first {@link IArrayIterator Random-access iterator} to the initial position of the heap to be shrank by one. + * @param last {@link IArrayIterator Random-access iterator} to the final position of the heap to be shrank by one. + * The range used is [first, last), which contains all the elements between first and + * last, including the element pointed by first but not the element pointed by last. + * {@link IArrayIterator RandomAccessIterator} shall point to a type for which {@link Iterator.swap swap} + * is properly defined. + */ + function pop_heap>(first: RandomAccessIterator, last: RandomAccessIterator): void; + /** + * Pop element from heap range. + * + * Rearranges the elements in the heap range [first, last) in such a way that the part considered a + * heap is shortened by one: The element with the highest value is moved to (last - 1). + * + * While the element with the highest value is moved from first to (last - 1) (which now is out of the + * heap), the other elements are reorganized in such a way that the range [first, last - 1) preserves + * the properties of a heap. + * + * A range can be organized into a heap by calling {@link make_heap}. After that, its heap properties are + * preserved if elements are added and removed from it using {@link push_heap} and {@link pop_heap}, respectively. + * + * @param first {@link IArrayIterator Random-access iterator} to the initial position of the heap to be shrank by one. + * @param last {@link IArrayIterator Random-access iterator} to the final position of the heap to be shrank by one. + * The range used is [first, last), which contains all the elements between first and + * last, including the element pointed by first but not the element pointed by last. + * {@link IArrayIterator RandomAccessIterator} shall point to a type for which {@link Iterator.swap swap} + * is properly defined. + * @param compare Binary function that accepts two elements in the range as arguments, and returns a value + * convertible to boolean. The value returned indicates whether the element passed as + * first argument is considered to go before the second in the specific strict weak ordering it defines. + * The function shall not modify any of its arguments. This can either be a function pointer or a + * function object. + */ + function pop_heap>(first: RandomAccessIterator, last: RandomAccessIterator, compare: (x: T, y: T) => boolean): void; + /** + * Test if range is heap. + * + * Returns true if the range [first, last) forms a heap, as if constructed with {@link make_heap}. + * + * The elements are compared using {@link less}. + * + * @param first {@link IArrayIterator Random-access iterator} to the initial position of the sequence. + * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence. The range used is + * [first, last), which contains all the elements between first and last, + * including the element pointed by first but not the element pointed by last. + * {@link IArrayIterator RandomAccessIterator} shall point to a type for which {@link Iterator.swap swap} + * is properly defined. + * + * @return true if the range [first, last) is a heap (as if constructed with + * {@link make_heap}), false otherwise. If the range [first, last) contains less + * than two elements, the function always returns true. + */ + function is_heap>(first: RandomAccessIterator, last: RandomAccessIterator): boolean; + /** + * Test if range is heap. + * + * Returns true if the range [first, last) forms a heap, as if constructed with {@link make_heap}. + * + * The elements are compared using compare. + * + * @param first {@link IArrayIterator Random-access iterator} to the initial position of the sequence. + * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence. The range used is + * [first, last), which contains all the elements between first and last, + * including the element pointed by first but not the element pointed by last. + * {@link IArrayIterator RandomAccessIterator} shall point to a type for which {@link Iterator.swap swap} + * is properly defined. + * @param compare Binary function that accepts two elements in the range as arguments, and returns a value + * convertible to boolean. The value returned indicates whether the element passed as + * first argument is considered to go before the second in the specific strict weak ordering it defines. + * The function shall not modify any of its arguments. This can either be a function pointer or a + * function object. + * + * @return true if the range [first, last) is a heap (as if constructed with + * {@link make_heap}), false otherwise. If the range [first, last) contains less + * than two elements, the function always returns true. + */ + function is_heap>(first: RandomAccessIterator, last: RandomAccessIterator, compare: (x: T, y: T) => boolean): boolean; + /** + * Find first element not in heap order. + * + * Returns an iterator to the first element in the range [first, last) which is not in a valid + * position if the range is considered a heap (as if constructed with {@link make_heap}). + * + * The range between first and the iterator returned is a heap. + * + * If the entire range is a valid heap, the function returns last. + * + * The elements are compared using {@link less}. + * + * @param first {@link IArrayIterator Random-access iterator} to the initial position of the sequence. + * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence. The range used is + * [first, last), which contains all the elements between first and last, + * including the element pointed by first but not the element pointed by last. + * {@link IArrayIterator RandomAccessIterator} shall point to a type for which {@link Iterator.swap swap} + * is properly defined. + */ + function is_heap_until>(first: RandomAccessIterator, last: RandomAccessIterator): RandomAccessIterator; + /** + * Find first element not in heap order. + * + * Returns an iterator to the first element in the range [first, last) which is not in a valid + * position if the range is considered a heap (as if constructed with {@link make_heap}). + * + * The range between first and the iterator returned is a heap. + * + * If the entire range is a valid heap, the function returns last. + * + * The elements are compared using {@link less}. + * + * @param first {@link IArrayIterator Random-access iterator} to the initial position of the sequence. + * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence. The range used is + * [first, last), which contains all the elements between first and last, + * including the element pointed by first but not the element pointed by last. + * {@link IArrayIterator RandomAccessIterator} shall point to a type for which {@link Iterator.swap swap} + * is properly defined. + * @param compare Binary function that accepts two elements in the range as arguments, and returns a value + * convertible to boolean. The value returned indicates whether the element passed as + * first argument is considered to go before the second in the specific strict weak ordering it defines. + * The function shall not modify any of its arguments. This can either be a function pointer or a + * function object. + */ + function is_heap_until>(first: RandomAccessIterator, last: RandomAccessIterator, compare: (x: T, y: T) => boolean): RandomAccessIterator; + /** + * Sort elements of heap. + * + * Sorts the elements in the heap range [first, last) into ascending order. + * + * The elements are compared using {@link less}, which shall be the same as used to construct the heap. + * + * The range loses its properties as a heap. + * + * @param first {@link IArrayIterator Random-access iterator} to the initial position of the sequence to be sorted. + * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence to be sorted. + * The range used is [first, last), which contains all the elements between first and + * last, including the element pointed by first but not the element pointed by last. + * {@link IArrayIterator RandomAccessIterator} shall point to a type for which {@link Iterator.swap swap} + * is properly defined. + */ + function sort_heap>(first: RandomAccessIterator, last: RandomAccessIterator): void; + /** + * Sort elements of heap. + * + * Sorts the elements in the heap range [first, last) into ascending order. + * + * The elements are compared using compare, which shall be the same as used to construct the heap. + * + * The range loses its properties as a heap. + * + * @param first {@link IArrayIterator Random-access iterator} to the initial position of the sequence to be sorted. + * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence to be sorted. + * The range used is [first, last), which contains all the elements between first and + * last, including the element pointed by first but not the element pointed by last. + * {@link IArrayIterator RandomAccessIterator} shall point to a type for which {@link Iterator.swap swap} + * is properly defined. + * @param compare Binary function that accepts two elements in the range as arguments, and returns a value + * convertible to boolean. The value returned indicates whether the element passed as + * first argument is considered to go before the second in the specific strict weak ordering it defines. + * The function shall not modify any of its arguments. This can either be a function pointer or a + * function object. + */ + function sort_heap>(first: RandomAccessIterator, last: RandomAccessIterator, compare: (x: T, y: T) => boolean): void; +} +declare namespace std { + /** + * Return iterator to lower bound. + * + * Returns an iterator pointing to the first element in the range [first, last) which does not + * compare less than val. + * + * The elements are compared using {@link less}. The elements in the range shall already be {@link is_sorted sorted} + * according to this same criterion ({@link less}), or at least {@link is_partitioned partitioned} with respect to + * val. + * + * The function optimizes the number of comparisons performed by comparing non-consecutive elements of the sorted + * range, which is specially efficient for {@link IArrayIterator random-access iterators}. + * + * Unlike {@link upper_bound}, the value pointed by the iterator returned by this function may also be equivalent + * to val, and not only greater. + * + * @param first {@link Iterator Forward iterator} to the initial position of a {@link is_sorted sorted} (or properly + * {@link is_partitioned partitioned}) sequence. + * @param last {@link Iterator Forward iterator} to the final position of a {@link is_sorted sorted} (or properly + * {@link is_partitioned partitioned}) sequence. The range used is [first, last), which + * contains all the elements between first and last, including the element pointed by + * first but not the element pointed by last. + * @param val Value of the lower bound to search for in the range. T shall be a type supporting being compared + * with elements of the range [first, last) as the left-hand side operand of {@link less}. + * + * @return An iterator to the lower bound of val in the range. If all the element in the range compare less than + * val, the function returns last. + */ + function lower_bound>(first: ForwardIterator, last: ForwardIterator, val: T): ForwardIterator; + /** + * Return iterator to lower bound. + * + * Returns an iterator pointing to the first element in the range [first, last) which does not + * compare less than val. + * + * The elements are compared using compare. The elements in the range shall already be + * {@link is_sorted sorted} according to this same criterion (compare), or at least + * {@link is_partitioned partitioned} with respect to val. + * + * The function optimizes the number of comparisons performed by comparing non-consecutive elements of the sorted + * range, which is specially efficient for {@link IArrayIterator random-access iterators}. + * + * Unlike {@link upper_bound}, the value pointed by the iterator returned by this function may also be equivalent + * to val, and not only greater. + * + * @param first {@link Iterator Forward iterator} to the initial position of a {@link is_sorted sorted} (or properly + * {@link is_partitioned partitioned}) sequence. + * @param last {@link Iterator Forward iterator} to the final position of a {@link is_sorted sorted} (or properly + * {@link is_partitioned partitioned}) sequence. The range used is [first, last), which + * contains all the elements between first and last, including the element pointed by + * first but not the element pointed by last. + * @param val Value of the lower bound to search for in the range. + * @param compare Binary function that accepts two arguments (the first of the type pointed by ForwardIterator, + * and the second, always val), and returns a value convertible to bool. The value + * returned indicates whether the first argument is considered to go before the second. The function + * shall not modify any of its arguments. + * + * @return An iterator to the lower bound of val in the range. If all the element in the range compare less than + * val, the function returns last. + */ + function lower_bound>(first: ForwardIterator, last: ForwardIterator, val: T, compare: (x: T, y: T) => boolean): ForwardIterator; + /** + * Return iterator to upper bound. + * + * Returns an iterator pointing to the first element in the range [first, last) which compares + * greater than val. + * + * The elements are compared using {@link less}. The elements in the range shall already be {@link is_sorted sorted} + * according to this same criterion ({@link less}), or at least {@link is_partitioned partitioned} with respect to + * val. + * + * The function optimizes the number of comparisons performed by comparing non-consecutive elements of the sorted + * range, which is specially efficient for {@link IArrayIterator random-access iterators}. + * + * Unlike {@link lower_bound}, the value pointed by the iterator returned by this function cannot be equivalent to + * val, only greater. + * + * @param first {@link Iterator Forward iterator} to the initial position of a {@link is_sorted sorted} (or properly + * {@link is_partitioned partitioned}) sequence. + * @param last {@link Iterator Forward iterator} to the final position of a {@link is_sorted sorted} (or properly + * {@link is_partitioned partitioned}) sequence. The range used is [first, last), which + * contains all the elements between first and last, including the element pointed by + * first but not the element pointed by last. + * @param val Value of the lower bound to search for in the range. T shall be a type supporting being compared + * with elements of the range [first, last) as the left-hand side operand of {@link less}. + * + * @return An iterator to the upper bound of val in the range. If no element in the range comparse greater than + * val, the function returns last. + */ + function upper_bound>(first: ForwardIterator, last: ForwardIterator, val: T): ForwardIterator; + /** + * Return iterator to upper bound. + * + * Returns an iterator pointing to the first element in the range [first, last) which compares + * greater than val. + * + * The elements are compared using compare. The elements in the range shall already be + * {@link is_sorted sorted} according to this same criterion (compare), or at least + * {@link is_partitioned partitioned} with respect to val. + * + * The function optimizes the number of comparisons performed by comparing non-consecutive elements of the sorted + * range, which is specially efficient for {@link IArrayIterator random-access iterators}. + * + * Unlike {@link lower_bound}, the value pointed by the iterator returned by this function cannot be equivalent to + * val, only greater. + * + * @param first {@link Iterator Forward iterator} to the initial position of a {@link is_sorted sorted} (or properly + * {@link is_partitioned partitioned}) sequence. + * @param last {@link Iterator Forward iterator} to the final position of a {@link is_sorted sorted} (or properly + * {@link is_partitioned partitioned}) sequence. The range used is [first, last), which + * contains all the elements between first and last, including the element pointed by + * first but not the element pointed by last. + * @param val Value of the lower bound to search for in the range. + * @param compare Binary function that accepts two arguments (the first of the type pointed by ForwardIterator, + * and the second, always val), and returns a value convertible to bool. The value + * returned indicates whether the first argument is considered to go before the second. The function + * shall not modify any of its arguments. + * + * @return An iterator to the upper bound of val in the range. If no element in the range comparse greater than + * val, the function returns last. + */ + function upper_bound>(first: ForwardIterator, last: ForwardIterator, val: T, compare: (x: T, y: T) => boolean): ForwardIterator; + /** + * Get subrange of equal elements. + * + * Returns the bounds of the subrange that includes all the elements of the range [first, last) with + * values equivalent to val. + * + * The elements are compared using {@link less}. Two elements, ax/i> and y are considered equivalent + * if (!less(x, y) && !less(y, x)). + * + * The elements in the range shall already be {@link is_sorted sorted} according to this same criterion + * ({@link less}), or at least {@link is_partitioned partitioned} with respect to val. + * + * If val is not equivalent to any value in the range, the subrange returned has a length of zero, with both + * iterators pointing to the nearest value greater than val, if any, or to last, if val compares + * greater than all the elements in the range. + * + * @param first {@link Iterator Forward iterator} to the initial position of a {@link is_sorted sorted} (or properly + * {@link is_partitioned partitioned}) sequence. + * @param last {@link Iterator Forward iterator} to the final position of a {@link is_sorted sorted} (or properly + * {@link is_partitioned partitioned}) sequence. The range used is [first, last), which + * contains all the elements between first and last, including the element pointed by + * first but not the element pointed by last. + * @param val Value of the lower bound to search for in the range. T shall be a type supporting being compared + * with elements of the range [first, last) as the left-hand side operand of {@link less}. + * + * @return A {@link Pair} object, whose member {@link Pair.first} is an iterator to the lower bound of the subrange of + * equivalent values, and {@link Pair.second} its upper bound. The values are the same as those that would be + * returned by functions {@link lower_bound} and {@link upper_bound} respectively. + */ + function equal_range>(first: ForwardIterator, last: ForwardIterator, val: T): Pair; + /** + * Get subrange of equal elements. + * + * Returns the bounds of the subrange that includes all the elements of the range [first, last) with + * values equivalent to val. + * + * The elements are compared using compare. Two elements, ax/i> and y are considered equivalent + * if (!compare(x, y) && !compare(y, x)). + * + * The elements in the range shall already be {@link is_sorted sorted} according to this same criterion + * (compare), or at least {@link is_partitioned partitioned} with respect to val. + * + * If val is not equivalent to any value in the range, the subrange returned has a length of zero, with both + * iterators pointing to the nearest value greater than val, if any, or to last, if val compares + * greater than all the elements in the range. + * + * @param first {@link Iterator Forward iterator} to the initial position of a {@link is_sorted sorted} (or properly + * {@link is_partitioned partitioned}) sequence. + * @param last {@link Iterator Forward iterator} to the final position of a {@link is_sorted sorted} (or properly + * {@link is_partitioned partitioned}) sequence. The range used is [first, last), which + * contains all the elements between first and last, including the element pointed by + * first but not the element pointed by last. + * @param val Value of the lower bound to search for in the range. + * @param compare Binary function that accepts two arguments of the type pointed by ForwardIterator (and of type + * T), and returns a value convertible to bool. The value returned indicates whether + * the first argument is considered to go before the second. The function shall not modify any of its + * arguments. + * + * @return A {@link Pair} object, whose member {@link Pair.first} is an iterator to the lower bound of the subrange of + * equivalent values, and {@link Pair.second} its upper bound. The values are the same as those that would be + * returned by functions {@link lower_bound} and {@link upper_bound} respectively. + */ + function equal_range>(first: ForwardIterator, last: ForwardIterator, val: T, compare: (x: T, y: T) => boolean): Pair; + /** + * Get subrange of equal elements. + * + * Returns the bounds of the subrange that includes all the elements of the range [first, last) with + * values equivalent to val. + * + * The elements are compared using {@link less}. Two elements, x and y are considered equivalent + * if (!less(x, y) && !less(y, x)). + * + * The elements in the range shall already be {@link is_sorted sorted} according to this same criterion + * ({@link less}), or at least {@link is_partitioned partitioned} with respect to val. + * + * If val is not equivalent to any value in the range, the subrange returned has a length of zero, with both + * iterators pointing to the nearest value greater than val, if any, or to last, if val compares + * greater than all the elements in the range. + * + * @param first {@link Iterator Forward iterator} to the initial position of a {@link is_sorted sorted} (or properly + * {@link is_partitioned partitioned}) sequence. + * @param last {@link Iterator Forward iterator} to the final position of a {@link is_sorted sorted} (or properly + * {@link is_partitioned partitioned}) sequence. The range used is [first, last), which + * contains all the elements between first and last, including the element pointed by + * first but not the element pointed by last. + * @param val Value of the lower bound to search for in the range. T shall be a type supporting being compared + * with elements of the range [first, last) as the left-hand side operand of {@link less}. + * + * @return true if an element equivalent to val is found, and false otherwise. + */ + function binary_search>(first: ForwardIterator, last: ForwardIterator, val: T): boolean; + /** + * Get subrange of equal elements. + * + * Returns the bounds of the subrange that includes all the elements of the range [first, last) with + * values equivalent to val. + * + * The elements are compared using {compare}. Two elements, x and y are considered equivalent + * if (!compare(x, y) && !compare(y, x)). + * + * The elements in the range shall already be {@link is_sorted sorted} according to this same criterion + * (compare), or at least {@link is_partitioned partitioned} with respect to val. + * + * If val is not equivalent to any value in the range, the subrange returned has a length of zero, with both + * iterators pointing to the nearest value greater than val, if any, or to last, if val compares + * greater than all the elements in the range. + * + * @param first {@link Iterator Forward iterator} to the initial position of a {@link is_sorted sorted} (or properly + * {@link is_partitioned partitioned}) sequence. + * @param last {@link Iterator Forward iterator} to the final position of a {@link is_sorted sorted} (or properly + * {@link is_partitioned partitioned}) sequence. The range used is [first, last), which + * contains all the elements between first and last, including the element pointed by + * first but not the element pointed by last. + * @param val Value of the lower bound to search for in the range. + * @param compare Binary function that accepts two arguments of the type pointed by ForwardIterator (and of type + * T), and returns a value convertible to bool. The value returned indicates whether + * the first argument is considered to go before the second. The function shall not modify any of its + * arguments. + * + * @return true if an element equivalent to val is found, and false otherwise. + */ + function binary_search>(first: ForwardIterator, last: ForwardIterator, val: T, compare: (x: T, y: T) => boolean): boolean; +} +declare namespace std { + /** + * Test whether range is partitioned. + * + * Returns true if all the elements in the range [first, last) for which pred + * returns true precede those for which it returns false. + * + * If the range is {@link Container.empty empty}, the function returns true. + * + * @param first {@link Iterator Input iterator} to the initial position of the sequence. + * @param last {@link Iterator Input iterator} to the final position of the sequence. The range used is + * [first, last), which contains all the elements between first and last, + * including the element pointed by first but not the element pointed by last. + * @param pred Unary function that accepts an element in the range as argument, and returns a value convertible to + * bool. The value returned indicates whether the element belongs to the first group (if + * true, the element is expected before all the elements for which it returns + * false). The function shall not modify its argument. + * + * @return true if all the elements in the range [first, last) for which pred returns + * true precede those for which it returns false. Otherwise it returns + * false. If the range is {@link Container.empty empty}, the function returns true. + */ + function is_partitioned>(first: InputIterator, last: InputIterator, pred: (x: T) => boolean): boolean; + /** + * Partition range in two. + * + * Rearranges the elements from the range [first, last), in such a way that all the elements for + * which pred returns true precede all those for which it returns false. The iterator + * returned points to the first element of the second group. + * + * The relative ordering within each group is not necessarily the same as before the call. See + * {@link stable_partition} for a function with a similar behavior but with stable ordering within each group. + * + * @param first {@link Iterator Forward iterator} to the initial position of the sequence to partition. + * @param last {@link Iterator Forward iterator} to the final position of the sequence to partition. The range used is + * [first, last), which contains all the elements between first and last, + * including the element pointed by first but not the element pointed by last. + * @param pred Unary function that accepts an element in the range as argument, and returns a value convertible to + * bool. The value returned indicates whether the element belongs to the first group (if + * true, the element is expected before all the elements for which it returns + * false). The function shall not modify its argument. + * + * @return An iterator that points to the first element of the second group of elements (those for which pred + * returns false), or last if this group is {@link Container.empty empty}. + */ + function partition>(first: BidirectionalIterator, last: BidirectionalIterator, pred: (x: T) => boolean): BidirectionalIterator; + /** + * Partition range in two - stable ordering. + * + * Rearranges the elements in the range [first, last), in such a way that all the elements for which + * pred returns true precede all those for which it returns false, and, unlike + * function {@link partition}, the relative order of elements within each group is preserved. + * + * This is generally implemented using an internal temporary buffer. + * + * @param first {@link Iterator Bidirectional iterator} to the initial position of the sequence to partition. + * @param last {@link Iterator Bidirectional iterator} to the final position of the sequence to partition. The range + * used is [first, last), which contains all the elements between first and + * last, including the element pointed by first but not the element pointed by last. + * @param pred Unary function that accepts an element in the range as argument, and returns a value convertible to + * bool. The value returned indicates whether the element belongs to the first group (if + * true, the element is expected before all the elements for which it returns + * false). The function shall not modify its argument. + * + * @return An iterator that points to the first element of the second group of elements (those for which pred + * returns false), or last if this group is {@link Container.empty empty}. + */ + function stable_partition>(first: BidirectionalIterator, last: BidirectionalIterator, pred: (x: T) => boolean): BidirectionalIterator; + /** + * Partition range into two. + * + * Copies the elements in the range [first, last) for which pred returns true + * into the range pointed by result_true, and those for which it does not into the range pointed by + * result_false. + * + * @param first {@link Iterator Input iterator} to the initial position of the range to be copy-partitioned. + * @param last {@link Iterator Input iterator} to the final position of the range to be copy-partitioned. The range + * used is [first, last), which contains all the elements between first and + * last, including the element pointed by first but not the element pointed by last. + * @param result_true {@link Iterator Output iterator} to the initial position of the range where the elements for + * which pred returns true are stored. + * @param result_false {@link Iterator Output iterator} to the initial position of the range where the elements for + * which pred returns false are stored. + * @param pred Unary function that accepts an element pointed by InputIterator as argument, and returns a value + * convertible to bool. The value returned indicates on which result range the element is + * copied. The function shall not modify its argument. + * + * @return A {@link Pair} of iterators with the end of the generated sequences pointed by result_true and + * result_false, respectivelly. Its member {@link Pair.first first} points to the element that follows + * the last element copied to the sequence of elements for which pred returned true. Its + * member {@link Pair.second second} points to the element that follows the last element copied to the sequence + * of elements for which pred returned false. + */ + function partition_copy, OutputIterator1 extends base.ILinearIterator, OutputIterator2 extends base.ILinearIterator>(first: InputIterator, last: InputIterator, result_true: OutputIterator1, result_false: OutputIterator2, pred: (val: T) => T): Pair; + /** + * Get partition point. + * + * Returns an iterator to the first element in the partitioned range [first, last) for which + * pred is not true, indicating its partition point. + * + * The elements in the range shall already {@link is_partitioned be partitioned}, as if {@link partition} had been + * called with the same arguments. + * + * The function optimizes the number of comparisons performed by comparing non-consecutive elements of the sorted + * range, which is specially efficient for {@link Iteartor random-access iterators}. + * + * @param first {@link Iterator Forward iterator} to the initial position of the partitioned sequence. + * @param last {@link Iterator Forward iterator} to the final position of the partitioned sequence. The range checked + * is [first, last), which contains all the elements between first an last, + * including the element pointed by first but not the element pointed by last. + * @param pred Unary function that accepts an element in the range as argument, and returns a value convertible to + * bool. The value returned indicates whether the element goes before the partition point (if + * true, it goes before; if false goes at or after it). The function shall not + * modify its argument. + * + * @return An iterator to the first element in the partitioned range [first, last) for which pred + * is not true, or last if it is not true for any element. + */ + function partition_point>(first: ForwardIterator, last: ForwardIterator, pred: (x: T) => boolean): ForwardIterator; +} +declare namespace std { + /** + * Merge sorted ranges. + * + * Combines the elements in the sorted ranges [first1, last1) and [first2, last2), into + * a new range beginning at result with all its elements sorted. + * + * The elements are compared using {@link less}. The elements in both ranges shall already be ordered according to + * this same criterion ({@link less}). The resulting range is also sorted according to this. + * + * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. + * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence. The range used is + * [first1, last1), which contains all the elements between first1 and last1, + * including the element pointed by first1 but not the element pointed by last1. + * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. + * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. The range used is + * [first2, last2). + * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting combined + * range is stored. Its size is equal to the sum of both ranges above. + * + * @return An iterator pointing to the past-the-end element in the resulting sequence. + */ + function merge, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator): OutputIterator; + /** + * Merge sorted ranges. + * + * Combines the elements in the sorted ranges [first1, last1) and [first2, last2), into + * a new range beginning at result with all its elements sorted. + * + * The elements are compared using {@link less}. The elements in both ranges shall already be ordered according to + * this same criterion (compare). The resulting range is also sorted according to this. + * + * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. + * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence. The range used is + * [first1, last1), which contains all the elements between first1 and last1, + * including the element pointed by first1 but not the element pointed by last1. + * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. + * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. The range used is + * [first2, last2). + * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting combined + * range is stored. Its size is equal to the sum of both ranges above. + * @param compare Binary function that accepts two arguments of the types pointed by the iterators, and returns a value + * convertible to bool. The value returned indicates whether the first argument is + * considered to go before the second in the specific strict weak ordering it defines. The + * function shall not modify any of its arguments. + * + * @return An iterator pointing to the past-the-end element in the resulting sequence. + */ + function merge, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator, compare: (x: T, y: T) => boolean): OutputIterator; + /** + * Merge consecutive sorted ranges. + * + * Merges two consecutive sorted ranges: [first, middle) and [middle, last), putting + * the result into the combined sorted range [first, last). + * + * The elements are compared using {@link less}. The elements in both ranges shall already be ordered according to + * this same criterion ({@link less}). The resulting range is also sorted according to this. + * + * The function preserves the relative order of elements with equivalent values, with the elements in the first + * range preceding those equivalent in the second. + * + * @param first {@link Iterator Bidirectional iterator} to the initial position in the first sorted sequence to merge. + * This is also the initial position where the resulting merged range is stored. + * @param middle {@link Iterator Bidirectional iterator} to the initial position of the second sorted sequence, which + * because both sequences must be consecutive, matches the past-the-end position of the first + * sequence. + * @param last {@link Iterator Bidirectional iterator} to the past-the-end position of the second sorted + * sequence. This is also the past-the-end position of the range where the resulting merged range is + * stored. + */ + function inplace_merge>(first: BidirectionalIterator, middle: BidirectionalIterator, last: BidirectionalIterator): void; + /** + * Merge consecutive sorted ranges. + * + * Merges two consecutive sorted ranges: [first, middle) and [middle, last), putting + * the result into the combined sorted range [first, last). + * + * The elements are compared using compare. The elements in both ranges shall already be ordered according + * to this same criterion (compare). The resulting range is also sorted according to this. + * + * The function preserves the relative order of elements with equivalent values, with the elements in the first + * range preceding those equivalent in the second. + * + * @param first {@link Iterator Bidirectional iterator} to the initial position in the first sorted sequence to merge. + * This is also the initial position where the resulting merged range is stored. + * @param middle {@link Iterator Bidirectional iterator} to the initial position of the second sorted sequence, which + * because both sequences must be consecutive, matches the past-the-end position of the first + * sequence. + * @param last {@link Iterator Bidirectional iterator} to the past-the-end position of the second sorted + * sequence. This is also the past-the-end position of the range where the resulting merged range is + * stored. + * @param compare Binary function that accepts two arguments of the types pointed by the iterators, and returns a value + * convertible to bool. The value returned indicates whether the first argument is + * considered to go before the second in the specific strict weak ordering it defines. The + * function shall not modify any of its arguments. + */ + function inplace_merge>(first: BidirectionalIterator, middle: BidirectionalIterator, last: BidirectionalIterator, compare: (x: T, y: T) => boolean): void; + /** + * Test whether sorted range includes another sorted range. + * + * Returns true if the sorted range [first1, last1) contains all the elements in the + * sorted range [first2, last2). + * + * The elements are compared using {@link less}. Two elements, x and y are considered equivalent + * if (!less(x, y) && !less(y, x)). + * + * The elements in the range shall already be ordered according to this same criterion ({@link less}). + * + * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. + * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence (which is tested on + * whether it contains the second sequence). The range used is [first1, last1), which + * contains all the elements between first1 and last1, including the element pointed by + * first1 but not the element pointed by last1. + * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. + * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. (which is tested + * on whether it is contained in the first sequence). The range used is [first2, last2). + * + * @return true if every element in the range [first2, last2) is contained in the range + * [first1, last1), false otherwise. If [first2, last2) is an empty + * range, the function returns true. + */ + function includes, InputIterator2 extends Iterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2): boolean; + /** + * Test whether sorted range includes another sorted range. + * + * Returns true if the sorted range [first1, last1) contains all the elements in the + * sorted range [first2, last2). + * + * The elements are compared using compare. Two elements, x and y are considered equivalent + * if (!compare(x, y) && !compare(y, x)). + * + * The elements in the range shall already be ordered according to this same criterion (compare). + * + * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. + * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence (which is tested on + * whether it contains the second sequence). The range used is [first1, last1), which + * contains all the elements between first1 and last1, including the element pointed by + * first1 but not the element pointed by last1. + * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. + * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. (which is tested + * on whether it is contained in the first sequence). The range used is [first2, last2). + * @param compare Binary function that accepts two elements as arguments (one from each of the two sequences, in the + * same order), and returns a value convertible to bool. The value returned indicates + * whether the element passed as first argument is considered to go before the second in the specific + * strict weak ordering it defines. The function shall not modify any of its arguments. + * + * @return true if every element in the range [first2, last2) is contained in the range + * [first1, last1), false otherwise. If [first2, last2) is an empty + * range, the function returns true. + */ + function includes, InputIterator2 extends Iterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, compare: (x: T, y: T) => boolean): boolean; + /** + * Union of two sorted ranges. + * + * Constructs a sorted range beginning in the location pointed by result with the set union of the + * two sorted ranges [first1, last1) and [first2, last2). + * + * The union of two sets is formed by the elements that are present in either one of the sets, or in both. + * Elements from the second range that have an equivalent element in the first range are not copied to the resulting + * range. + * + * The elements are compared using {@link less}. Two elements, x and y are considered equivalent + * if (!less(x, y) && !less(y, x)). + * + * The elements in the ranges shall already be ordered according to this same criterion ({@link less}). The + * resulting range is also sorted according to this. + * + * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. + * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence. The range used is + * [first1, last1), which contains all the elements between first1 and last1, + * including the element pointed by first1 but not the element pointed by last1. + * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. + * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. The range used is + * [first2, last2). + * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is + * stored. The pointed type shall support being assigned the value of an element from the other ranges. + * + * @return An iterator to the end of the constructed range. + */ + function set_union, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator): OutputIterator; + /** + * Union of two sorted ranges. + * + * Constructs a sorted range beginning in the location pointed by result with the set union of the + * two sorted ranges [first1, last1) and [first2, last2). + * + * The union of two sets is formed by the elements that are present in either one of the sets, or in both. + * Elements from the second range that have an equivalent element in the first range are not copied to the resulting + * range. + * + * The elements are compared using compare. Two elements, x and y are considered equivalent + * if (!compare(x, y) && !compare(y, x)). + * + * The elements in the ranges shall already be ordered according to this same criterion (compare). The + * resulting range is also sorted according to this. + * + * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. + * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence. The range used is + * [first1, last1), which contains all the elements between first1 and last1, + * including the element pointed by first1 but not the element pointed by last1. + * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. + * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. The range used is + * [first2, last2). + * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is + * stored. The pointed type shall support being assigned the value of an element from the other ranges. + * @param compare Binary function that accepts two arguments of the types pointed by the input iterators, and returns a + * value convertible to bool. The value returned indicates whether the first argument is + * considered to go before the second in the specific strict weak ordering it defines. The + * function shall not modify any of its arguments. + * + * @return An iterator to the end of the constructed range. + */ + function set_union, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator, compare: (x: T, y: T) => boolean): OutputIterator; + /** + * Intersection of two sorted ranges. + * + * Constructs a sorted range beginning in the location pointed by result with the set intersection of + * the two sorted ranges [first1, last1) and [first2, last2). + * + * The intersection of two sets is formed only by the elements that are present in both sets. The elements + * copied by the function come always from the first range, in the same order. + * + * The elements are compared using {@link less}. Two elements, x and y are considered equivalent + * if (!less(x, y) && !less(y, x)). + * + * The elements in the ranges shall already be ordered according to this same criterion ({@link less}). The + * resulting range is also sorted according to this. + * + * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. + * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence. The range used is + * [first1, last1), which contains all the elements between first1 and last1, + * including the element pointed by first1 but not the element pointed by last1. + * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. + * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. The range used is + * [first2, last2). + * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is + * stored. The pointed type shall support being assigned the value of an element from the first range. + * + * @return An iterator to the end of the constructed range. + */ + function set_intersection, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator): OutputIterator; + /** + * Intersection of two sorted ranges. + * + * Constructs a sorted range beginning in the location pointed by result with the set intersection of + * the two sorted ranges [first1, last1) and [first2, last2). + * + * The intersection of two sets is formed only by the elements that are present in both sets. The elements + * copied by the function come always from the first range, in the same order. + * + * The elements are compared using compare. Two elements, x and y are considered equivalent + * if (!compare(x, y) && !compare(y, x)). + * + * The elements in the ranges shall already be ordered according to this same criterion (compare). The + * resulting range is also sorted according to this. + * + * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. + * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence. The range used is + * [first1, last1), which contains all the elements between first1 and last1, + * including the element pointed by first1 but not the element pointed by last1. + * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. + * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. The range used is + * [first2, last2). + * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is + * stored. The pointed type shall support being assigned the value of an element from the first range. + * @param compare Binary function that accepts two arguments of the types pointed by the input iterators, and returns a + * value convertible to bool. The value returned indicates whether the first argument is + * considered to go before the second in the specific strict weak ordering it defines. The + * function shall not modify any of its arguments. + * + * @return An iterator to the end of the constructed range. + */ + function set_intersection, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator, compare: (x: T, y: T) => boolean): OutputIterator; + /** + * Difference of two sorted ranges. + * + * Constructs a sorted range beginning in the location pointed by result with the set difference of + * the sorted range [first1, last1) with respect to the sorted range [first2, last2). + * + * The difference of two sets is formed by the elements that are present in the first set, but not in the + * second one. The elements copied by the function come always from the first range, in the same order. + * + * For containers supporting multiple occurrences of a value, the difference includes as many occurrences of + * a given value as in the first range, minus the amount of matching elements in the second, preserving order. + * + * Notice that this is a directional operation - for a symmetrical equivalent, see {@link set_symmetric_difference}. + * + * The elements are compared using {@link less}. Two elements, x and y are considered equivalent + * if (!less(x, y) && !less(y, x)). + * + * The elements in the ranges shall already be ordered according to this same criterion ({@link less}). The + * resulting range is also sorted according to this. + * + * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. + * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence. The range used is + * [first1, last1), which contains all the elements between first1 and last1, + * including the element pointed by first1 but not the element pointed by last1. + * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. + * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. The range used is + * [first2, last2). + * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is + * stored. The pointed type shall support being assigned the value of an element from the first range. + * + * @return An iterator to the end of the constructed range. + */ + function set_difference, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator): OutputIterator; + /** + * Difference of two sorted ranges. + * + * Constructs a sorted range beginning in the location pointed by result with the set difference of + * the sorted range [first1, last1) with respect to the sorted range [first2, last2). + * + * The difference of two sets is formed by the elements that are present in the first set, but not in the + * second one. The elements copied by the function come always from the first range, in the same order. + * + * For containers supporting multiple occurrences of a value, the difference includes as many occurrences of + * a given value as in the first range, minus the amount of matching elements in the second, preserving order. + * + * Notice that this is a directional operation - for a symmetrical equivalent, see {@link set_symmetric_difference}. + * + * The elements are compared using compare. Two elements, x and y are considered equivalent + * if (!compare(x, y) && !compare(y, x)). + * + * The elements in the ranges shall already be ordered according to this same criterion (compare). The + * resulting range is also sorted according to this. + * + * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. + * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence. The range used is + * [first1, last1), which contains all the elements between first1 and last1, + * including the element pointed by first1 but not the element pointed by last1. + * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. + * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. The range used is + * [first2, last2). + * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is + * stored. The pointed type shall support being assigned the value of an element from the first range. + * @param compare Binary function that accepts two arguments of the types pointed by the input iterators, and returns a + * value convertible to bool. The value returned indicates whether the first argument is + * considered to go before the second in the specific strict weak ordering it defines. The + * function shall not modify any of its arguments. + * + * @return An iterator to the end of the constructed range. + */ + function set_difference, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator, compare: (x: T, y: T) => boolean): OutputIterator; + /** + * Symmetric difference of two sorted ranges. + * + * Constructs a sorted range beginning in the location pointed by0 result with the set + * symmetric difference of the two sorted ranges [first1, last1) and [first2, last2). + * + * The symmetric difference of two sets is formed by the elements that are present in one of the sets, but + * not in the other. Among the equivalent elements in each range, those discarded are those that appear before in the + * existent order before the call. The existing order is also preserved for the copied elements. + * + * The elements are compared using {@link less}. Two elements, x and y are considered equivalent + * if (!less(x, y) && !less(y, x)). + * + * The elements in the ranges shall already be ordered according to this same criterion ({@link less}). The + * resulting range is also sorted according to this. + * + * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. + * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence. The range used is + * [first1, last1), which contains all the elements between first1 and last1, + * including the element pointed by first1 but not the element pointed by last1. + * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. + * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. The range used is + * [first2, last2). + * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is + * stored. The pointed type shall support being assigned the value of an element from the other ranges. + * @param compare Binary function that accepts two arguments of the types pointed by the input iterators, and returns a + * value convertible to bool. The value returned indicates whether the first argument is + * considered to go before the second in the specific strict weak ordering it defines. The + * function shall not modify any of its arguments. + * + * @return An iterator to the end of the constructed range. + */ + function set_symmetric_difference, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator): OutputIterator; + /** + * Symmetric difference of two sorted ranges. + * + * Constructs a sorted range beginning in the location pointed by0 result with the set + * symmetric difference of the two sorted ranges [first1, last1) and [first2, last2). + * + * The symmetric difference of two sets is formed by the elements that are present in one of the sets, but + * not in the other. Among the equivalent elements in each range, those discarded are those that appear before in the + * existent order before the call. The existing order is also preserved for the copied elements. + * + * The elements are compared using compare. Two elements, x and y are considered equivalent + * if (!compare(x, y) && !compare(y, x)). + * + * The elements in the ranges shall already be ordered according to this same criterion (compare). The + * resulting range is also sorted according to this. + * + * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. + * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence. The range used is + * [first1, last1), which contains all the elements between first1 and last1, + * including the element pointed by first1 but not the element pointed by last1. + * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. + * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. The range used is + * [first2, last2). + * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is + * stored. The pointed type shall support being assigned the value of an element from the other ranges. + * @param compare Binary function that accepts two arguments of the types pointed by the input iterators, and returns a + * value convertible to bool. The value returned indicates whether the first argument is + * considered to go before the second in the specific strict weak ordering it defines. The + * function shall not modify any of its arguments. + * + * @return An iterator to the end of the constructed range. + */ + function set_symmetric_difference, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator, compare: (x: T, y: T) => boolean): OutputIterator; +} +declare namespace std { + /** + * Return the smallest. + * + * Returns the smallest of all the elements in the args. + * + * @param args Values to compare. + * + * @return The lesser of the values passed as arguments. + */ + function min(...args: T[]): T; + /** + * Return the largest. + * + * Returns the largest of all the elements in the args. + * + * @param args Values to compare. + * + * @return The largest of the values passed as arguments. + */ + function max(...args: T[]): T; + /** + * Return smallest and largest elements. + * + * Returns a {@link Pair} with the smallest of all the elements in the args as first element (the first of + * them, if there are more than one), and the largest as second (the last of them, if there are more than one). + * + * @param args Values to compare. + * + * @return The lesser and greatest of the values passed as arguments. + */ + function minmax(...args: T[]): Pair; + /** + * Return smallest element in range. + * + * Returns an iterator pointing to the element with the smallest value in the range [first, last). + * + * The comparisons are performed using either {@link less}; An element is the smallest if no other element + * compares less than it. If more than one element fulfills this condition, the iterator returned points to the first + * of such elements. + * + * @param first {@link Iteartor Input iterator} to the initial final position of the sequence to compare. + * @param last {@link Iteartor Input iterator} to the final final position of the sequence to compare. The range used + * is [first, last), which contains all the elements between first and last, + * including the element pointed by first but not the element pointed by last. + * + * @return An iterator to smallest value in the range, or last if the range is empty. + */ + function min_element>(first: ForwardIterator, last: ForwardIterator): ForwardIterator; + /** + * Return smallest element in range. + * + * Returns an iterator pointing to the element with the smallest value in the range [first, last). + * + * The comparisons are performed using either compare; An element is the smallest if no other element + * compares less than it. If more than one element fulfills this condition, the iterator returned points to the first + * of such elements. + * + * @param first {@link Iteartor Input iterator} to the initial final position of the sequence to compare. + * @param last {@link Iteartor Input iterator} to the final final position of the sequence to compare. The range used + * is [first, last), which contains all the elements between first and last, + * including the element pointed by first but not the element pointed by last. + * @param compare Binary function that accepts two elements in the range as arguments, and returns a value convertible + * to bool. The value returned indicates whether the element passed as first argument is + * considered less than the second. The function shall not modify any of its arguments. + * + * @return An iterator to smallest value in the range, or last if the range is empty. + */ + function min_element>(first: ForwardIterator, last: ForwardIterator, compare: (x: T, y: T) => boolean): ForwardIterator; + /** + * Return largest element in range. + * + * Returns an iterator pointing to the element with the largest value in the range [first, last). + * + * The comparisons are performed using either {@link greater}; An element is the largest if no other element + * compares less than it. If more than one element fulfills this condition, the iterator returned points to the first + * of such elements. + * + * @param first {@link Iteartor Input iterator} to the initial final position of the sequence to compare. + * @param last {@link Iteartor Input iterator} to the final final position of the sequence to compare. The range used + * is [first, last), which contains all the elements between first and last, + * including the element pointed by first but not the element pointed by last. + * + * @return An iterator to largest value in the range, or last if the range is empty. + */ + function max_element>(first: ForwardIterator, last: ForwardIterator): ForwardIterator; + /** + * Return largest element in range. + * + * Returns an iterator pointing to the element with the largest value in the range [first, last). + * + * The comparisons are performed using either compare; An element is the largest if no other element + * compares less than it. If more than one element fulfills this condition, the iterator returned points to the first + * of such elements. + * + * @param first {@link Iteartor Input iterator} to the initial final position of the sequence to compare. + * @param last {@link Iteartor Input iterator} to the final final position of the sequence to compare. The range used + * is [first, last), which contains all the elements between first and last, + * including the element pointed by first but not the element pointed by last. + * @param compare Binary function that accepts two elements in the range as arguments, and returns a value convertible + * to bool. The value returned indicates whether the element passed as first argument is + * considered less than the second. The function shall not modify any of its arguments. + * + * @return An iterator to largest value in the range, or last if the range is empty. + */ + function max_element>(first: ForwardIterator, last: ForwardIterator, compare: (x: T, y: T) => boolean): ForwardIterator; + /** + * Return smallest and largest elements in range. + * + * Returns a {@link Pair} with an iterator pointing to the element with the smallest value in the range + * [first, last) as first element, and the largest as second. + * + * The comparisons are performed using either {@link less} and {@link greater}. + * + * If more than one equivalent element has the smallest value, the first iterator points to the first of such + * elements. + * + * If more than one equivalent element has the largest value, the second iterator points to the last of such + * elements. + * + * @param first {@link Iteartor Input iterator} to the initial final position of the sequence to compare. + * @param last {@link Iteartor Input iterator} to the final final position of the sequence to compare. The range used + * is [first, last), which contains all the elements between first and last, + * including the element pointed by first but not the element pointed by last. + * @param compare Binary function that accepts two elements in the range as arguments, and returns a value convertible + * to bool. The value returned indicates whether the element passed as first argument is + * considered less than the second. The function shall not modify any of its arguments. + * + * @return A {@link Pair} with an iterator pointing to the element with the smallest value in the range + * [first, last) as first element, and the largest as second. + */ + function minmax_element>(first: ForwardIterator, last: ForwardIterator): Pair; + /** + * Return smallest and largest elements in range. + * + * Returns a {@link Pair} with an iterator pointing to the element with the smallest value in the range + * [first, last) as first element, and the largest as second. + * + * The comparisons are performed using either compare. + * + * If more than one equivalent element has the smallest value, the first iterator points to the first of such + * elements. + * + * If more than one equivalent element has the largest value, the second iterator points to the last of such + * elements. + * + * @param first {@link Iteartor Input iterator} to the initial final position of the sequence to compare. + * @param last {@link Iteartor Input iterator} to the final final position of the sequence to compare. The range used + * is [first, last), which contains all the elements between first and last, + * including the element pointed by first but not the element pointed by last. + * @param compare Binary function that accepts two elements in the range as arguments, and returns a value convertible + * to bool. The value returned indicates whether the element passed as first argument is + * considered less than the second. The function shall not modify any of its arguments. + * + * @return A {@link Pair} with an iterator pointing to the element with the smallest value in the range + * [first, last) as first element, and the largest as second. + */ + function minmax_element>(first: ForwardIterator, last: ForwardIterator, compare: (x: T, y: T) => boolean): Pair; + /** + * Clamp a value between a pair of boundary. + * + * @param v The value to clamp. + * @param lo Start of the boundaries to clamp *v* to. + * @param hi Terminal of the boundaries to clamp *v* to. + * + * @return *lo* if *v* is less than *lo*, *hi* if *hi* is less than *v*, otherwise *v*. + */ + function clamp(v: T, lo: T, hi: T): T; + /** + * Clamp a value between a pair of boundary. + * + * @param v The value to clamp. + * @param lo Start of the boundaries to clamp *v* to. + * @param hi Terminal of the boundaries to clamp *v* to. + * @param comp Binary function that accepts two elements as arguments (one of each of the two sequences, in the + * same order), and returns a value convertible to bool. The value returned indicates + * whether the elements are considered to match in the context of this function. + * + * @return *lo* if *v* is less than *lo*, *hi* if *hi* is less than *v*, otherwise *v*. + */ + function clamp(v: T, lo: T, hi: T, comp: (x: T, y: T) => boolean): T; + /** + * Test whether range is permutation of another. + * + * Compares the elements in the range [first1, last1) with those in the range beginning at + * first2, and returns true if all of the elements in both ranges match, even in a different + * order. + * + * @param first1 An {@link Iterator} to the initial position of the first sequence. + * @param last1 An {@link Iterator} to the final position in a sequence. The range used is + * [first1, last1), including the element pointed by first1, but not the element + * pointed by last1. + * @param first2 An {@link Iterator} to the initial position of the second sequence. The comparison includes up to + * as many elements of this sequence as those in the range [first1, last1). + * + * @return true if all the elements in the range [first1, last1) compare equal to those + * of the range starting at first2 in any order, and false otherwise. + */ + function is_permutation, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2): boolean; + /** + * Test whether range is permutation of another. + * + * Compares the elements in the range [first1, last1) with those in the range beginning at + * first2, and returns true if all of the elements in both ranges match, even in a different + * order. + * + * @param first1 An {@link Iterator} to the initial position of the first sequence. + * @param last1 An {@link Iterator} to the final position in a sequence. The range used is + * [first1, last1), including the element pointed by first1, but not the element + * pointed by last1. + * @param first2 An {@link Iterator} to the initial position of the second sequence. The comparison includes up to + * as many elements of this sequence as those in the range [first1, last1). + * @param pred Binary function that accepts two elements as argument (one of each of the two sequences, in the same + * order), and returns a value convertible to bool. The value returned indicates whether + * the elements are considered to match in the context of this function. + * + * @return true if all the elements in the range [first1, last1) compare equal to those + * of the range starting at first2 in any order, and false otherwise. + */ + function is_permutation, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, pred: (x: T, y: T) => boolean): boolean; + /** + * Transform range to previous permutation. + * + * Rearranges the elements in the range [*first*, *last*) into the previous *lexicographically-ordered* permutation. + * + * A *permutation* is each one of the N! possible arrangements the elements can take (where *N* is the number of + * elements in the range). Different permutations can be ordered according to how they compare + * {@link lexicographicaly lexicographical_compare} to each other; The first such-sorted possible permutation (the one + * that would compare *lexicographically smaller* to all other permutations) is the one which has all its elements + * sorted in ascending order, and the largest has all its elements sorted in descending order. + * + * The comparisons of individual elements are performed using the {@link less less()} function. + * + * If the function can determine the previous permutation, it rearranges the elements as such and returns true. If + * that was not possible (because it is already at the lowest possible permutation), it rearranges the elements + * according to the last permutation (sorted in descending order) and returns false. + * + * @param first Bidirectional iterators to the initial positions of the sequence + * @param last Bidirectional iterators to the final positions of the sequence. The range used is [*first*, *last*), + * which contains all the elements between *first* and *last*, including the element pointed by *first* + * but not the element pointed by *last*. + * + * @return true if the function could rearrange the object as a lexicographicaly smaller permutation. Otherwise, the + * function returns false to indicate that the arrangement is not less than the previous, but the largest + * possible (sorted in descending order). + */ + function prev_permutation>(first: BidirectionalIterator, last: BidirectionalIterator): boolean; + /** + * Transform range to previous permutation. + * + * Rearranges the elements in the range [*first*, *last*) into the previous *lexicographically-ordered* permutation. + * + * A *permutation* is each one of the N! possible arrangements the elements can take (where *N* is the number of + * elements in the range). Different permutations can be ordered according to how they compare + * {@link lexicographicaly lexicographical_compare} to each other; The first such-sorted possible permutation (the one + * that would compare *lexicographically smaller* to all other permutations) is the one which has all its elements + * sorted in ascending order, and the largest has all its elements sorted in descending order. + * + * The comparisons of individual elements are performed using the *compare*. + * + * If the function can determine the previous permutation, it rearranges the elements as such and returns true. If + * that was not possible (because it is already at the lowest possible permutation), it rearranges the elements + * according to the last permutation (sorted in descending order) and returns false. + * + * @param first Bidirectional iterators to the initial positions of the sequence + * @param last Bidirectional iterators to the final positions of the sequence. The range used is [*first*, *last*), + * which contains all the elements between *first* and *last*, including the element pointed by *first* + * but not the element pointed by *last*. + * @param compare Binary function that accepts two arguments of the type pointed by BidirectionalIterator, and returns + * a value convertible to bool. The value returned indicates whether the first argument is considered + * to go before the second in the specific strict weak ordering it defines. + * + * @return true if the function could rearrange the object as a lexicographicaly smaller permutation. Otherwise, the + * function returns false to indicate that the arrangement is not less than the previous, but the largest + * possible (sorted in descending order). + */ + function prev_permutation>(first: BidirectionalIterator, last: BidirectionalIterator, compare: (x: T, y: T) => boolean): boolean; + /** + * Transform range to next permutation. + * + * Rearranges the elements in the range [*first*, *last*) into the next *lexicographically greater* permutation. + * + * A permutation is each one of the *N!* possible arrangements the elements can take (where *N* is the number of + * elements in the range). Different permutations can be ordered according to how they compare + * {@link lexicographicaly lexicographical_compare} to each other; The first such-sorted possible permutation (the one + * that would compare *lexicographically smaller* to all other permutations) is the one which has all its elements + * sorted in ascending order, and the largest has all its elements sorted in descending order. + * + * The comparisons of individual elements are performed using the {@link less} function. + * + * If the function can determine the next higher permutation, it rearranges the elements as such and returns true. If + * that was not possible (because it is already at the largest possible permutation), it rearranges the elements + * according to the first permutation (sorted in ascending order) and returns false. + * + * @param first Bidirectional iterators to the initial positions of the sequence + * @param last Bidirectional iterators to the final positions of the sequence. The range used is [*first*, *last*), + * which contains all the elements between *first* and *last*, including the element pointed by *first* + * but not the element pointed by *last*. + * + * @return true if the function could rearrange the object as a lexicographicaly greater permutation. Otherwise, the + * function returns false to indicate that the arrangement is not greater than the previous, but the lowest + * possible (sorted in ascending order). + */ + function next_permutation>(first: BidirectionalIterator, last: BidirectionalIterator): boolean; + /** + * Transform range to next permutation. + * + * Rearranges the elements in the range [*first*, *last*) into the next *lexicographically greater* permutation. + * + * A permutation is each one of the *N!* possible arrangements the elements can take (where *N* is the number of + * elements in the range). Different permutations can be ordered according to how they compare + * {@link lexicographicaly lexicographical_compare} to each other; The first such-sorted possible permutation (the one + * that would compare *lexicographically smaller* to all other permutations) is the one which has all its elements + * sorted in ascending order, and the largest has all its elements sorted in descending order. + * + * The comparisons of individual elements are performed using the *compare*. + * + * If the function can determine the next higher permutation, it rearranges the elements as such and returns true. If + * that was not possible (because it is already at the largest possible permutation), it rearranges the elements + * according to the first permutation (sorted in ascending order) and returns false. + * + * @param first Bidirectional iterators to the initial positions of the sequence + * @param last Bidirectional iterators to the final positions of the sequence. The range used is [*first*, *last*), + * which contains all the elements between *first* and *last*, including the element pointed by *first* + * but not the element pointed by *last*. + * @param compare Binary function that accepts two arguments of the type pointed by BidirectionalIterator, and returns + * a value convertible to bool. The value returned indicates whether the first argument is considered + * to go before the second in the specific strict weak ordering it defines. + * + * @return true if the function could rearrange the object as a lexicographicaly greater permutation. Otherwise, the + * function returns false to indicate that the arrangement is not greater than the previous, but the lowest + * possible (sorted in ascending order). + */ + function next_permutation>(first: BidirectionalIterator, last: BidirectionalIterator, compare: (x: T, y: T) => boolean): boolean; +} +declare namespace std.base { + /** + * An abstract container. + * + * + * + * + * + * ### Container properties + *
+ *
Sequence
+ *
Elements in sequence containers are ordered in a strict linear sequence. Individual elements are + * accessed by their position in this sequence.
+ * + *
Doubly-linked list
+ *
Each element keeps information on how to locate the next and the previous elements, allowing + * constant time insert and erase operations before or after a specific element (even of entire ranges), + * but no direct random access.
+ *
+ * + * @param Type of elements. + * + * @author Jeongho Nam + */ + abstract class Container { + /** + * Default Constructor. + */ + protected constructor(); + /** + * Assign new content to content. + * + * Assigns new contents to the container, replacing its current contents, and modifying its + * {@link size} accordingly. + * + * @param begin Input interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. + */ + abstract assign>(begin: InputIterator, end: InputIterator): void; + /** + * Clear content. + * + * Removes all elements from the Container, leaving the container with a size of 0. + */ + clear(): void; + /** + * Return iterator to beginning. + * + * Returns an iterator referring the first element in the + * + * #### Note + * If the container is {@link empty}, the returned iterator is same with {@link end end()}. + * + * @return An iterator to the first element in the The iterator containes the first element's value. + */ + abstract begin(): Iterator; + /** + * Return iterator to end. + * Returns an iterator referring to the past-the-end element in the + * + * The past-the-end element is the theoretical element that would follow the last element in the + * It does not point to any element, and thus shall not be dereferenced. + * + * Because the ranges used by functions of the Container do not include the element reference by their + * closing iterator, this function is often used in combination with {@link Container}.{@link begin} to + * specify a range including all the elements in the container. + * + * #### Note + * Returned iterator from {@link Container}.{@link end} does not refer any element. Trying to accessing + * element by the iterator will cause throwing exception ({@link OutOfRange}). + * + * If the container is {@link empty}, this function returns the same as {@link Container}.{@link begin}. + * + * + * @return An iterator to the end element in the + */ + abstract end(): Iterator; + /** + * Return {@link ReverseIterator reverse iterator} to reverse beginning. + * + * Returns a {@link ReverseIterator reverse iterator} pointing to the last element in the container (i.e., + * its reverse beginning). + * + * {@link ReverseIterator reverse iterators} iterate backwards: increasing them moves them towards the + * beginning of the + * + * {@link rbegin} points to the element right before the one that would be pointed to by member {@link end}. + * + * + * @return A {@link ReverseIterator reverse iterator} to the reverse beginning of the sequence + */ + abstract rbegin(): IReverseIterator; + /** + * Return {@link ReverseIterator reverse iterator} to reverse end. + * + * Returns a {@link ReverseIterator reverse iterator} pointing to the theoretical element preceding the + * first element in the container (which is considered its reverse end). + * + * The range between {@link Container}.{@link rbegin} and {@link Container}.{@link rend} contains all + * the elements of the container (in reverse order). + * + * @return A {@link ReverseIterator reverse iterator} to the reverse end of the sequence + */ + abstract rend(): IReverseIterator; + /** + * Return the number of elements in the {@link Container}. + * + * @return The number of elements in the container. + */ + abstract size(): number; + /** + * Test whether the container is empty. + * Returns whether the container is empty (i.e. whether its size is 0). + * + * This function does not modify the container in any way. To clear the content of the container, + * see {@link clear clear()}. + * + * @return true if the container size is 0, false otherwise. + */ + empty(): boolean; + /** + * Insert elements. + * + * Appends new elements to the container, and returns the new size of the + * + * @param items New elements to insert. + * + * @return New size of the Container. + */ + abstract push(...items: T[]): number; + /** + * Insert an element. + * + * The container is extended by inserting a new element before the element at the specified + * position. This effectively increases the {@link Container.size container size} by the amount of + * elements inserted. + * + * @param position Position in the {@link Container} where the new element is inserted. + * {@link iterator} is a member type, defined as a {@link Iterator random access iterator} + * type that points to elements. + * @param val Value to be copied to the inserted element. + * + * @re + public abstract insert(position: Iterator, val: T): Iterator; + + /* --------------------------------------------------------- + ERASE + --------------------------------------------------------- */ + /** + * Erase an element. + * + * Removes from the container a single element. + * + * This effectively reduces the container size by the number of element removed. + * + * @param position Iterator pointing to a single element to be removed from the Container. + * + * @return An iterator pointing to the element that followed the last element erased by the function + * call. This is the {@link end Container.end} if the operation erased the last element in the + * sequence. + */ + abstract erase(position: Iterator): Iterator; + /** + * Erase elements. + * + * Removes from the container a range of elements. + * + * This effectively reduces the container size by the number of elements removed. + * + * @param begin An iterator specifying a range of beginning to erase. + * @param end An iterator specifying a range of end to erase. + * + * @return An iterator pointing to the element that followed the last element erased by the function + * call. This is the {@link end Container.end} if the operation erased the last element in + * the sequence. + */ + abstract erase(begin: Iterator, end: Iterator): Iterator; + /** + * Swap content. + * + * Exchanges the content of the container by the content of obj, which is another + * {@link Container container} object with same type of elements. Sizes and container type may differ. + * + * After the call to this member function, the elements in this container are those which were in obj + * before the call, and the elements of obj are those which were in this. All iterators, references and + * pointers remain valid for the swapped objects. + * + * Notice that a non-member function exists with the same name, {@link swap swap}, overloading that + * algorithm with an optimization that behaves like this member function. + * + * @param obj Another {@link Container container} of the same type of elements (i.e., instantiated + * with the same template parameter, T) whose content is swapped with that of this + * {@link Container container}. + */ + swap(obj: Container): void; + } + interface IReverseIterator extends ReverseIterator, Iterator, IReverseIterator> { + } +} +declare namespace std { + /** + * Bi-directional iterator. + * + * {@link Iterator Bidirectional iterators} are iterators that can be used to access the sequence of elements + * in a range in both directions (towards the end and towards the beginning). + * + * All {@link IArrayIterator random-access iterators} are also valid {@link Iterrator bidirectional iterators}. + * + * There is not a single type of {@link Iterator bidirectional iterator}: {@link Container Each container} + * may define its own specific iterator type able to iterate through it and access its elements. + * + * + * + * + * @reference http://www.cplusplus.com/reference/iterator/BidirectionalIterator + * @author Jeongho Nam + */ + abstract class Iterator { + /** + * @hidden + */ + protected source_: base.Container; + /** + * Construct from the source {@link Container container}. + * + * @param source The source container. + */ + protected constructor(source: base.Container); + /** + * Get iterator to previous element. + * + * If current iterator is the first item(equal with {@link Container.begin Container.begin()}), + * returns {@link Container.end Container.end()}. + * + * @return An iterator of the previous item. + */ + abstract prev(): Iterator; + /** + * Get iterator to next element. + * + * If current iterator is the last item, returns {@link Container.end Container.end()}. + * + * @return An iterator of the next item. + */ + abstract next(): Iterator; + /** + * Advances the {@link Iterator} by n element positions. + * + * @param n Number of element positions to advance. + * @return An advanced iterator. + */ + abstract advance(n: number): Iterator; + /** + * Get source container. + * + * Get source container of this iterator is directing for. + */ + abstract source(): base.Container; + /** + * Whether an iterator is equal with the iterator. + * + * Compare two iterators and returns whether they are equal or not. + * + * #### Note + * Iterator's {@link equals equals()} only compare souce container and index number. + * + * Although elements in a pair, key and value are {@link equal_to equal_to}, if the source map or + * index number is different, then the {@link equals equals()} will return false. If you want to + * compare the elements of a pair, compare them directly by yourself. + * + * @param obj An iterator to compare + * @return Indicates whether equal or not. + */ + equals(obj: Iterator): boolean; + /** + * Get value of the iterator is pointing. + * + * @return A value of the iterator. + */ + readonly abstract value: T; + abstract swap(obj: Iterator): void; + } +} +declare namespace std { + /** + * This class reverses the direction in which a bidirectional or random-access iterator iterates through a range. + * + * A copy of the original iterator (the {@link Iterator base iterator}) is kept internally and used to reflect + * the operations performed on the {@link ReverseIterator}: whenever the {@link ReverseIterator} is incremented, its + * {@link Iterator base iterator} is decreased, and vice versa. A copy of the {@link Iterator base iterator} with the + * current state can be obtained at any time by calling member {@link base}. + * + * Notice however that when an iterator is reversed, the reversed version does not point to the same element in + * the range, but to the one preceding it. This is so, in order to arrange for the past-the-end element of a + * range: An iterator pointing to a past-the-end element in a range, when reversed, is pointing to the last element + * (not past it) of the range (this would be the first element of the reversed range). And if an iterator to the + * first element in a range is reversed, the reversed iterator points to the element before the first element (this + * would be the past-the-end element of the reversed range). + * + * + * + * + * @reference http://www.cplusplus.com/reference/iterator/reverse_iterator + * @author Jeongho Nam + */ + abstract class ReverseIterator, Base extends Iterator, This extends ReverseIterator> extends Iterator { + /** + * @hidden + */ + protected base_: Base; + /** + * Construct from base iterator. + * + * @param base A reference of the base iterator, which iterates in the opposite direction. + */ + protected constructor(base: Base); + /** + * @hidden + */ + protected abstract _Create_neighbor(base: Base): This; + source(): Source; + /** + * Return base iterator. + * + * Return a reference of the base iteraotr. + * + * The base iterator is an iterator of the same type as the one used to construct the {@link ReverseIterator}, + * but pointing to the element next to the one the {@link ReverseIterator} is currently pointing to + * (a {@link ReverseIterator} has always an offset of -1 with respect to its base iterator). + * + * @return A reference of the base iterator, which iterates in the opposite direction. + */ + base(): Base; + /** + * Get value of the iterator is pointing. + * + * @return A value of the reverse iterator. + */ + readonly value: T; + /** + * @inheritdoc + */ + prev(): This; + /** + * @inheritdoc + */ + next(): This; + /** + * @inheritdoc + */ + advance(n: number): This; + /** + * @inheritdoc + */ + equals(obj: This): boolean; + /** + * @inheritdoc + */ + swap(obj: This): void; + } + /** + * Return the number of elements in the {@link Container}. + * + * @param container A container with a size method. + * @return The number of elements in the container. + */ + function size(container: base.Container): number; + /** + * Test whether the container is empty. + * + * Returns whether the {@link Container} is empty (i.e. whether its {@link size} is 0). + * + * @param container A container with a empty method. + * @return true if the container size is 0, false otherwise. + */ + function empty(container: base.Container): boolean; + /** + * Return distance between {@link Iterator iterators}. + * + * Calculates the number of elements between first and last. + * + * If it is a {@link IArrayIterator random-access iterator}, the function uses operator- to calculate this. + * Otherwise, the function uses the increase operator {@link Iterator.next next()} repeatedly. + * + * @param first Iterator pointing to the initial element. + * @param last Iterator pointing to the final element. This must be reachable from first. + * + * @return The number of elements between first and last. + */ + function distance>(first: InputIterator, last: InputIterator): number; + /** + * Advance iterator. + * + * Advances the iterator it by n elements positions. + * + * @param it Iterator to be advanced. + * @param n Number of element positions to advance. + * + * @return An iterator to the element n positions before it. + */ + function advance>(it: InputIterator, n: number): InputIterator; + /** + * Get iterator to previous element. + * + * Returns an iterator pointing to the element that it would be pointing to if advanced -n positions. + * + * @param it Iterator to base position. + * @param n Number of element positions offset (1 by default). + * + * @return An iterator to the element n positions before it. + */ + function prev>(it: BidirectionalIterator, n?: number): BidirectionalIterator; + /** + * Get iterator to next element. + * + * Returns an iterator pointing to the element that it would be pointing to if advanced n positions. + * + * @param it Iterator to base position. + * @param n Number of element positions offset (1 by default). + * + * @return An iterator to the element n positions away from it. + */ + function next>(it: ForwardIterator, n?: number): ForwardIterator; + /** + * Iterator to beginning. + * + * Returns an iterator pointing to the first element in the sequence. + * + * If the sequence is {@link empty}, the returned value shall not be dereferenced. + * + * @param container A container object of a class type for which member {@link begin} is defined. + * @return The same as returned by {@link begin begin()}. + */ + function begin(container: base.Container): Iterator; + function begin(container: Vector): VectorIterator; + function begin(container: List): ListIterator; + function begin(container: Deque): DequeIterator; + function begin(container: base.SetContainer): SetIterator; + function begin(container: base.MapContainer): MapIterator; + /** + * Iterator to reverse-beginning. + * + * Returns a reverse iterator pointing to the last element in the sequence. + * + * If the sequence is {@link empty}, the returned value shall not be dereferenced. + * + * @param container A container object of a class type for which member {@link rbegin} is defined. + * @return The same as returned by {@link rbegin()}. + */ + function rbegin(container: base.Container): base.IReverseIterator; + function rbegin(container: Vector): VectorReverseIterator; + function rbegin(container: List): ListReverseIterator; + function rbegin(container: Deque): DequeReverseIterator; + function rbegin(container: base.SetContainer): SetReverseIterator; + function rbegin(container: base.MapContainer): MapReverseIterator; + /** + * Iterator to end. + * + * Returns an iterator pointing to the past-the-end element in the sequence. + * + * If the sequence is {@link empty}, the returned value compares equal to the one returned by {@link begin} with the same argument. + * + * @param container A container of a class type for which member {@link end} is defined. + * @return The same as returned by {@link end end()}. + */ + function end(container: base.Container): Iterator; + function end(container: Vector): VectorIterator; + function end(container: List): ListIterator; + function end(container: Deque): DequeIterator; + function end(container: base.SetContainer): SetIterator; + function end(container: base.MapContainer): MapIterator; + /** + * Iterator to end. + * + * Returns an iterator pointing to the past-the-end element in the sequence. + * + * If the sequence is {@link empty}, the returned value compares equal to the one returned by {@link begin} with the same argument. + * + * @param container A container of a class type for which member {@link end} is defined. + * @return The same as returned by {@link end end()}. + */ + function rend(container: base.Container): base.IReverseIterator; + function rend(container: Vector): VectorReverseIterator; + function rend(container: List): ListReverseIterator; + function rend(container: Deque): DequeReverseIterator; + function rend(container: base.SetContainer): SetReverseIterator; + function rend(container: base.MapContainer): MapReverseIterator; + /** + * Make reverse iterator. + * + * @param it A reference of the base iterator, which iterates in the opposite direction. + * @return A {@link ReverseIterator reverse iterator} based on *it*. + */ + function make_reverse_iterator(it: VectorIterator): VectorReverseIterator; + function make_reverse_iterator(it: DequeIterator): DequeReverseIterator; + function make_reverse_iterator(it: ListIterator): ListReverseIterator; + function make_reverse_iterator(it: SetIterator): SetReverseIterator; + function make_reverse_iterator(it: MapIterator): MapReverseIterator; +} +declare namespace std.base { + /** + * @hidden + */ + abstract class _ListContainer> extends Container implements IDequeContainer { + /** + * @hidden + */ + private begin_; + /** + * @hidden + */ + private end_; + /** + * @hidden + */ + private size_; + /** + * Default Constructor. + */ + protected constructor(); + /** + * @hidden + */ + protected abstract _Create_iterator(prev: BidirectionalIterator, next: BidirectionalIterator, val: T): BidirectionalIterator; + /** + * @hidden + */ + protected _Set_begin(it: BidirectionalIterator): void; + /** + * @inheritdoc + */ + assign>(first: InputIterator, last: InputIterator): void; + /** + * @inheritdoc + */ + clear(): void; + /** + * @inheritdoc + */ + begin(): BidirectionalIterator; + /** + * @inheritdoc + */ + end(): BidirectionalIterator; + /** + * @inheritdoc + */ + size(): number; + /** + * @inheritdoc + */ + front(): T; + /** + * @inheritdoc + */ + back(): T; + /** + * @inheritdoc + */ + push_front(val: T): void; + /** + * @inheritdoc + */ + push_back(val: T): void; + /** + * @inheritdoc + */ + pop_front(): void; + /** + * @inheritdoc + */ + pop_back(): void; + /** + * @inheritdoc + */ + push(...items: T[]): number; + /** + * Insert an element. + * + * The container is extended by inserting a new element before the element at the specified + * position. This effectively increases the {@link List.size List size} by the amount of elements + * inserted. + * + * Unlike other standard sequence containers, {@link List} is specifically designed to be efficient + * inserting and removing elements in any position, even in the middle of the sequence. + * + * @param position Position in the container where the new element is inserted. + * {@link iterator}> is a member type, defined as a + * {@link ListIterator bidirectional iterator} type that points to elements. + * @param val Value to be inserted as an element. + * + * @return An iterator that points to the newly inserted element; val. + */ + insert(position: BidirectionalIterator, val: T): BidirectionalIterator; + /** + * Insert elements by repeated filling. + * + * The container is extended by inserting a new element before the element at the specified + * position. This effectively increases the {@link List.size List size} by the amount of elements + * inserted. + * + * Unlike other standard sequence containers, {@link List} is specifically designed to be efficient + * inserting and removing elements in any position, even in the middle of the sequence. + * + * @param position Position in the container where the new elements are inserted. The {@link iterator} is a + * member type, defined as a {@link ListIterator bidirectional iterator} type that points to + * elements. + * @param size Number of elements to insert. + * @param val Value to be inserted as an element. + * + * @return An iterator that points to the first of the newly inserted elements. + */ + insert(position: BidirectionalIterator, size: number, val: T): BidirectionalIterator; + /** + * Insert elements by range iterators. + * + * The container is extended by inserting a new element before the element at the specified + * position. This effectively increases the {@link List.size List size} by the amount of elements + * inserted. + * + * Unlike other standard sequence containers, {@link List} is specifically designed to be efficient + * inserting and removing elements in any position, even in the middle of the sequence. + * + * @param position Position in the container where the new elements are inserted. The {@link iterator} is a + * member type, defined as a {@link ListIterator bidirectional iterator} type that points to + * elements. + * @param begin An iterator specifying range of the begining element. + * @param end An iterator specifying range of the ending element. + * + * @return An iterator that points to the first of the newly inserted elements. + */ + insert>(position: BidirectionalIterator, begin: InputIterator, end: InputIterator): BidirectionalIterator; + /** + * @hidden + */ + private _Insert_by_repeating_val(position, n, val); + /** + * @hidden + */ + protected _Insert_by_range>(position: BidirectionalIterator, begin: InputIterator, end: InputIterator): BidirectionalIterator; + /** + * Erase an element. + * + * Removes from the {@link List} either a single element; position. + * + * This effectively reduces the container size by the number of element removed. + * + * Unlike other standard sequence containers, {@link List} objects are specifically designed to be + * efficient inserting and removing elements in any position, even in the middle of the sequence. + * + * @param position Iterator pointing to a single element to be removed from the {@link List}. + * + * @return An iterator pointing to the element that followed the last element erased by the function call. + * This is the {@link end end()} if the operation erased the last element in the sequence. + */ + erase(position: BidirectionalIterator): BidirectionalIterator; + /** + * Erase elements. + * + * Removes from the {@link List} container a range of elements. + * + * This effectively reduces the container {@link size} by the number of elements removed. + * + * Unlike other standard sequence containers, {@link List} objects are specifically designed to be + * efficient inserting and removing elements in any position, even in the middle of the sequence. + * + * @param begin An iterator specifying a range of beginning to erase. + * @param end An iterator specifying a range of end to erase. + * + * @return An iterator pointing to the element that followed the last element erased by the function call. + * This is the {@link end end()} if the operation erased the last element in the sequence. + */ + erase(begin: BidirectionalIterator, end: BidirectionalIterator): BidirectionalIterator; + /** + * @hidden + */ + protected _Erase_by_range(first: BidirectionalIterator, last: BidirectionalIterator): BidirectionalIterator; + /** + * Swap content. + * + * Exchanges the content of the container by the content of obj, which is another + * {@link List container} object with same type of elements. Sizes and container type may differ. + * + * After the call to this member function, the elements in this container are those which were in obj + * before the call, and the elements of obj are those which were in this. All iterators, references and + * pointers remain valid for the swapped objects. + * + * Notice that a non-member function exists with the same name, {@link swap swap}, overloading that + * algorithm with an optimization that behaves like this member function. + * + * @param obj Another {@link List container} of the same type of elements (i.e., instantiated + * with the same template parameter, T) whose content is swapped with that of this + * {@link List container}. + */ + swap(obj: _ListContainer): void; + /** + * @inheritdoc + */ + swap(obj: Container): void; + } +} +declare namespace std.base { + /** + * @hidden + */ + abstract class _ListIteratorBase extends Iterator { + /** + * @hidden + */ + protected prev_: _ListIteratorBase; + /** + * @hidden + */ + protected next_: _ListIteratorBase; + /** + * @hidden + */ + protected value_: T; + /** + * Initializer Constructor. + * + * @param source The source {@link Container} to reference. + * @param prev A refenrece of previous node ({@link ListIterator iterator}). + * @param next A refenrece of next node ({@link ListIterator iterator}). + * @param value Value to be stored in the node (iterator). + */ + protected constructor(source: Container, prev: _ListIteratorBase, next: _ListIteratorBase, value: T); + /** + * @inheritdoc + */ + prev(): _ListIteratorBase; + /** + * @inheritdoc + */ + next(): _ListIteratorBase; + /** + * @inheritdoc + */ + advance(step: number): _ListIteratorBase; + /** + * @inheritdoc + */ + readonly value: T; + /** + * @inheritdoc + */ + equals(obj: _ListIteratorBase): boolean; + /** + * @inheritdoc + */ + swap(obj: _ListIteratorBase): void; + } +} +declare namespace std.base { + /** + * An abstract error instance. + * + * {@link ErrorInstance} is an abstract class of {@link ErrorCode} and {@link ErrorCondition} + * holding an error instance's identifier {@link value}, associated with a {@link category}. + * + * The operating system and other low-level applications and libraries generate numerical error codes to + * represent possible results. These numerical values may carry essential information for a specific platform, + * but be non-portable from one platform to another. + * + * Objects of this class associate such numerical codes to {@link ErrorCategory error categories}, + * so that they can be interpreted when needed as more abstract (and portable) + * {@link ErrorCondition error conditions}. + * + * + * + * + * @author Jeongho Nam + */ + abstract class ErrorInstance { + /** + * @hidden + */ + protected category_: ErrorCategory; + /** + * @hidden + */ + protected value_: number; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from a numeric value and error category. + * + * @param val A numerical value identifying an error instance. + * @param category A reference to an {@link ErrorCategory} object. + */ + constructor(val: number, category: ErrorCategory); + /** + * Assign error instance. + * + * Assigns the {@link ErrorCode} object a value of val associated with the {@link ErrorCategory}. + * + * @param val A numerical value identifying an error instance. + * @param category A reference to an {@link ErrorCategory} object. + */ + assign(val: number, category: ErrorCategory): void; + /** + * Clear error instance. + * + * Clears the value in the {@link ErrorCode} object so that it is set to a value of 0 of the + * {@link ErrorCategory.systemCategory ErrorCategory.systemCategory()} (indicating no error). + */ + clear(): void; + /** + * Get category. + * + * Returns a reference to the {@link ErrorCategory} associated with the {@link ErrorCode} object. + * + * @return A reference to a non-copyable object of a type derived from {@link ErrorCategory}. + */ + category(): ErrorCategory; + /** + * Error value. + * + * Returns the error value associated with the {@link ErrorCode} object. + * + * @return The error value. + */ + value(): number; + /** + * Get message. + * + * Returns the message associated with the error instance. + * + * Error messages are defined by the {@link category} the error instance belongs to. + * + * This function returns the same as if the following member was called: + * + * category().message(value()) + * + * @return A string object with the message associated with the {@link ErrorCode}. + */ + message(): string; + /** + * Default error condition. + * + * Returns the default {@link ErrorCondition}object associated with the {@link ErrorCode} object. + * + * This function returns the same as if the following member was called: + * + * category().default_error_condition(value()) + * + * {@link ErrorCategory.default_error_condition ErrorCategory.default_error_condition()} + * is a virtual member function, that can operate differently for each category. + * + * @return An {@link ErrorCondition}object that corresponds to the {@link ErrorCode} object. + */ + default_error_condition(): ErrorCondition; + /** + * Convert to bool. + * + * Returns whether the error instance has a numerical {@link value} other than 0. + * + * If it is zero (which is generally used to represent no error), the function returns false, otherwise it returns true. + * + * @return true if the error's numerical value is not zero. + * false otherwise. + */ + to_bool(): boolean; + } +} +declare namespace std.base { + /** + * @hidden + */ + enum _Hash { + MIN_SIZE = 10, + RATIO = 1, + MAX_RATIO = 2, + } + /** + * @hidden + */ + abstract class _HashBuckets { + private buckets_; + private item_size_; + protected constructor(); + rehash(size: number): void; + clear(): void; + size(): number; + item_size(): number; + capacity(): number; + at(index: number): Vector; + hash_index(val: T): number; + insert(val: T): void; + erase(val: T): void; + } +} +declare namespace std.base { + /** + * @hidden + */ + class _MapHashBuckets extends _HashBuckets> { + private map_; + constructor(map: IHashMap); + find(key: K): MapIterator; + } +} +declare namespace std.base { + /** + * @hidden + */ + class _SetHashBuckets extends _HashBuckets> { + private set_; + constructor(set: IHashSet); + find(val: T): SetIterator; + } +} +declare namespace std.base { + /** + * Array Container. + * + * {@link IArrayContainer} is an interface for sequence containers representing arrays that can change in + * {@link size}. However, compared to arrays, {@link IArrayContainer} objectss consume more memory in exchange for + * the ability to manage storage and grow dynamically in an efficient way. + * + * Both {@link Vector Vectors} and {@link Deque Deques} who implemented {@link IArrayContainer} provide a very + * similar interface and can be used for similar purposes, but internally both work in quite different ways: + * While {@link Vector Vectors} use a single array that needs to be occasionally reallocated for growth, the + * elements of a {@link Deque} can be scattered in different chunks of storage, with the container keeping the + * necessary information internally to provide direct access to any of its elements in constant time and with a + * uniform sequential interface (through iterators). Therefore, {@link Deque Deques} are a little more complex + * internally than {@link Vector Vectors}, but this allows them to grow more efficiently under certain + * circumstances, especially with very long sequences, where reallocations become more expensive. + * + * Both {@link Vector Vectors} and {@link Deque Deques} provide a very similar interface and can be used for + * similar purposes, but internally both work in quite different ways: While {@link Vector Vectors} use a single + * array that needs to be occasionally reallocated for growth, the elements of a {@link Deque} can be scattered + * in different chunks of storage, with the container keeping the necessary information internally to provide + * direct access to any of its elements in constant time and with a uniform sequential interface (through + * iterators). Therefore, {@link Deque Deques} are a little more complex internally than {@link Vector Vectors}, + * but this allows them to grow more efficiently under certain circumstances, especially with very long + * sequences, where reallocations become more expensive. + * + * For operations that involve frequent insertion or removals of elements at positions other than the + * beginning or the end, {@link IArrayContainer} objects perform worse and have less consistent iterators and references + * than {@link List Lists}. + * + * + * + * + * + * ### Container properties + *
+ *
Sequence
+ *
+ * Elements in sequence containers are ordered in a strict linear sequence. Individual elements are + * accessed by their position in this sequence. + *
+ * + *
Dynamic array
+ *
+ * Allows direct access to any element in the sequence, even through pointer arithmetics, and provides + * relatively fast addition/removal of elements at the end of the sequence. + *
+ *
+ * + * @param Type of the elements. + * + * @author Jeongho Nam + */ + interface IArrayContainer extends ILinearContainer { + /** + * Access element. + * Returns a value to the element at position index in the {@link IArrayContainer container}.

+ * + * The function automatically checks whether index is within the bounds of valid elements + * in the {@link IArrayContainer container}, throwing an {@link OutOfRange} exception if it is not (i.e., + * if index is greater or equal than its {@link size}). + * + * @param index Position of an element in the + * If this is greater than or equal to the {@link IArrayContainer container} {@link size}, an + * exception of type {@link OutOfRange} is thrown. Notice that the first + * element has a position of 0 (not 1). + * + * @return The element at the specified position in the + */ + at(index: number): T; + /** + * Modify element. + * Replaces an element at the specified position (index) in this {@link IArrayContainer container} + * with the specified element (val). + * + * The function automatically checks whether index is within the bounds of valid elements + * in the {@link IArrayContainer container}, throwing an {@link OutOfRange} exception if it is not (i.e., if + * index is greater or equal than its {@link size}). + * + * @.param index A specified position of the value to replace. + * @param val A value to be stored at the specified position. + * + * @return The previous element had stored at the specified position. + */ + set(index: number, val: T): void; + } + /** + * Random-access iterator. + * + * {@link IArrayIterator Random-access iterators} are iterators that can be used to access elements at an + * arbitrary offset position relative to the element they point to, offering the same functionality as pointers. + * + * {@link IArrayIterator Random-access iterators} are the most complete iterators in terms of functionality. + * All pointer types are also valid {@link IArrayIterator random-access iterators}. + * + * There is not a single type of {@link IArrayIterator random-access iterator}: Each container may define its + * own specific iterator type able to iterate through it and access its elements. + * + * + * + * + * + * @reference http://www.cplusplus.com/reference/iterator/RandomAccessIterator + * @author Jeongho Nam + */ + interface IArrayIterator extends ILinearIterator { + /** + * @inheritdoc + */ + source(): IArrayContainer; + /** + * Get index, sequence number of the iterator in the source {@link IArrayContainer array}. + * + * @return Sequence number of the iterator in the source {@link IArrayContainer array}. + */ + index(): number; + /** + * @inheritdoc + */ + prev(): IArrayIterator; + /** + * @inheritdoc + */ + next(): IArrayIterator; + } +} +declare namespace std.base { + /** + * An interface for deque + * + * + * + * + * + * @author Jeongho Nam + */ + interface IDequeContainer extends ILinearContainer { + /** + * Insert element at beginning. + * + * Inserts a new element at the beginning of the {@link IDeque container}, right before its + * current first element. This effectively increases the {@link IDeque container} {@link size} by + * one. + * + * @param val Value to be inserted as an element. + */ + push_front(val: T): void; + /** + * Delete first element. + * + * Removes the first element in the {@link IDeque container}, effectively reducing its + * {@link size} by one. + */ + pop_front(): void; + } +} +declare namespace std.base { + /** + * Common interface for hash map. + * + * {@link IHashMap}s are associative containers that store elements formed by the combination of + * a key value and a mapped value. + * + * In an {@link IHashMap}, the key value is generally used to uniquely identify the + * element, while the mapped value is an object with the content associated to this key. + * Types of key and mapped value may differ. + * + * Internally, the elements in the {@link IHashMap} are not sorted in any particular order with + * respect to either their key or mapped values, but organized into buckets depending on + * their hash values to allow for fast access to individual elements directly by their key values + * (with a constant average time complexity on average). + * + * Elements with equivalent keys are grouped together in the same bucket and in such a way that + * an iterator can iterate through all of them. Iterators in the container are doubly linked iterators. + * + * + * + * + * + * ### Container properties + *
+ *
Associative
+ *
Elements in associative containers are referenced by their key and not by their absolute + * position in the container.
+ * + *
Hashed
+ *
Hashed containers organize their elements using hash tables that allow for fast access to elements + * by their key.
+ * + *
Map
+ *
Each element associates a key to a mapped value: + * Keys are meant to identify the elements whose main content is the mapped value.
+ *
+ * + * @param Type of the key values. + * Each element in an {@link IHashMap} is identified by a key value. + * @param Type of the mapped value. + * Each element in an {@link IHashMap} is used to store some data as its mapped value. + * + * @reference http://www.cplusplus.com/reference/unordered_map + * @author Jeongho Nam + */ + interface IHashMap extends MapContainer { + /** + * Return number of buckets. + * + * Returns the number of buckets in the {@link IHashMap} container. + * + * A bucket is a slot in the container's internal hash table to which elements are assigned based on the + * hash value of their key. + * + * The number of buckets influences directly the {@link load_factor load factor} of the container's hash + * table (and thus the probability of collision). The container automatically increases the number of buckets to + * keep the load factor below a specific threshold (its {@link max_load_factor}), causing a {@link rehash} each + * time the number of buckets needs to be increased. + * + * @return The current amount of buckets. + */ + bucket_count(): number; + /** + * Return bucket size. + * + * Returns the number of elements in bucket n. + * + * A bucket is a slot in the container's internal hash table to which elements are assigned based on the hash + * value of their key. + * + * The number of elements in a bucket influences the time it takes to access a particular element in the + * bucket. The container automatically increases the number of buckets to keep the {@link load_cator load factor} + * (which is the average bucket size) below its {@link max_load_factor}. + * + * @param n Bucket number. This shall be lower than {@link bucket_count}. + * + * @return The number of elements in bucket n. + */ + bucket_size(n: number): number; + /** + * Get maximum load factor. + * + * Returns the current maximum load factor for the {@link HashMultiMap} container. + * + * The load factor is the ratio between the number of elements in the container (its {@link size}) and the + * number of buckets ({@link bucket_count}). + * + * By default, {@link HashMultiMap} containers have a {@link max_load_factor} of 1.0. + * + * The load factor influences the probability of collision in the hash table (i.e., the probability of two + * elements being located in the same bucket). The container uses the value of max_load_factor as the threshold + * that forces an increase in the number of buckets (and thus causing a {@link rehash}). + * + * Note though, that implementations may impose an upper limit on the number of buckets (see + * {@link max_bucket_count}), which may force the container to ignore the {@link max_load_factor}. + * + * @return The current load factor. + */ + max_load_factor(): number; + /** + * Set maximum load factor. + * + * Sets z as the cnew maximum load factor for the {@link HashMultiMap} container. + * + * The load factor is the ratio between the number of elements in the container (its {@link size}) and the + * number of buckets ({@link bucket_count}). + * + * By default, {@link HashMultiMap} containers have a {@link max_load_factor} of 1.0. + * + * The load factor influences the probability of collision in the hash table (i.e., the probability of two + * elements being located in the same bucket). The container uses the value of max_load_factor as the threshold + * that forces an increase in the number of buckets (and thus causing a {@link rehash}). + * + * Note though, that implementations may impose an upper limit on the number of buckets (see + * {@link max_bucket_count}), which may force the container to ignore the {@link max_load_factor}. + * + * @param z The new maximum load factor. + */ + max_load_factor(z: number): void; + /** + * Locate element's bucket. + * + * Returns the bucket number where the element with key is located. + * + * A bucket is a slot in the container's internal hash table to which elements are assigned based on the + * hash value of their key. Buckets are numbered from 0 to ({@link bucket_count} - 1). + * + * Individual elements in a bucket can be accessed by means of the range iterators returned by + * {@link begin} and {@link end}. + * + * @param key Key whose bucket is to be located. + */ + bucket(key: Key): number; + /** + * Request a capacity change. + * + * Sets the number of buckets in the container ({@link bucket_count}) to the most appropriate to contain at + * least n elements. + * + * If n is greater than the current {@link bucket_count} multiplied by the {@link max_load_factor}, + * the container's {@link bucket_count} is increased and a {@link rehash} is forced. + * + * If n is lower than that, the function may have no effect. + * + * @param n The number of elements requested as minimum capacity. + */ + reserve(n: number): void; + /** + * Set number of buckets. + * + * Sets the number of buckets in the container to n or more. + * + * If n is greater than the current number of buckets in the container ({@link bucket_count}), a + * {@link HashBuckets.rehash rehash} is forced. The new {@link bucket_count bucket count} can either be equal or + * greater than n. + * + * If n is lower than the current number of buckets in the container ({@link bucket_count}), the + * function may have no effect on the {@link bucket_count bucket count} and may not force a + * {@link HashBuckets.rehash rehash}. + * + * A {@link HashBuckets.rehash rehash} is the reconstruction of the hash table: All the elements in the + * container are rearranged according to their hash value into the new set of buckets. This may alter the order + * of iteration of elements within the container. + * + * {@link HashBuckets.rehash Rehashes} are automatically performed by the container whenever its + * {@link load_factor load factor} is going to surpass its {@link max_load_factor} in an operation. + * + * Notice that this function expects the number of buckets as argument. A similar function exists, + * {@link reserve}, that expects the number of elements in the container as argument. + * + * @param n The minimum number of buckets for the container hash table. + */ + rehash(n: number): void; + } +} +declare namespace std.base { + /** + * A common interface for hash set. + * + * {@link IHashSet}s are containers that store unique elements in no particular order, and which + * allow for fast retrieval of individual elements based on their value. + * + * In an {@link IHashSet}, the value of an element is at the same time its key, that + * identifies it uniquely. Keys are immutable, therefore, the elements in an {@link IHashSet} cannot be + * modified once in the container - they can be inserted and removed, though. + * + * Internally, the elements in the {@link IHashSet} are not sorted in any particular order, but + * organized into buckets depending on their hash values to allow for fast access to individual elements + * directly by their values (with a constant average time complexity on average). + * + * {@link IHashSet} containers are faster than {@link TreeSet} containers to access individual + * elements by their key, although they are generally less efficient for range iteration through a + * subset of their elements. + * + * + * + * + * + * ### Container properties + *
+ *
Associative
+ *
Elements in associative containers are referenced by their key and not by their absolute + * position in the container.
+ * + *
Hashed
+ *
Hashed containers organize their elements using hash tables that allow for fast access to elements + * by their key.
+ * + *
Set
+ *
The value of an element is also the key used to identify it.
+ *
+ * + * @param Type of the elements. + * Each element in an {@link IHashSet} is also uniquely identified by this value. + * + * @reference http://www.cplusplus.com/reference/unordered_set/unordered_set + * @author Jeongho Nam + */ + interface IHashSet extends SetContainer { + /** + * Return number of buckets. + * + * Returns the number of buckets in the {@link IHashSet} container. + * + * A bucket is a slot in the container's internal hash table to which elements are assigned based on the + * hash value of their key. + * + * The number of buckets influences directly the {@link load_factor load factor} of the container's hash + * table (and thus the probability of collision). The container automatically increases the number of buckets to + * keep the load factor below a specific threshold (its {@link max_load_factor}), causing a {@link rehash} each + * time the number of buckets needs to be increased. + * + * @return The current amount of buckets. + */ + bucket_count(): number; + /** + * Return bucket size. + * + * Returns the number of elements in bucket n. + * + * A bucket is a slot in the container's internal hash table to which elements are assigned based on the hash + * value of their key. + * + * The number of elements in a bucket influences the time it takes to access a particular element in the + * bucket. The container automatically increases the number of buckets to keep the {@link load_cator load factor} + * (which is the average bucket size) below its {@link max_load_factor}. + * + * @param n Bucket number. This shall be lower than {@link bucket_count}. + * + * @return The number of elements in bucket n. + */ + bucket_size(n: number): number; + /** + * Get maximum load factor. + * + * Returns the current maximum load factor for the {@link HashMultiMap} container. + * + * The load factor is the ratio between the number of elements in the container (its {@link size}) and the + * number of buckets ({@link bucket_count}). + * + * By default, {@link HashMultiMap} containers have a {@link max_load_factor} of 1.0. + * + * The load factor influences the probability of collision in the hash table (i.e., the probability of two + * elements being located in the same bucket). The container uses the value of max_load_factor as the threshold + * that forces an increase in the number of buckets (and thus causing a {@link rehash}). + * + * Note though, that implementations may impose an upper limit on the number of buckets (see + * {@link max_bucket_count}), which may force the container to ignore the {@link max_load_factor}. + * + * @return The current load factor. + */ + max_load_factor(): number; + /** + * Set maximum load factor. + * + * Sets z as the cnew maximum load factor for the {@link HashMultiMap} container. + * + * The load factor is the ratio between the number of elements in the container (its {@link size}) and the + * number of buckets ({@link bucket_count}). + * + * By default, {@link HashMultiMap} containers have a {@link max_load_factor} of 1.0. + * + * The load factor influences the probability of collision in the hash table (i.e., the probability of two + * elements being located in the same bucket). The container uses the value of max_load_factor as the threshold + * that forces an increase in the number of buckets (and thus causing a {@link rehash}). + * + * Note though, that implementations may impose an upper limit on the number of buckets (see + * {@link max_bucket_count}), which may force the container to ignore the {@link max_load_factor}. + * + * @param z The new maximum load factor. + */ + max_load_factor(z: number): void; + /** + * Locate element's bucket. + * + * Returns the bucket number where the element with key is located. + * + * A bucket is a slot in the container's internal hash table to which elements are assigned based on the + * hash value of their key. Buckets are numbered from 0 to ({@link bucket_count} - 1). + * + * Individual elements in a bucket can be accessed by means of the range iterators returned by + * {@link begin} and {@link end}. + * + * @param key Key whose bucket is to be located. + */ + bucket(key: T): number; + /** + * Request a capacity change. + * + * Sets the number of buckets in the container ({@link bucket_count}) to the most appropriate to contain at + * least n elements. + * + * If n is greater than the current {@link bucket_count} multiplied by the {@link max_load_factor}, + * the container's {@link bucket_count} is increased and a {@link rehash} is forced. + * + * If n is lower than that, the function may have no effect. + * + * @param n The number of elements requested as minimum capacity. + */ + reserve(n: number): void; + /** + * Set number of buckets. + * + * Sets the number of buckets in the container to n or more. + * + * If n is greater than the current number of buckets in the container ({@link bucket_count}), a + * {@link HashBuckets.rehash rehash} is forced. The new {@link bucket_count bucket count} can either be equal or + * greater than n. + * + * If n is lower than the current number of buckets in the container ({@link bucket_count}), the + * function may have no effect on the {@link bucket_count bucket count} and may not force a + * {@link HashBuckets.rehash rehash}. + * + * A {@link HashBuckets.rehash rehash} is the reconstruction of the hash table: All the elements in the + * container are rearranged according to their hash value into the new set of buckets. This may alter the order + * of iteration of elements within the container. + * + * {@link HashBuckets.rehash Rehashes} are automatically performed by the container whenever its + * {@link load_factor load factor} is going to surpass its {@link max_load_factor} in an operation. + * + * Notice that this function expects the number of buckets as argument. A similar function exists, + * {@link reserve}, that expects the number of elements in the container as argument. + * + * @param n The minimum number of buckets for the container hash table. + */ + rehash(n: number): void; + } +} +declare namespace std.base { + /** + * An interface for linear containers. + * + * + * + * + * + * @author Jeonngho Nam + */ + interface ILinearContainer extends Container { + /** + * @inheritdoc + */ + assign>(begin: InputIterator, end: InputIterator): void; + /** + * Assign container content. + * + * Assigns new contents to the {@link IList container}, replacing its current contents, + * and modifying its {@link size} accordingly. + * + * @param n New size for the + * @param val Value to fill the container with. Each of the n elements in the container will + * be initialized to a copy of this value. + */ + assign(n: number, val: T): void; + /** + * Access first element. + * Returns a value of the first element in the {@link IList container}. + * + * Unlike member {@link end end()}, which returns an iterator just past this element, + * this function returns a direct value. + * + * Calling this function on an {@link empty} {@link IList container} causes undefined behavior. + * + * @return A value of the first element of the {@link IList container}. + */ + front(): T; + /** + * Access last element. + * Returns a value of the last element in the {@link IList container}. + * + * Unlike member {@link end end()}, which returns an iterator just past this element, + * this function returns a direct value. + * + * Calling this function on an {@link empty} {@link IList container} causes undefined behavior. + * + * @return A value of the last element of the {@link IList container}. + */ + back(): T; + /** + * Add element at the end. + * + * Adds a new element at the end of the {@link IList container}, after its current last element. + * This effectively increases the {@link IList container} {@link size} by one. + * + * @param val Value to be copied to the new element. + */ + push_back(val: T): void; + /** + * Delete last element. + * + * Removes the last element in the {@link IList container}, effectively reducing the + * {@link IList container} {@link size} by one. + */ + pop_back(): void; + /** + * Insert an element. + * + * The {@link IList conatiner} is extended by inserting new element before the element at the + * specified position, effectively increasing the {@link IList container} {@link size} by + * one. + * + * @param position Position in the {@link IList container} where the new elements are inserted. + * {@link iterator} is a member type, defined as a {@link iterator random access iterator} + * type that points to elements. + * @param val Value to be copied to the inserted element. + * + * @return An iterator that points to the newly inserted element. + */ + insert(position: Iterator, val: T): Iterator; + /** + * Insert elements by range iterators. + * + * The {@link IList container} is extended by inserting new elements before the element at the + * specified position, effectively increasing the {@link IList container} {@link size} by + * the number of repeating elements
n
. + * + * @param position Position in the {@link IList container} where the new elements are inserted. + * {@link iterator} is a member type, defined as a {@link iterator random access iterator} + * type that points to elements. + * @param n Number of elements to insert. Each element is initialized to a copy of val. + * @param val Value to be copied (or moved) to the inserted elements. + * + * @return An iterator that points to the first of the newly inserted elements. + */ + insert(position: Iterator, n: number, val: T): Iterator; + /** + * Insert elements by range iterators. + * + * The {@link IList container} is extended by inserting new elements before the element at the + * specified position, effectively increasing the {@link IList container} {@link size} by + * the number of elements inserted by range iterators. + * + * @param position Position in the {@link IList container} where the new elements are inserted. + * {@link iterator} is a member type, defined as a {@link iterator random access iterator} + * type that points to elements. + * @param begin Input interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. + * + * @return An iterator that points to the first of the newly inserted elements. + */ + insert>(position: Iterator, begin: InputIterator, end: InputIterator): Iterator; + } + /** + * An interface for iterators from linear containers. + * + * {@link ILieanerIterator} is an bi-directional iterator which is created from the related + * {@link ILinearContainer linear containers}. Not only accessing to {@link value} of the pointed element from + * this {@link ILieanerIterator}, but also modifying the {@link value} is possible. + * + * @author Jeongho Nam + */ + interface ILinearIterator extends Iterator { + /** + * @inheritdoc + */ + source(): ILinearContainer; + /** + * @inheritdoc + */ + value: T; + /** + * @inheritdoc + */ + prev(): ILinearIterator; + /** + * @inheritdoc + */ + next(): ILinearIterator; + } +} +declare namespace std.base { + /** + * Common interface for tree-structured map. + * + * {@link ITreeMap ITreeMaps} are associative containers that store elements formed by a combination of + * a key value and a mapped value, following a specific order. + * + * In a {@link ITreeMap}, the key values are generally used to sort and uniquely identify + * the elements, while the mapped values store the content associated to this key. The types of + * key and mapped value may differ, and are grouped together in member type + * value_type, which is a {@link Pair} type combining both: + * + * typedef Pair value_type; + * + * Internally, the elements in a {@link ITreeMap}are always sorted by its key following a + * strict weak ordering criterion indicated by its internal comparison method (of {@link less}). + * + * {@link ITreeMap}containers are generally slower than {@link IHashMap} containers + * to access individual elements by their key, but they allow the direct iteration on subsets based + * on their order. + * + * {@link ITreeMap TreeMultiMaps} are typically implemented as binary search trees. + * + * + * + * + * ### Container properties + *
+ *
Associative
+ *
Elements in associative containers are referenced by their key and not by their absolute + * position in the container.
+ * + *
Ordered
+ *
The elements in the container follow a strict order at all times. All inserted elements are + * given a position in this order.
+ * + *
Map
+ *
Each element associates a key to a mapped value: + * Keys are meant to identify the elements whose main content is the mapped value.
+ *
+ * + * @param Type of the keys. Each element in a map is uniquely identified by its key value. + * @param Type of the mapped value. Each element in a map stores some data as its mapped value. + * + * @reference http://www.cplusplus.com/reference/map + * @author Jeongho Nam + */ + interface ITreeMap extends MapContainer { + /** + * Return key comparison function. + * + * Returns a references of the comparison function used by the container to compare keys. + * + * The comparison object of a {@link ITreeMap tree-map object} is set on + * {@link TreeMap.constructor construction}. Its type (Key) is the last parameter of the + * {@link ITreeMap.constructor constructors}. By default, this is a {@link less} function, which returns the same + * as operator<. + * + * This function determines the order of the elements in the container: it is a function pointer that takes + * two arguments of the same type as the element keys, and returns true if the first argument + * is considered to go before the second in the strict weak ordering it defines, and false otherwise. + * + * + * Two keys are considered equivalent if {@link key_comp} returns false reflexively (i.e., no + * matter the order in which the keys are passed as arguments). + * + * @return The comparison function. + */ + key_comp(): (x: Key, y: Key) => boolean; + /** + * Return value comparison function. + * + * Returns a comparison function that can be used to compare two elements to get whether the key of the first + * one goes before the second. + * + * The arguments taken by this function object are of member type Pair (defined in + * {@link ITreeMap}), but the mapped type (T) part of the value is not taken into consideration in this + * comparison. + * + * This comparison class returns true if the {@link Pair.first key} of the first argument + * is considered to go before that of the second (according to the strict weak ordering specified by the + * container's comparison function, {@link key_comp}), and false otherwise. + * + * @return The comparison function for element values. + */ + value_comp(): (x: Pair, y: Pair) => boolean; + /** + * Return iterator to lower bound. + * + * Returns an iterator pointing to the first element in the container whose key is not considered to + * go before k (i.e., either it is equivalent or goes after). + * + * The function uses its internal comparison object (key_comp) to determine this, returning an + * iterator to the first element for which key_comp(k, element_key) would return false. + * + * If the {@link ITreeMap} class is instantiated with the default comparison type ({@link less}), + * the function returns an iterator to the first element whose key is not less than k. + * + * A similar member function, {@link upper_bound}, has the same behavior as {@link lower_bound}, except + * in the case that the {@link ITreeMap} contains an element with a key equivalent to k: In this + * case, {@link lower_bound} returns an iterator pointing to that element, whereas {@link upper_bound} + * returns an iterator pointing to the next element. + * + * @param k Key to search for. + * + * @return An iterator to the the first element in the container whose key is not considered to go before + * k, or {@link ITreeMap.end} if all keys are considered to go before k. + */ + lower_bound(key: Key): MapIterator; + /** + * Return iterator to upper bound. + * + * Returns an iterator pointing to the first element in the container whose key is considered to + * go after k. + * + * The function uses its internal comparison object (key_comp) to determine this, returning an + * iterator to the first element for which key_comp(k, element_key) would return true. + * + * If the {@link ITreeMap} class is instantiated with the default comparison type ({@link less}), + * the function returns an iterator to the first element whose key is greater than k. + * + * A similar member function, {@link lower_bound}, has the same behavior as {@link upper_bound}, except + * in the case that the map contains an element with a key equivalent to k: In this case + * {@link lower_bound} returns an iterator pointing to that element, whereas {@link upper_bound} returns an + * iterator pointing to the next element. + * + * @param k Key to search for. + * + * @return An iterator to the the first element in the container whose key is considered to go after + * k, or {@link TreeMap.end end} if no keys are considered to go after k. + */ + upper_bound(key: Key): MapIterator; + /** + * Get range of equal elements. + * + * Returns the bounds of a range that includes all the elements in the container which have a key + * equivalent to k. + * + * If no matches are found, the range returned has a length of zero, with both iterators pointing to + * the first element that has a key considered to go after k according to the container's internal + * comparison object (key_comp). + * + * Two keys are considered equivalent if the container's comparison object returns false reflexively + * (i.e., no matter the order in which the keys are passed as arguments). + * + * @param k Key to search for. + * + * @return The function returns a {@link Pair}, whose member {@link Pair.first} is the lower bound of + * the range (the same as {@link lower_bound}), and {@link Pair.second} is the upper bound + * (the same as {@link upper_bound}). + */ + equal_range(key: Key): Pair, MapIterator>; + } +} +declare namespace std.base { + /** + * A common interface for tree-structured set. + * + * {@link ITreeSet TreeMultiSets} are containers that store elements following a specific order. + * + * In a {@link ITreeSet}, the value of an element also identifies it (the value is itself + * the key, of type T). The value of the elements in a {@link ITreeSet} cannot + * be modified once in the container (the elements are always const), but they can be inserted or removed + * from the + * + * Internally, the elements in a {@link ITreeSet TreeMultiSets} are always sorted following a strict + * weak ordering criterion indicated by its internal comparison method (of {@link IComparable.less less}). + * + * {@link ITreeSet} containers are generally slower than {@link IHashSet} containers + * to access individual elements by their key, but they allow the direct iteration on subsets based on + * their order. + * + * {@link ITreeSet TreeMultiSets} are typically implemented as binary search trees. + * + * + * + * + * ### Container properties + *
+ *
Associative
+ *
+ * Elements in associative containers are referenced by their key and not by their absolute + * position in the container. + *
+ * + *
Ordered
+ *
+ * The elements in the container follow a strict order at all times. All inserted elements are + * given a position in this order. + *
+ * + *
Set
+ *
The value of an element is also the key used to identify it.
+ *
+ * + * @param Type of the elements. Each element in a {@link ITreeSet} container is also identified + * by this value (each value is itself also the element's key). + * + * @reference http://www.cplusplus.com/reference/set + * @author Jeongho Nam + */ + interface ITreeSet extends SetContainer { + /** + * Return comparison function. + * + * Returns a copy of the comparison function used by the container. + * + * By default, this is a {@link less} object, which returns the same as operator<. + * + * This object determines the order of the elements in the container: it is a function pointer or a function + * object that takes two arguments of the same type as the container elements, and returns true if + * the first argument is considered to go before the second in the strict weak ordering it + * defines, and false otherwise. + * + * Two elements of a {@link ITreeSet} are considered equivalent if {@link key_comp} returns false + * reflexively (i.e., no matter the order in which the elements are passed as arguments). + * + * In {@link ITreeSet} containers, the keys to sort the elements are the values (T) themselves, + * therefore {@link key_comp} and its sibling member function {@link value_comp} are equivalent. + * + * @return The comparison function. + */ + key_comp(): (x: T, y: T) => boolean; + /** + * Return comparison function. + * + * Returns a copy of the comparison function used by the container. + * + * By default, this is a {@link less} object, which returns the same as operator<. + * + * This object determines the order of the elements in the container: it is a function pointer or a function + * object that takes two arguments of the same type as the container elements, and returns true if + * the first argument is considered to go before the second in the strict weak ordering it + * defines, and false otherwise. + * + * Two elements of a {@link ITreeSet} are considered equivalent if {@link key_comp} returns false + * reflexively (i.e., no matter the order in which the elements are passed as arguments). + * + * In {@link ITreeSet} containers, the keys to sort the elements are the values (T) themselves, + * therefore {@link key_comp} and its sibling member function {@link value_comp} are equivalent. + * + * @return The comparison function. + */ + value_comp(): (x: T, y: T) => boolean; + /** + * Return iterator to lower bound. + * + * Returns an iterator pointing to the first element in the container which is not considered to + * go before val (i.e., either it is equivalent or goes after). + * + * The function uses its internal comparison object (key_comp) to determine this, returning an + * iterator to the first element for which key_comp(element,val) would return false. + * + * If the {@link ITreeSet} class is instantiated with the default comparison type ({@link less}), + * the function returns an iterator to the first element that is not less than val. + + * A similar member function, {@link upper_bound}, has the same behavior as {@link lower_bound}, except + * in the case that the {@link ITreeSet} contains elements equivalent to val: In this case + * {@link lower_bound} returns an iterator pointing to the first of such elements, whereas + * {@link upper_bound} returns an iterator pointing to the element following the last. + * + * @param val Value to compare. + * + * @return An iterator to the the first element in the container which is not considered to go before + * val, or {@link ITreeSet.end} if all elements are considered to go before val. + */ + lower_bound(val: T): SetIterator; + /** + * Return iterator to upper bound. + * + * Returns an iterator pointing to the first element in the container which is considered to go after + * val. + + * The function uses its internal comparison object (key_comp) to determine this, returning an + * iterator to the first element for which key_comp(val,element) would return true. + + * If the {@code ITreeSet} class is instantiated with the default comparison type (less), the + * function returns an iterator to the first element that is greater than val. + * + * A similar member function, {@link lower_bound}, has the same behavior as {@link upper_bound}, except + * in the case that the {@ITreeSet} contains elements equivalent to val: In this case + * {@link lower_bound} returns an iterator pointing to the first of such elements, whereas + * {@link upper_bound} returns an iterator pointing to the element following the last. + * + * @param val Value to compare. + * + * @return An iterator to the the first element in the container which is considered to go after + * val, or {@link TreeSet.end end} if no elements are considered to go after val. + */ + upper_bound(val: T): SetIterator; + /** + * Get range of equal elements. + * + * Returns the bounds of a range that includes all the elements in the container that are equivalent + * to val. + * + * If no matches are found, the range returned has a length of zero, with both iterators pointing to + * the first element that is considered to go after val according to the container's + * internal comparison object (key_comp). + * + * Two elements of a multiset are considered equivalent if the container's comparison object returns + * false reflexively (i.e., no matter the order in which the elements are passed as arguments). + * + * @param key Value to search for. + * + * @return The function returns a {@link Pair}, whose member {@link Pair.first} is the lower bound of + * the range (the same as {@link lower_bound}), and {@link Pair.second} is the upper bound + * (the same as {@link upper_bound}). + */ + equal_range(val: T): Pair, SetIterator>; + } +} +declare namespace std.base { + /** + * @hidden + */ + class _ArrayIterator extends Iterator { + private data_; + private index_; + constructor(data: Array, index: number); + source(): Container; + index(): number; + readonly value: T; + prev(): _ArrayIterator; + next(): _ArrayIterator; + advance(n: number): _ArrayIterator; + equals(obj: _ArrayIterator): boolean; + swap(obj: _ArrayIterator): void; + } +} +declare namespace std.base { + /** + * @hidden + */ + class _Repeater extends Iterator { + private index_; + private value_; + constructor(index: number, value?: T); + source(): base.Container; + index(): number; + readonly value: T; + prev(): _Repeater; + next(): _Repeater; + advance(n: number): _Repeater; + equals(obj: _Repeater): boolean; + swap(obj: _Repeater): void; + } +} +declare namespace std.base { + /** + * An abstract map. + * + * {@link MapContainer MapContainers} are associative containers that store elements formed by a combination + * of a key value (Key) and a mapped value (T), and which allows for fast retrieval + * of individual elements based on their keys. + * + * In a {@link MapContainer}, the key values are generally used to identify the elements, while the + * mapped values store the content associated to this key. The types of key and + * mapped value may differ, and are grouped together in member type value_type, which is a + * {@link Pair} type combining both: + * + * typedef pair value_type; + * + * {@link MapContainer} stores elements, keeps sequence and enables indexing by inserting elements into a + * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index + * table like {@link RBTree tree} or {@link HashBuckets hash-table}. + * + * + * + * + * ### Container properties + *
+ *
Associative
+ *
+ * Elements in associative containers are referenced by their key and not by their absolute position + * in the container. + *
+ * + *
Map
+ *
+ * Each element associates a key to a mapped value: + * Keys are meant to identify the elements whose main content is the mapped value. + *
+ *
+ * + * @param Type of the keys. Each element in a map is identified by its key value. + * @param Type of the mapped value. Each element in a map stores some data as its mapped value. + * + * @author Jeongho Nam + */ + abstract class MapContainer extends Container> { + /** + * @hidden + */ + private data_; + /** + * Default Constructor. + */ + protected constructor(); + /** + * @inheritdoc + */ + assign>>(first: InputIterator, last: InputIterator): void; + /** + * @inheritdoc + */ + clear(): void; + /** + * Get iterator to element. + * + * Searches the container for an element with a identifier equivalent to key and returns an + * iterator to it if found, otherwise it returns an iterator to {@link end end()}. + * + * Two keys are considered equivalent if the container's comparison object returns false reflexively + * (i.e., no matter the order in which the elements are passed as arguments). + * + * Another member functions, {@link has has()} and {@link count count()}, can be used to just check + * whether a particular key exists. + * + * @param key Key to be searched for + * @return An iterator to the element, if an element with specified key is found, or + * {@link end end()} otherwise. + */ + abstract find(key: Key): MapIterator; + /** + * Return iterator to beginning. + * + * Returns an iterator referring the first element in the + * + * #### Note + * If the container is {@link empty}, the returned iterator is same with {@link end end()}. + * + * @return An iterator to the first element in the The iterator containes the first element's value. + */ + begin(): MapIterator; + /** + * Return iterator to end. + * Returns an iterator referring to the past-the-end element in the + * + * The past-the-end element is the theoretical element that would follow the last element in the + * It does not point to any element, and thus shall not be dereferenced. + * + * Because the ranges used by functions of the container do not include the element reference by their + * closing iterator, this function is often used in combination with {@link MapContainer}.{@link begin} to + * specify a range including all the elements in the + * + * #### Note + * Returned iterator from {@link MapContainer}.{@link end} does not refer any element. Trying to accessing + * element by the iterator will cause throwing exception ({@link OutOfRange}). + * + * If the container is {@link empty}, this function returns the same as {@link begin}. + * + * @return An iterator to the end element in the + */ + end(): MapIterator; + /** + * Return {@link MapReverseIterator reverse iterator} to reverse beginning. + * + * Returns a {@link MapReverseIterator reverse iterator} pointing to the last element in the container + * (i.e., its reverse beginning). + * + * {@link MapReverseIterator Reverse iterators} iterate backwards: increasing them moves them towards the + * beginning of the container. + * + * {@link rbegin} points to the element preceding the one that would be pointed to by member {@link end}. + *7 + * + * @return A {@link MapReverseIterator reverse iterator} to the reverse beginning of the sequence + * + */ + rbegin(): MapReverseIterator; + /** + * Return {@link MapReverseIterator reverse iterator} to reverse end. + * + * Returns a {@link MapReverseIterator reverse iterator} pointing to the theoretical element right before + * the first element in the {@link MapContainer map container} (which is considered its reverse end). + * + * + * The range between {@link MapContainer}.{@link rbegin} and {@link MapContainer}.{@link rend} contains + * all the elements of the container (in reverse order). + * + * @return A {@link MapReverseIterator reverse iterator} to the reverse end of the sequence + */ + rend(): MapReverseIterator; + /** + * Whether have the item or not. + * + * Indicates whether a map has an item having the specified identifier. + * + * @param key Key value of the element whose mapped value is accessed. + * + * @return Whether the map has an item having the specified identifier. + */ + has(key: Key): boolean; + /** + * Count elements with a specific key. + * + * Searches the container for elements whose key is key and returns the number of elements found. + * + * @param key Key value to be searched for. + * + * @return The number of elements in the container with a key. + */ + abstract count(key: Key): number; + /** + * Return the number of elements in the map. + */ + size(): number; + /** + * @inheritdoc + */ + push(...args: Pair[]): number; + /** + * @inheritdoc + */ + push(...args: [Key, T][]): number; + /** + * Construct and insert element with hint + * + * Inserts a new element in the {@link MapContainer map container}. This new element is constructed in + * place using *args* as the arguments for the element's constructor. *hint* points to a location in the + * container suggested as a hint on where to start the search for its insertion point (the container may or + * may not use this suggestion to optimize the insertion operation). + * + * A similar member function exists, {@link insert}, which either copies or moves an existing object into + * the container, and may also take a position *hint*. + * + * @param hint Hint for the position where the element can be inserted. + * @param key The key used both to look up and to insert if not found. + * @param value Value, the item. + * + * @return An iterator pointing to either the newly inserted element or to the element that already had an + * equivalent key in the {@link MapContainer}. + */ + emplace_hint(hint: MapIterator, key: Key, val: T): MapIterator; + /** + * Construct and insert element with hint + * + * Inserts a new element in the {@link MapContainer map container}. This new element is constructed in + * place using *args* as the arguments for the element's constructor. *hint* points to a location in the + * container suggested as a hint on where to start the search for its insertion point (the container may or + * may not use this suggestion to optimize the insertion operation). + * + * A similar member function exists, {@link insert}, which either copies or moves an existing object into + * the container, and may also take a position *hint*. + * + * @param hint Hint for the position where the element can be inserted. + * @param key The key used both to look up and to insert if not found. + * @param value Value, the item. + * + * @return An {@link MapIterator iterator} pointing to either the newly inserted element or to the element + * that already had an equivalent key in the {@link MapContainer}. + */ + emplace_hint(hint: MapReverseIterator, key: Key, val: T): MapReverseIterator; + /** + * Construct and insert element with hint + * + * Inserts a new element in the {@link MapContainer map container}. This new element is constructed in + * place using *args* as the arguments for the element's constructor. *hint* points to a location in the + * container suggested as a hint on where to start the search for its insertion point (the container may or + * may not use this suggestion to optimize the insertion operation). + * + * A similar member function exists, {@link insert}, which either copies or moves an existing object into + * the container, and may also take a position *hint*. + * + * @param hint Hint for the position where the element can be inserted. + * @param pair A single argument of a {@link Pair} type with a value for the *key* as + * {@link Pair.first first} member, and a *value* for the mapped value as + * {@link Pair.second second}. + * + * @return An iterator pointing to either the newly inserted element or to the element that already had an + * equivalent key in the {@link MapContainer}. + */ + emplace_hint(hint: MapIterator, pair: Pair): MapIterator; + /** + * Construct and insert element with hint + * + * Inserts a new element in the {@link MapContainer map container}. This new element is constructed in + * place using *args* as the arguments for the element's constructor. *hint* points to a location in the + * container suggested as a hint on where to start the search for its insertion point (the container may or + * may not use this suggestion to optimize the insertion operation). + * + * A similar member function exists, {@link insert}, which either copies or moves an existing object into + * the container, and may also take a position *hint*. + * + * @param hint Hint for the position where the element can be inserted. + * @param pair A single argument of a {@link Pair} type with a value for the *key* as + * {@link Pair.first first} member, and a *value* for the mapped value as + * {@link Pair.second second}. + * + * @return An {@link MapIterator iterator} pointing to either the newly inserted element or to the element + * that already had an equivalent key in the {@link MapContainer}. + */ + emplace_hint(hint: MapReverseIterator, pair: Pair): MapReverseIterator; + /** + * Insert an element. + * + * Extends the container by inserting a new element, effectively increasing the container {@link size} + * by the number of element inserted (zero or one). + * + * @param hint Hint for the position where the element can be inserted. + * @param pair A single argument of a {@link Pair} type with a value for the *key* as + * {@link Pair.first first} member, and a *value* for the mapped value as + * {@link Pair.second second}. + * + * @return An iterator pointing to either the newly inserted element or to the element that already had an + * equivalent key in the {@link MapContainer}. + */ + insert(hint: MapIterator, pair: Pair): MapIterator; + /** + * Insert an element. + * + * Extends the container by inserting a new element, effectively increasing the container {@link size} + * by the number of element inserted (zero or one). + * + * @param hint Hint for the position where the element can be inserted. + * @param pair A single argument of a {@link Pair} type with a value for the *key* as + * {@link Pair.first first} member, and a *value* for the mapped value as + * {@link Pair.second second}. + * + * @return An iterator pointing to either the newly inserted element or to the element that already had an + * equivalent key in the {@link MapContainer}. + */ + insert(hint: MapReverseIterator, pair: Pair): MapReverseIterator; + /** + * Insert an element. + * + * Extends the container by inserting new elements, effectively increasing the container {@link size} + * by the number of elements inserted. + * + * @param hint Hint for the position where the element can be inserted. + * @param tuple Tuple represensts the {@link Pair} to be inserted as an element. + * + * @return An iterator pointing to either the newly inserted element or to the element that already had an + * equivalent key in the {@link MapContainer}. + */ + insert(hint: MapIterator, tuple: [L, U]): MapIterator; + /** + * Insert an element. + * + * Extends the container by inserting new elements, effectively increasing the container {@link size} + * by the number of elements inserted. + * + * @param hint Hint for the position where the element can be inserted. + * @param tuple Tuple represensts the {@link Pair} to be inserted as an element. + * + * @return An iterator pointing to either the newly inserted element or to the element that already had an + * equivalent key in the {@link MapContainer}. + */ + insert(hint: MapReverseIterator, tuple: [L, U]): MapReverseIterator; + /** + * Insert elements from range iterators. + * + * Extends the container by inserting new elements, effectively increasing the container {@link size} by + * the number of elements inserted. + * + * @param begin Input iterator specifying initial position of a range of elements. + * @param end Input iterator specifying final position of a range of elements. + * Notice that the range includes all the elements between begin and end, + * including the element pointed by begin but not the one pointed by end. + */ + insert>>(first: InputIterator, last: InputIterator): void; + /** + * @hidden + */ + protected abstract _Insert_by_pair(pair: Pair): any; + /** + * @hidden + */ + private _Insert_by_tuple(tuple); + /** + * @hidden + */ + protected abstract _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; + /** + * @hidden + */ + private _Insert_by_hint_with_tuple(hint, tuple); + /** + * @hidden + */ + protected abstract _Insert_by_range>>(first: InputIterator, last: InputIterator): void; + /** + * Erase an elemet by key. + * + * Removes from the {@link MapContainer map container} a single element. + * + * This effectively reduces the container {@link size} by the number of element removed (zero or one), + * which are destroyed. + * + * @param key Key of the element to be removed from the {@link MapContainer}. + */ + erase(key: Key): number; + /** + * Erase an elemet by iterator. + * + * Removes from the {@link MapContainer map container} a single element. + * + * This effectively reduces the container {@link size} by the number of element removed (zero or one), + * which are destroyed. + * + * @param it Iterator specifying position winthin the {@link MapContainer map contaier} to be removed. + */ + erase(it: MapIterator): MapIterator; + /** + * Erase elements by range iterators. + * + * Removes from the {@link MapContainer map container} a range of elements. + * + * This effectively reduces the container {@link size} by the number of elements removed, which are + * destroyed. + * + * @param begin An iterator specifying initial position of a range within {@link MApContainer map container} + * to be removed. + * @param end An iterator specifying initial position of a range within {@link MApContainer map container} + * to be removed. + * Notice that the range includes all the elements between begin and end, + * including the element pointed by begin but not the one pointed by end. + */ + erase(begin: MapIterator, end: MapIterator): MapIterator; + /** + * Erase an elemet by iterator. + * + * Removes from the {@link MapContainer map container} a single element. + * + * This effectively reduces the container {@link size} by the number of element removed (zero or one), + * which are destroyed. + * + * @param it Iterator specifying position winthin the {@link MapContainer map contaier} to be removed. + */ + erase(it: MapReverseIterator): MapReverseIterator; + /** + * Erase elements by range iterators. + * + * Removes from the {@link MapContainer map container} a range of elements. + * + * This effectively reduces the container {@link size} by the number of elements removed, which are + * destroyed. + * + * @param begin An iterator specifying initial position of a range within {@link MApContainer map container} + * to be removed. + * @param end An iterator specifying initial position of a range within {@link MApContainer map container} + * to be removed. + * Notice that the range includes all the elements between begin and end, + * including the element pointed by begin but not the one pointed by end. + */ + erase(begin: MapReverseIterator, end: MapReverseIterator): MapReverseIterator; + /** + * @hidden + */ + private _Erase_by_key(key); + /** + * @hidden + */ + private _Erase_by_iterator(first, last?); + /** + * @hidden + */ + private _Erase_by_range(first, last); + /** + * @hidden + */ + protected _Swap(obj: MapContainer): void; + /** + * Merge two maps. + * + * Extracts and transfers elements from *source* to this container. + * + * @param source A {@link MapContainer map container} to transfer the elements from. + */ + abstract merge(source: MapContainer): void; + /** + * @hidden + */ + protected abstract _Handle_insert(first: MapIterator, last: MapIterator): void; + /** + * @hidden + */ + protected abstract _Handle_erase(first: MapIterator, last: MapIterator): void; + } + /** + * @hidden + */ + class _MapElementList extends _ListContainer, MapIterator> { + private associative_; + private rend_; + constructor(associative: MapContainer); + protected _Create_iterator(prev: MapIterator, next: MapIterator, val: Pair): MapIterator; + protected _Set_begin(it: MapIterator): void; + associative(): MapContainer; + rbegin(): MapReverseIterator; + rend(): MapReverseIterator; + } +} +declare namespace std { + /** + * An iterator of {@link MapContainer map container}. + * + * + * + * + * @author Jeongho Nam + */ + class MapIterator extends base._ListIteratorBase> implements IComparable> { + /** + * Construct from the {@link MapContainer source map} and {@link ListIterator list iterator}. + * + * @param source The source {@link MapContainer}. + * @param list_iterator A {@link ListIterator} pointing {@link Pair} of key and value. + */ + constructor(source: base._MapElementList, prev: MapIterator, next: MapIterator, val: Pair); + /** + * Get iterator to previous element. + */ + prev(): MapIterator; + /** + * Get iterator to next element. + */ + next(): MapIterator; + /** + * Advances the Iterator by n element positions. + * + * @param step Number of element positions to advance. + * @return An advanced Iterator. + */ + advance(step: number): MapIterator; + /** + * @hidden + */ + source(): base.MapContainer; + /** + * Get first, key element. + */ + readonly first: Key; + /** + * Get second, value element. + */ + /** + * Set second value. + */ + second: T; + /** + * @inheritdoc + */ + less(obj: MapIterator): boolean; + /** + * @inheritdoc + */ + equals(obj: MapIterator): boolean; + /** + * @inheritdoc + */ + hashCode(): number; + /** + * @inheritdoc + */ + swap(obj: MapIterator): void; + } + /** + * A reverse-iterator of {@link MapContainer map container}. + * + * + * + * + * @author Jeongho Nam + */ + class MapReverseIterator extends ReverseIterator, base.MapContainer, MapIterator, MapReverseIterator> { + /** + * Construct from base iterator. + * + * @param base A reference of the base iterator, which iterates in the opposite direction. + */ + constructor(base: MapIterator); + /** + * @hidden + */ + protected _Create_neighbor(base: MapIterator): MapReverseIterator; + /** + * Get first, key element. + */ + readonly first: Key; + /** + * Get second, value element. + */ + /** + * Set second value. + */ + second: T; + } +} +declare namespace std.base { + /** + * An abstract multi-map. + * + * {@link MultiMap MultiMaps} are associative containers that store elements formed by a combination of a + * key value (Key) and a mapped value (T), and which allows for fast retrieval of + * individual elements based on their keys. + * + * In a {@link MapContainer}, the key values are generally used to identify the elements, while the + * mapped values store the content associated to this key. The types of key and + * mapped value may differ, and are grouped together in member type value_type, which is a + * {@link Pair} type combining both: + * + * typedef pair value_type; + * + * {@link UniqueMap} stores elements, keeps sequence and enables indexing by inserting elements into a + * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index + * table like {@link RBTree tree} or {@link HashBuckets hash-table}. + * + * + * + * + * ### Container properties + *
+ *
Associative
+ *
+ * Elements in associative containers are referenced by their key and not by their absolute position + * in the container. + *
+ * + *
Map
+ *
+ * Each element associates a key to a mapped value: + * Keys are meant to identify the elements whose main content is the mapped value. + *
+ * + *
Multiple equivalent keys
+ *
Multiple elements in the container can have equivalent keys.
+ *
+ * + * @param Type of the keys. Each element in a map is identified by its key value. + * @param Type of the mapped value. Each element in a map stores some data as its mapped value. + * + * @author Jeongho Nam + */ + abstract class MultiMap extends MapContainer { + /** + * Construct and insert element. + * + * Inserts a new element in the {@link MultiMap}. This new element is constructed in place using args + * as the arguments for the element's constructor. + * + * This effectively increases the container {@link size} by one. + * + * A similar member function exists, {@link insert}, which either copies or moves existing objects into the + * container. + * + * @param key The key used both to look up and to insert if not found. + * @param value Value, the item. + * + * @return An {@link MapIterator iterator} to the newly inserted element. + */ + emplace(key: Key, value: T): MapIterator; + /** + * Construct and insert element. + * + * Inserts a new element in the {@link MultiMap}. This new element is constructed in place using args + * as the arguments for the element's constructor. + * + * This effectively increases the container {@link size} by one. + * + * A similar member function exists, {@link insert}, which either copies or moves existing objects into the + * container. + * + * @param pair A single argument of a {@link Pair} type with a value for the *key* as + * {@link Pair.first first} member, and a *value* for the mapped value as + * {@link Pair.second second}. + * @return An {@link MapIterator iterator} to the newly inserted element. + */ + emplace(pair: Pair): MapIterator; + /** + * Insert elements. + * + * Extends the container by inserting new elements, effectively increasing the container {@link size} by + * the number of elements inserted. + * + * @param pair A single argument of a {@link Pair} type with a value for the *key* as + * {@link Pair.first first} member, and a *value* for the mapped value as + * {@link Pair.second second}. + * + * @return An iterator pointing to the newly inserted element. + */ + insert(pair: Pair): MapIterator; + /** + * Insert elements. + * + * Extends the container by inserting new elements, effectively increasing the container {@link size} by + * the number of elements inserted. + * + * @param tuple Tuple represensts the {@link Pair} to be inserted as an element. + * + * @return An iterator pointing to the newly inserted element. + */ + insert(tuple: [L, U]): MapIterator; + /** + * @inheritdoc + */ + insert(hint: MapIterator, pair: Pair): MapIterator; + /** + * @inheritdoc + */ + insert(hint: MapReverseIterator, pair: Pair): MapReverseIterator; + /** + * @inheritdoc + */ + insert(hint: MapIterator, tuple: [L, U]): MapIterator; + /** + * @inheritdoc + */ + insert(hint: MapReverseIterator, tuple: [L, U]): MapReverseIterator; + /** + * @inheritdoc + */ + insert>>(first: InputIterator, last: InputIterator): void; + /** + * @inheritdoc + */ + merge(source: MapContainer): void; + } +} +declare namespace std.base { + /** + * An abstract set. + * + * {@link SetContainer SetContainers} are containers that store elements allowing fast retrieval of + * individual elements based on their value. + * + * In an {@link SetContainer}, the value of an element is at the same time its key, used to + * identify it. Keys are immutable, therefore, the elements in an {@link SetContainer} cannot be + * modified once in the container - they can be inserted and removed, though. + * + * {@link SetContainer} stores elements, keeps sequence and enables indexing by inserting elements into a + * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index + * table like {@link RBTree tree} or {@link HashBuckets hash-table}. + * + * + * + * + * ### Container properties + *
+ *
Associative
+ *
+ * Elements in associative containers are referenced by their key and not by their absolute + * position in the container. + *
+ * + *
Set
+ *
The value of an element is also the key used to identify it.
+ *
+ * + * @param Type of the elements. Each element in a {@link SetContainer} container is also identified + * by this value (each value is itself also the element's key). + * + * @author Jeongho Nam + */ + abstract class SetContainer extends Container { + /** + * {@link List} storing elements. + * + * Storing elements and keeping those sequence of the {@link SetContainer} are implemented by + * {@link data_ this list container}. Implementing index-table is also related with {@link data_ this list} + * by storing {@link ListIterator iterators} ({@link SetIterator} references {@link ListIterator}) who are + * created from {@link data_ here}. + */ + private data_; + /** + * Default Constructor. + */ + protected constructor(); + /** + * @inheritdoc + */ + assign>(begin: Iterator, end: Iterator): void; + /** + * @inheritdoc + */ + clear(): void; + /** + * Get iterator to element. + * + * Searches the container for an element with key as value and returns an iterator to it if found, + * otherwise it returns an iterator to {@link end end()} (the element past the end of the container). + * + * Another member function, {@link count count()}, can be used to just check whether a particular element + * exists. + * + * @param key Key to be searched for. + * + * @return An iterator to the element, if the specified value is found, or {@link end end()} if it is not + * found in the + */ + abstract find(val: T): SetIterator; + /** + * @inheritdoc + */ + begin(): SetIterator; + /** + * @inheritdoc + */ + end(): SetIterator; + /** + * @inheritdoc + */ + rbegin(): SetReverseIterator; + /** + * @inheritdoc + */ + rend(): SetReverseIterator; + /** + * Whether have the item or not. + * + * Indicates whether a set has an item having the specified identifier. + * + * @param key Key value of the element whose mapped value is accessed. + * + * @return Whether the set has an item having the specified identifier. + */ + has(val: T): boolean; + /** + * Count elements with a specific key. + * + * Searches the container for elements with a value of k and returns the number of elements found. + * + * @param key Value of the elements to be counted. + * + * @return The number of elements in the container with a key. + */ + abstract count(val: T): number; + /** + * @inheritdoc + */ + size(): number; + /** + * @inheritdoc + */ + push(...items: T[]): number; + /** + * Insert an element with hint. + * + * Extends the container by inserting new elements, effectively increasing the container size by the + * number of elements inserted. + * + * @param hint Hint for the position where the element can be inserted. + * @param val Value to be inserted as an element. + * + * @return An iterator pointing to either the newly inserted element or to the element that already had its + * same value in the {@link SetContainer}. + */ + insert(hint: SetIterator, val: T): SetIterator; + /** + * Insert an element with hint. + * + * Extends the container by inserting new elements, effectively increasing the container size by the + * number of elements inserted. + * + * @param hint Hint for the position where the element can be inserted. + * @param val Value to be inserted as an element. + * + * @return An iterator pointing to either the newly inserted element or to the element that already had its + * same value in the {@link SetContainer}. + */ + insert(hint: SetReverseIterator, val: T): SetReverseIterator; + /** + * Insert elements with a range of a + * + * Extends the container by inserting new elements, effectively increasing the container size by the + * number of elements inserted. + * + * @param begin An iterator specifying range of the begining element. + * @param end An iterator specifying range of the ending element. + */ + insert>(begin: InputIterator, end: InputIterator): void; + /** + * @hidden + */ + protected abstract _Insert_by_val(val: T): any; + /** + * @hidden + */ + protected abstract _Insert_by_hint(hint: SetIterator, val: T): SetIterator; + /** + * @hidden + */ + protected abstract _Insert_by_range>(begin: InputIterator, end: InputIterator): void; + /** + * Erase an element. + * Removes from the set container the elements whose value is key. + * + * This effectively reduces the container size by the number of elements removed. + * + * @param key Value of the elements to be erased. + * + * @return Number of elements erased. + */ + erase(val: T): number; + /** + * @inheritdoc + */ + erase(it: SetIterator): SetIterator; + /** + * Erase elements. + * Removes from the set container a range of elements.. + * + * This effectively reduces the container size by the number of elements removed. + * + * @param begin An iterator specifying a range of beginning to erase. + * @param end An iterator specifying a range of end to erase. + */ + erase(begin: SetIterator, end: SetIterator): SetIterator; + /** + * @inheritdoc + */ + erase(it: SetReverseIterator): SetReverseIterator; + /** + * Erase elements. + * Removes from the set container a range of elements.. + * + * This effectively reduces the container size by the number of elements removed. + * + * @param begin An iterator specifying a range of beginning to erase. + * @param end An iterator specifying a range of end to erase. + */ + erase(begin: SetReverseIterator, end: SetReverseIterator): SetReverseIterator; + /** + * @hidden + */ + private _Erase_by_iterator(first, last?); + /** + * @hidden + */ + private _Erase_by_val(val); + /** + * @hidden + */ + private _Erase_by_range(first, last); + /** + * @hidden + */ + protected _Swap(obj: SetContainer): void; + /** + * Merge two sets. + * + * Extracts and transfers elements from *source* to this container. + * + * @param source A {@link SetContainer set container} to transfer the elements from. + */ + abstract merge(source: SetContainer): void; + /** + * @hidden + */ + protected abstract _Handle_insert(first: SetIterator, last: SetIterator): void; + /** + * @hidden + */ + protected abstract _Handle_erase(first: SetIterator, last: SetIterator): void; + } + /** + * @hidden + */ + class _SetElementList extends _ListContainer> { + private associative_; + private rend_; + constructor(associative: SetContainer); + protected _Create_iterator(prev: SetIterator, next: SetIterator, val: T): SetIterator; + protected _Set_begin(it: SetIterator): void; + associative(): SetContainer; + rbegin(): SetReverseIterator; + rend(): SetReverseIterator; + } +} +declare namespace std { + /** + * An iterator of a Set. + * + * + * + * + * @author Jeongho Nam + */ + class SetIterator extends base._ListIteratorBase implements IComparable> { + /** + * Construct from source and index number. + * + * #### Note + * Do not create iterator directly. + * + * Use begin(), find() or end() in Map instead. + * + * @param map The source Set to reference. + * @param index Sequence number of the element in the source Set. + */ + constructor(source: base._SetElementList, prev: SetIterator, next: SetIterator, val: T); + /** + * @inheritdoc + */ + source(): base.SetContainer; + /** + * @inheritdoc + */ + prev(): SetIterator; + /** + * @inheritdoc + */ + next(): SetIterator; + /** + * @inheritdoc + */ + advance(size: number): SetIterator; + /** + * @inheritdoc + */ + less(obj: SetIterator): boolean; + /** + * @inheritdoc + */ + equals(obj: SetIterator): boolean; + /** + * @inheritdoc + */ + hashCode(): number; + /** + * @inheritdoc + */ + swap(obj: SetIterator): void; + } + /** + * A reverse-iterator of Set. + * + * + * + * + * @param Type of the elements. + * + * @author Jeongho Nam + */ + class SetReverseIterator extends ReverseIterator, SetIterator, SetReverseIterator> { + /** + * Construct from base iterator. + * + * @param base A reference of the base iterator, which iterates in the opposite direction. + */ + constructor(base: SetIterator); + /** + * @hidden + */ + protected _Create_neighbor(base: SetIterator): SetReverseIterator; + } +} +declare namespace std.base { + /** + * An abstract set. + * + * {@link SetContainer SetContainers} are containers that store elements allowing fast retrieval of + * individual elements based on their value. + * + * In an {@link SetContainer}, the value of an element is at the same time its key, used to + * identify it. Keys are immutable, therefore, the elements in an {@link SetContainer} cannot be + * modified once in the container - they can be inserted and removed, though. + * + * {@link SetContainer} stores elements, keeps sequence and enables indexing by inserting elements into a + * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index + * table like {@link RBTree tree} or {@link HashBuckets hash-table}. + * + * + * + * + * ### Container properties + *
+ *
Associative
+ *
+ * Elements in associative containers are referenced by their key and not by their absolute + * position in the container. + *
+ * + *
Set
+ *
The value of an element is also the key used to identify it.
+ * + *
Multiple equivalent keys
+ *
Multiple elements in the container can have equivalent keys.
+ *
+ * + * @param Type of the elements. Each element in a {@link SetContainer} container is also identified + * by this value (each value is itself also the element's key). + * + * @author Jeongho Nam + */ + abstract class MultiSet extends SetContainer { + /** + * Insert an element. + * + * Extends the container by inserting new elements, effectively increasing the container {@link size} by + * the number of elements inserted. + * + * @param key Value to be inserted as an element. + * + * @return An iterator to the newly inserted element. + */ + insert(val: T): SetIterator; + /** + * @inheritdoc + */ + insert(hint: SetIterator, val: T): SetIterator; + /** + * @inheritdoc + */ + insert(hint: SetReverseIterator, val: T): SetReverseIterator; + /** + * @inheritdoc + */ + insert>(begin: InputIterator, end: InputIterator): void; + /** + * @inheritdoc + */ + merge(source: SetContainer): void; + } +} +declare namespace std.base { + /** + * @hidden + */ + enum _Color { + BLACK = 0, + RED = 1, + } +} +declare namespace std.base { + /** + * @hidden + */ + abstract class _XTree { + protected root_: _XTreeNode; + protected constructor(); + clear(): void; + find(val: T): _XTreeNode; + protected _Fetch_maximum(node: _XTreeNode): _XTreeNode; + abstract is_less(left: T, right: T): boolean; + abstract is_equal_to(left: T, right: T): boolean; + insert(val: T): void; + private _Insert_case1(N); + private _Insert_case2(N); + private _Insert_case3(N); + private _Insert_case4(node); + private _Insert_case5(node); + erase(val: T): void; + private _Erase_case1(N); + private _Erase_case2(N); + private _Erase_case3(N); + private _Erase_case4(N); + private _Erase_case5(N); + private _Erase_case6(node); + protected _Rotate_left(node: _XTreeNode): void; + protected _Rotate_right(node: _XTreeNode): void; + protected _Replace_node(oldNode: _XTreeNode, newNode: _XTreeNode): void; + private _Fetch_color(node); + } +} +declare namespace std.base { + /** + * @hidden + */ + class _MapTree extends _XTree> { + private map_; + private compare_; + constructor(map: ITreeMap, compare?: (x: Key, y: Key) => boolean); + find(key: Key): _XTreeNode>; + find(it: MapIterator): _XTreeNode>; + private _Find_by_key(key); + lower_bound(key: Key): MapIterator; + upper_bound(key: Key): MapIterator; + equal_range(key: Key): Pair, MapIterator>; + key_comp(): (x: Key, y: Key) => boolean; + value_comp(): (x: Pair, y: Pair) => boolean; + is_equal_to(left: MapIterator, right: MapIterator): boolean; + is_less(left: MapIterator, right: MapIterator): boolean; + } +} +declare namespace std.base { + /** + * @hidden + */ + class _SetTree extends _XTree> { + private set_; + private compare_; + /** + * Default Constructor. + */ + constructor(set: ITreeSet, compare?: (x: T, y: T) => boolean); + find(val: T): _XTreeNode>; + find(it: SetIterator): _XTreeNode>; + private _Find_by_val(val); + lower_bound(val: T): SetIterator; + upper_bound(val: T): SetIterator; + equal_range(val: T): Pair, SetIterator>; + key_comp(): (x: T, y: T) => boolean; + value_comp(): (x: T, y: T) => boolean; + is_equal_to(left: SetIterator, right: SetIterator): boolean; + is_less(left: SetIterator, right: SetIterator): boolean; + } +} +declare namespace std.base { + /** + * @hidden + */ + class _XTreeNode { + parent: _XTreeNode; + left: _XTreeNode; + right: _XTreeNode; + value: T; + color: _Color; + constructor(value: T, color: _Color); + readonly grandParent: _XTreeNode; + readonly sibling: _XTreeNode; + readonly uncle: _XTreeNode; + } +} +declare namespace std.base { + /** + * An abstract unique-map. + * + * {@link UniqueMap UniqueMaps} are associative containers that store elements formed by a combination of a + * key value (Key) and a mapped value (T), and which allows for fast retrieval of + * individual elements based on their keys. + * + * In a {@link MapContainer}, the key values are generally used to uniquely identify the elements, + * while the mapped values store the content associated to this key. The types of key and + * mapped value may differ, and are grouped together in member type value_type, which is a + * {@link Pair} type combining both: + * + * typedef pair value_type; + * + * {@link UniqueMap} stores elements, keeps sequence and enables indexing by inserting elements into a + * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index + * table like {@link RBTree tree} or {@link HashBuckets hash-table}. + * + * + * + * + * ### Container properties + *
+ *
Associative
+ *
+ * Elements in associative containers are referenced by their key and not by their absolute position + * in the container. + *
+ * + *
Map
+ *
+ * Each element associates a key to a mapped value: + * Keys are meant to identify the elements whose main content is the mapped value. + *
+ * + *
Unique keys
+ *
No two elements in the container can have equivalent keys.
+ *
+ * + * @param Type of the keys. Each element in a map is uniquely identified by its key value. + * @param Type of the mapped value. Each element in a map stores some data as its mapped value. + * + * @author Jeongho Nam + */ + abstract class UniqueMap extends MapContainer { + /** + * @inheritdoc + */ + count(key: Key): number; + /** + * Get an element + * + * Returns a reference to the mapped value of the element identified with key. + * + * @param key Key value of the element whose mapped value is accessed. + * + * @throw exception out of range + * + * @return A reference object of the mapped value (_Ty) + */ + get(key: Key): T; + /** + * Set an item as the specified identifier. + * + * If the identifier is already in map, change value of the identifier. If not, then insert the object + * with the identifier. + * + * @param key Key value of the element whose mapped value is accessed. + * @param val Value, the item. + */ + set(key: Key, val: T): void; + /** + * Construct and insert element. + * + * Inserts a new element in the {@link UniqueMap} if its *key* is unique. This new element is constructed in + * place using args as the arguments for the construction of a *value_type* (which is an object of a + * {@link Pair} type). + * + * The insertion only takes place if no other element in the container has a *key equivalent* to the one + * being emplaced (*keys* in a {@link UniqueMap} container are unique). + * + * If inserted, this effectively increases the container {@link size} by one. + * + * A similar member function exists, {@link insert}, which either copies or moves existing objects into the + * container. + * + * @param key The key used both to look up and to insert if not found. + * @param value Value, the item. + * + * @return If the function successfully inserts the element (because no equivalent element existed already in + * the {@link UniqueMap}), the function returns a {@link Pair} of an {@link MapIterator iterator} to + * the newly inserted element and a value of true. Otherwise, it returns an + * {@link MapIterator iterator} to the equivalent element within the container and a value of false. + */ + emplace(key: Key, value: T): Pair, boolean>; + /** + * Construct and insert element. + * + * Inserts a new element in the {@link UniqueMap} if its *key* is unique. This new element is constructed in + * place using args as the arguments for the construction of a *value_type* (which is an object of a + * {@link Pair} type). + * + * The insertion only takes place if no other element in the container has a *key equivalent* to the one + * being emplaced (*keys* in a {@link UniqueMap} container are unique). + * + * If inserted, this effectively increases the container {@link size} by one. + * + * A similar member function exists, {@link insert}, which either copies or moves existing objects into the + * container. + * + * @param pair A single argument of a {@link Pair} type with a value for the *key* as + * {@link Pair.first first} member, and a *value* for the mapped value as + * {@link Pair.second second}. + * + * @return If the function successfully inserts the element (because no equivalent element existed already in + * the {@link UniqueMap}), the function returns a {@link Pair} of an {@link MapIterator iterator} to + * the newly inserted element and a value of true. Otherwise, it returns an + * {@link MapIterator iterator} to the equivalent element within the container and a value of false. + */ + emplace(pair: Pair): Pair, boolean>; + /** + * Insert an element. + * + * Extends the container by inserting new elements, effectively increasing the container {@link size} by + * one. + * + * Because element keys in a {@link UniqueMap} are unique, the insertion operation checks whether + * each inserted element has a key equivalent to the one of an element already in the container, and + * if so, the element is not inserted, returning an iterator to this existing element (if the function + * returns a value). + * + * For a similar container allowing for duplicate elements, see {@link MultiMap}. + * + * @param pair A single argument of a {@link Pair} type with a value for the *key* as + * {@link Pair.first first} member, and a *value* for the mapped value as + * {@link Pair.second second}. + * + * @return A {@link Pair}, with its member {@link Pair.first} set to an iterator pointing to either the newly + * inserted element or to the element with an equivalent key in the {@link UniqueMap}. The + * {@link Pair.second} element in the {@link Pair} is set to true if a new element was inserted or + * false if an equivalent key already existed. + */ + insert(pair: Pair): Pair, boolean>; + /** + * Insert an element. + * + * Extends the container by inserting a new element, effectively increasing the container size by the + * number of elements inserted. + * + * Because element keys in a {@link UniqueMap} are unique, the insertion operation checks whether + * each inserted element has a key equivalent to the one of an element already in the container, and + * if so, the element is not inserted, returning an iterator to this existing element (if the function + * returns a value). + * + * For a similar container allowing for duplicate elements, see {@link MultiMap}. + * + * @param tuple Tuple represensts the {@link Pair} to be inserted as an element. + * + * @return A {@link Pair}, with its member {@link Pair.first} set to an iterator pointing to either the newly + * inserted element or to the element with an equivalent key in the {@link UniqueMap}. The + * {@link Pair.second} element in the {@link Pair} is set to true if a new element was inserted or + * false if an equivalent key already existed. + */ + insert(tuple: [L, U]): Pair, boolean>; + /** + * @inheritdoc + */ + insert(hint: MapIterator, pair: Pair): MapIterator; + /** + * @inheritdoc + */ + insert(hint: MapReverseIterator, pair: Pair): MapReverseIterator; + /** + * @inheritdoc + */ + insert(hint: MapIterator, tuple: [L, U]): MapIterator; + /** + * @inheritdoc + */ + insert(hint: MapReverseIterator, tuple: [L, U]): MapReverseIterator; + /** + * @inheritdoc + */ + insert>>(first: InputIterator, last: InputIterator): void; + /** + * Insert or assign an element. + * + * Inserts an element or assigns to the current element if the key already exists. + * + * Because element keys in a {@link UniqueMap} are unique, the insertion operation checks whether + * each inserted element has a key equivalent to the one of an element already in the container, and + * if so, the element is assigned, returning an iterator to this existing element (if the function returns a + * value). + * + * For a similar container allowing for duplicate elements, see {@link MultiMap}. + * + * @param key The key used both to look up and to insert if not found. + * @param value Value, the item. + * + * @return A {@link Pair}, with its member {@link Pair.first} set to an iterator pointing to either the newly + * inserted element or to the element with an equivalent key in the {@link UniqueMap}. The + * {@link Pair.second} element in the {@link Pair} is set to true if a new element was inserted or + * false if an equivalent key already existed so the value is assigned. + */ + insert_or_assign(key: Key, value: T): Pair, boolean>; + /** + * Insert or assign an element. + * + * Inserts an element or assigns to the current element if the key already exists. + * + * Because element keys in a {@link UniqueMap} are unique, the insertion operation checks whether + * each inserted element has a key equivalent to the one of an element already in the container, and + * if so, the element is assigned, returning an iterator to this existing element (if the function returns a + * value). + * + * For a similar container allowing for duplicate elements, see {@link MultiMap}. + * + * @param hint Hint for the position where the element can be inserted. + * @param key The key used both to look up and to insert if not found. + * @param value Value, the item. + * + * @return An iterator pointing to either the newly inserted element or to the element that already had an + * equivalent key in the {@link UniqueMap}. + */ + insert_or_assign(hint: MapIterator, key: Key, value: T): MapIterator; + /** + * Insert or assign an element. + * + * Inserts an element or assigns to the current element if the key already exists. + * + * Because element keys in a {@link UniqueMap} are unique, the insertion operation checks whether + * each inserted element has a key equivalent to the one of an element already in the container, and + * if so, the element is assigned, returning an iterator to this existing element (if the function returns a + * value). + * + * For a similar container allowing for duplicate elements, see {@link MultiMap}. + * + * @param hint Hint for the position where the element can be inserted. + * @param key The key used both to look up and to insert if not found. + * @param value Value, the item. + * + * @return An iterator pointing to either the newly inserted element or to the element that already had an + * equivalent key in the {@link UniqueMap}. + */ + insert_or_assign(hint: MapReverseIterator, key: Key, value: T): MapReverseIterator; + /** + * @hidden + */ + private _Insert_or_assign_with_key_value(key, value); + /** + * @hidden + */ + private _Insert_or_assign_with_hint(hint, key, value); + /** + * Extract an element. + * + * Extracts the element pointed to by key and erases it from the {@link UniqueMap}. + * + * @param key Key value of the element whose mapped value is accessed. + * + * @return A {@link Pair} containing the value pointed to by key. + */ + extract(key: Key): Pair; + /** + * Extract an element. + * + * Extracts the element pointed to by key and erases it from the {@link UniqueMap}. + * + * @param it An iterator pointing an element to extract. + * + * @return An iterator pointing to the element immediately following it prior to the element being + * erased. If no such element exists,returns {@link end end()}. + */ + extract(it: MapIterator): MapIterator; + /** + * Extract an element. + * + * Extracts the element pointed to by key and erases it from the {@link UniqueMap}. + * + * @param it An iterator pointing an element to extract. + * + * @return An iterator pointing to the element immediately following it prior to the element being + * erased. If no such element exists,returns {@link end end()}. + */ + extract(it: MapReverseIterator): MapReverseIterator; + /** + * @hidden + */ + private _Extract_by_key(key); + /** + * @hidden + */ + private _Extract_by_iterator(it); + /** + * @hidden + */ + private _Extract_by_reverse_iterator(it); + /** + * Merge two maps. + * + * Attempts to extract each element in *source* and insert it into this container. If there's an element in this + * container with key equivalent to the key of an element from *source*, tnen that element is not extracted from + * the *source*. Otherwise, no element with same key exists in this container, then that element will be + * transfered from the *source* to this container. + * + * @param source A {@link MapContainer map container} to transfer the elements from. + */ + merge(source: MapContainer): void; + } +} +declare namespace std.base { + /** + * An abstract set. + * + * {@link SetContainer SetContainers} are containers that store elements allowing fast retrieval of + * individual elements based on their value. + * + * In an {@link SetContainer}, the value of an element is at the same time its key, used to uniquely + * identify it. Keys are immutable, therefore, the elements in an {@link SetContainer} cannot be modified + * once in the container - they can be inserted and removed, though. + * + * {@link SetContainer} stores elements, keeps sequence and enables indexing by inserting elements into a + * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index + * table like {@link RBTree tree} or {@link HashBuckets hash-table}. + * + * + * + * + * ### Container properties + *
+ *
Associative
+ *
+ * Elements in associative containers are referenced by their key and not by their absolute + * position in the container. + *
+ * + *
Set
+ *
The value of an element is also the key used to identify it.
+ * + *
Unique keys
+ *
No two elements in the container can have equivalent keys.
+ *
+ * + * @param Type of the elements. Each element in a {@link SetContainer} container is also identified + * by this value (each value is itself also the element's key). + * + * @author Jeongho Nam + */ + abstract class UniqueSet extends SetContainer { + /** + * @inheritdoc + */ + count(key: T): number; + /** + * Insert an element. + * + * Extends the container by inserting new elements, effectively increasing the container {@link size} by + * the number of element inserted (zero or one). + * + * Because elements in a {@link UniqueSet UniqueSets} are unique, the insertion operation checks whether + * each inserted element is equivalent to an element already in the container, and if so, the element is not + * inserted, returning an iterator to this existing element (if the function returns a value). + * + * For a similar container allowing for duplicate elements, see {@link MultiSet}. + * + * @param key Value to be inserted as an element. + * + * @return A {@link Pair}, with its member {@link Pair.first} set to an iterator pointing to either the newly + * inserted element or to the equivalent element already in the {@link UniqueSet}. The + * {@link Pair.second} element in the {@link Pair} is set to true if a new element was inserted or + * false if an equivalent element already existed. + */ + insert(val: T): Pair, boolean>; + /** + * @inheritdoc + */ + insert(hint: SetIterator, val: T): SetIterator; + /** + * @inheritdoc + */ + insert(hint: SetReverseIterator, val: T): SetReverseIterator; + /** + * @inheritdoc + */ + insert>(begin: InputIterator, end: InputIterator): void; + /** + * Extract an element. + * + * Extracts the element pointed to by val and erases it from the {@link UniqueSet}. + * + * @param val Value to be extracted. + * + * @return A value. + */ + extract(val: T): T; + /** + * Extract an element. + * + * Extracts the element pointed to by key and erases it from the {@link UniqueMap}. + * + * @param it An iterator pointing an element to extract. + * + * @return An iterator pointing to the element immediately following it prior to the element being + * erased. If no such element exists,returns {@link end end()}. + */ + extract(it: SetIterator): SetIterator; + /** + * Extract an element. + * + * Extracts the element pointed to by key and erases it from the {@link UniqueMap}. + * + * @param it An iterator pointing an element to extract. + * + * @return An iterator pointing to the element immediately following it prior to the element being + * erased. If no such element exists,returns {@link end end()}. + */ + extract(it: SetReverseIterator): SetReverseIterator; + /** + * @hidden + */ + private _Extract_by_key(val); + /** + * @hidden + */ + private _Extract_by_iterator(it); + /** + * @hidden + */ + private _Extract_by_reverse_iterator(it); + /** + * Merge two sets. + * + * Attempts to extract each element in *source* and insert it into this container. If there's an element in this + * container with key equivalent to the key of an element from *source*, tnen that element is not extracted from + * the *source*. Otherwise, no element with same key exists in this container, then that element will be + * transfered from the *source* to this container. + * + * @param source A {@link SetContainer set container} to transfer the elements from. + */ + merge(source: SetContainer): void; + } +} +declare namespace std.Deque { + type iterator = DequeIterator; + type reverse_iterator = DequeReverseIterator; +} +declare namespace std { + /** + * Double ended queue. + * + * {@link Deque} (usually pronounced like "deck") is an irregular acronym of + * double-ended queue. Double-ended queues are sequence containers with dynamic sizes that can be + * expanded or contracted on both ends (either its front or its back). + * + * Specific libraries may implement deques in different ways, generally as some form of dynamic array. But in any + * case, they allow for the individual elements to be accessed directly through random access iterators, with storage + * handled automatically by expanding and contracting the container as needed. + * + * Therefore, they provide a functionality similar to vectors, but with efficient insertion and deletion of + * elements also at the beginning of the sequence, and not only at its end. But, unlike {@link Vector Vectors}, + * {@link Deque Deques} are not guaranteed to store all its elements in contiguous storage locations: accessing + * elements in a deque by offsetting a pointer to another element causes undefined behavior. + * + * Both {@link Vector}s and {@link Deque}s provide a very similar interface and can be used for similar purposes, + * but internally both work in quite different ways: While {@link Vector}s use a single array that needs to be + * occasionally reallocated for growth, the elements of a {@link Deque} can be scattered in different chunks of + * storage, with the container keeping the necessary information internally to provide direct access to any of its + * elements in constant time and with a uniform sequential interface (through iterators). Therefore, + * {@link Deque Deques} are a little more complex internally than {@link Vector}s, but this allows them to grow more + * efficiently under certain circumstances, especially with very long sequences, where reallocations become more + * expensive. + * + * For operations that involve frequent insertion or removals of elements at positions other than the beginning or + * the end, {@link Deque Deques} perform worse and have less consistent iterators and references than + * {@link List Lists}. + * + * + * + * + * + * ### Container properties + *
+ *
Sequence
+ *
Elements in sequence containers are ordered in a strict linear sequence. Individual elements + * are accessed by their position in this sequence.
+ * + *
Dynamic array
+ *
Generally implemented as a dynamic array, it allows direct access to any element in the + * sequence and provides relatively fast addition/removal of elements at the beginning or the end + * of the sequence.
+ *
+ * + * @param Type of the elements. + * + * @reference http://www.cplusplus.com/reference/deque/deque/ + * @author Jeongho Nam + */ + class Deque extends base.Container implements base.IArrayContainer, base.IDequeContainer { + /** + * @hidden + */ + private matrix_; + /** + * @hidden + */ + private size_; + /** + * @hidden + */ + private capacity_; + /** + * @hidden + */ + private begin_; + /** + * @hidden + */ + private end_; + /** + * @hidden + */ + private rend_; + /** + * Default Constructor. + * + * Constructs an empty container, with no elements. + */ + constructor(); + /** + * Initializer list Constructor. + * + * Constructs a container with a copy of each of the elements in array, in the same order. + * + * @param array An array containing elements to be copied and contained. + */ + constructor(items: Array); + /** + * Fill Constructor. + * + * Constructs a container with n elements. Each element is a copy of val (if provided). + * + * @param n Initial container size (i.e., the number of elements in the container at construction). + * @param val Value to fill the container with. Each of the n elements in the container is + * initialized to a copy of this value. + */ + constructor(size: number, val: T); + /** + * Copy Constructor. + * + * Constructs a container with a copy of each of the elements in container, in the same order. + * + * @param container Another container object of the same type (with the same class template + * arguments T), whose contents are either copied or acquired. + */ + constructor(container: Deque); + /** + * Range Constructor. + * + * Constructs a container with as many elements as the range (begin, end), with each + * element emplace-constructed from its corresponding element in that range, in the same order. + * + * @param begin Input interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. + */ + constructor(begin: Iterator, end: Iterator); + /** + * @inheritdoc + */ + assign>(begin: InputIterator, end: InputIterator): void; + /** + * @inheritdoc + */ + assign(n: number, val: T): void; + /** + * Request a change in capacity. + * + * Requests that the {@link Deque container} {@link capacity} be at least enough to contain + * n elements. + * + * If n is greater than the current {@link Deque container} {@link capacity}, the + * function causes the {@link Deque container} to reallocate its storage increasing its + * {@link capacity} to n (or greater). + * + * In all other cases, the function call does not cause a reallocation and the + * {@link Deque container} {@link capacity} is not affected. + * + * This function has no effect on the {@link Deque container} {@link size} and cannot alter + * its elements. + * + * @param n Minimum {@link capacity} for the {@link Deque container}. + * Note that the resulting {@link capacity} may be equal or greater than n. + */ + reserve(capacity: number): void; + /** + * @inheritdoc + */ + clear(): void; + /** + * @inheritdoc + */ + size(): number; + /** + * @inheritdoc + */ + empty(): boolean; + /** + * Return size of allocated storage capacity. + * + * Returns the size of the storage space currently allocated for the {@link Deque container}, + * expressed in terms of elements. + * + * This {@link capacity} is not necessarily equal to the {@link Deque container} {@link size}. + * It can be equal or greater, with the extra space allowing to accommodate for growth without the + * need to reallocate on each insertion. + * + * Notice that this {@link capacity} does not suppose a limit on the {@link size} of the + * {@link Deque container}. When this {@link capacity} is exhausted and more is needed, it is + * automatically expanded by the {@link Deque container} (reallocating it storage space). + * The theoretical limit on the {@link size} of a {@link Deque container} is given by member + * {@link max_size}. + * + * The {@link capacity} of a {@link Deque container} can be explicitly altered by calling member + * {@link Deque.reserve}. + * + * @return The size of the currently allocated storage capacity in the {@link Deque container}, + * measured in terms of the number elements it can hold. + */ + capacity(): number; + /** + * @inheritdoc + */ + front(): T; + /** + * @inheritdoc + */ + back(): T; + /** + * @inheritdoc + */ + begin(): DequeIterator; + /** + * @inheritdoc + */ + end(): DequeIterator; + /** + * @inheritdoc + */ + rbegin(): DequeReverseIterator; + /** + * @inheritdoc + */ + rend(): DequeReverseIterator; + /** + * @inheritdoc + */ + at(index: number): T; + /** + * @inheritdoc + */ + set(index: number, val: T): void; + /** + * @hidden + */ + private _Fetch_index(index); + /** + * @hidden + */ + private _Compute_col_size(capacity?); + /** + * @inheritdoc + */ + push(...items: T[]): number; + /** + * @inheritdoc + */ + push_front(val: T): void; + /** + * @inheritdoc + */ + push_back(val: T): void; + /** + * @inheritdoc + */ + pop_front(): void; + /** + * @inheritdoc + */ + pop_back(): void; + /** + * @inheritdoc + */ + insert(position: DequeIterator, val: T): DequeIterator; + /** + * @inheritdoc + */ + insert(position: DequeIterator, n: number, val: T): DequeIterator; + /** + * @inheritdoc + */ + insert>(position: DequeIterator, begin: InputIterator, end: InputIterator): DequeIterator; + /** + * @inheritdoc + */ + insert(position: DequeReverseIterator, val: T): DequeReverseIterator; + /** + * @inheritdoc + */ + insert(position: DequeReverseIterator, n: number, val: T): DequeReverseIterator; + /** + * @inheritdoc + */ + insert>(position: DequeReverseIterator, begin: InputIterator, end: InputIterator): DequeReverseIterator; + /** + * @hidden + */ + private _Insert_by_val(position, val); + /** + * @hidden + */ + private _Insert_by_repeating_val(position, n, val); + /** + * @hidden + */ + protected _Insert_by_range>(pos: DequeIterator, first: InputIterator, last: InputIterator): DequeIterator; + /** + * @hidden + */ + private _Insert_to_middle(pos, first, last); + /** + * @hidden + */ + private _Insert_to_end(first, last); + /** + * @hidden + */ + private _Try_expand_capacity(size); + /** + * @hidden + */ + private _Try_add_row_at_front(); + /** + * @hidden + */ + private _Try_add_row_at_back(); + /** + * @inheritdoc + */ + erase(position: DequeIterator): DequeIterator; + /** + * @inheritdoc + */ + erase(first: DequeIterator, last: DequeIterator): DequeIterator; + /** + * @inheritdoc + */ + erase(position: DequeReverseIterator): DequeReverseIterator; + /** + * @inheritdoc + */ + erase(first: DequeReverseIterator, last: DequeReverseIterator): DequeReverseIterator; + /** + * @hidden + */ + protected _Erase_by_range(first: DequeIterator, last: DequeIterator): DequeIterator; + /** + * Swap content. + * + * Exchanges the content of the container by the content of obj, which is another + * {@link Deque container} object with same type of elements. Sizes and container type may differ. + * + * After the call to this member function, the elements in this container are those which were in obj + * before the call, and the elements of obj are those which were in this. All iterators, references and + * pointers remain valid for the swapped objects. + * + * Notice that a non-member function exists with the same name, {@link swap swap}, overloading that + * algorithm with an optimization that behaves like this member function. + * + * @param obj Another {@link Deque container} of the same type of elements (i.e., instantiated + * with the same template parameter, T) whose content is swapped with that of this + * {@link Deque container}. + */ + swap(obj: Deque): void; + /** + * @inheritdoc + */ + swap(obj: base.Container): void; + /** + * @hidden + */ + private static readonly ROW_SIZE; + /** + * @hidden + */ + private static readonly MIN_CAPACITY; + /** + * @hidden + */ + private static readonly MAGNIFIER; + } +} +declare namespace std { + /** + * An iterator of {@link Deque}. + * + * + * + * + * @author Jeongho Nam + */ + class DequeIterator extends Iterator implements base.IArrayIterator { + /** + * @hidden + */ + private index_; + /** + * Construct from the source {@link Deque container}. + * + * #### Note + * Do not create the iterator directly, by yourself. + * + * Use {@link Deque.begin begin()}, {@link Deque.end end()} in {@link Deque container} instead. + * + * @param source The source {@link Deque container} to reference. + * @param index Sequence number of the element in the source {@link Deque}. + */ + constructor(source: Deque, index: number); + /** + * @inheritdoc + */ + source(): Deque; + /** + * @inheritdoc + */ + index(): number; + /** + * @inheritdoc + */ + /** + * Set value of the iterator is pointing to. + * + * @param val Value to set. + */ + value: T; + /** + * @inheritdoc + */ + prev(): DequeIterator; + /** + * @inheritdoc + */ + next(): DequeIterator; + /** + * @inheritdoc + */ + advance(n: number): DequeIterator; + /** + * @inheritdoc + */ + equals(obj: DequeIterator): boolean; + /** + * @inheritdoc + */ + swap(obj: DequeIterator): void; + } +} +declare namespace std { + /** + * A reverse-iterator of Deque. + * + * + * + * + * @param Type of the elements. + * + * @author Jeongho Nam + */ + class DequeReverseIterator extends ReverseIterator, DequeIterator, DequeReverseIterator> implements base.IArrayIterator { + /** + * Construct from base iterator. + * + * @param base A reference of the base iterator, which iterates in the opposite direction. + */ + constructor(base: DequeIterator); + /** + * @hidden + */ + protected _Create_neighbor(base: DequeIterator): DequeReverseIterator; + /** + * @inheritdoc + */ + index(): number; + /** + * @inheritdoc + */ + /** + * Set value of the iterator is pointing to. + * + * @param val Value to set. + */ + value: T; + } +} +declare namespace std { + /** + * Function handling termination on exception + * + * Calls the current terminate handler. + * + * By default, the terminate handler calls abort. But this behavior can be redefined by calling + * {@link set_terminate}. + * + * This function is automatically called when no catch handler can be found for a thrown exception, + * or for some other exceptional circumstance that makes impossible to continue the exception handling process. + * + * This function is provided so that the terminate handler can be explicitly called by a program that needs to + * abnormally terminate, and works even if {@link set_terminate} has not been used to set a custom terminate handler + * (calling abort in this case). + */ + function terminate(): void; + /** + * Set terminate handler function. + * + * A terminate handler function is a function automatically called when the exception handling process has + * to be abandoned for some reason. This happens when no catch handler can be found for a thrown exception, or for + * some other exceptional circumstance that makes impossible to continue the exception handling process. + * + * Before this function is called by the program for the first time, the default behavior is to call abort. + * + * A program may explicitly call the current terminate handler function by calling {@link terminate}. + * + * @param f Function that takes no parameters and returns no value (void). + */ + function set_terminate(f: () => void): void; + /** + * Get terminate handler function. + * + * The terminate handler function is automatically called when no catch handler can be found + * for a thrown exception, or for some other exceptional circumstance that makes impossible to continue the exception + * handling process. + * + * If no such function has been set by a previous call to {@link set_terminate}, the function returns a + * null-pointer. + * + * @return If {@link set_terminate} has previously been called by the program, the function returns the current + * terminate handler function. Otherwise, it returns a null-pointer. + */ + function get_terminate(): () => void; + /** + * Standard exception class. + * + * Base class for standard exceptions. + * + * All objects thrown by components of the standard library are derived from this class. + * Therefore, all standard exceptions can be caught by catching this type by reference. + * + * + * + * + * @reference http://www.cplusplus.com/reference/exception/exception + * @author Jeongho Nam + */ + class Exception { + /** + * @hidden + */ + private message_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from a message. + * + * @param message A message representing specification about the Exception. + */ + constructor(message: string); + /** + * Get string identifying exception. + * + * Returns a string that may be used to identify the exception. + * + * The particular representation pointed by the returned value is implementation-defined. + * As a virtual function, derived classes may redefine this function so that specify value are + * returned. + */ + what(): string; + } + /** + * Logic error exception. + * + * This class defines the type of objects thrown as exceptions to report errors in the internal + * logical of the program, such as violation of logical preconditions or class invariants. + * + * These errors are presumably detectable before the program executes. + * + * It is used as a base class for several logical error exceptions. + * + * + * + * + * @reference http://www.cplusplus.com/reference/stdexcept/logic_error + * @author Jeongho Nam + */ + class LogicError extends Exception { + /** + * Construct from a message. + * + * @param message A message representing specification about the Exception. + */ + constructor(message: string); + } + /** + * Domain error exception. + * + * This class defines the type of objects thrown as exceptions to report domain errors. + * + * Generally, the domain of a mathematical function is the subset of values that it is defined for. + * For example, the square root function is only defined for non-negative numbers. Thus, a negative number + * for such a function would qualify as a domain error. + * + * No component of the standard library throws exceptions of this type. It is designed as a standard + * exception to be thrown by programs. + * + * + *

+ * + * @reference http://www.cplusplus.com/reference/stdexcept/domain_error + * @author Jeongho Nam + */ + class DomainError extends LogicError { + /** + * Construct from a message. + * + * @param message A message representing specification about the Exception. + */ + constructor(message: string); + } + /** + * Invalid argument exception. + * + * This class defines the type of objects thrown as exceptions to report an invalid argument. + * + * It is a standard exception that can be thrown by programs. Some components of the standard library + * also throw exceptions of this type to signal invalid arguments. + * + * + * + * + * @reference http://www.cplusplus.com/reference/stdexcept/invalid_argument + * @author Jeongho Nam + */ + class InvalidArgument extends LogicError { + /** + * Construct from a message. + * + * @param message A message representing specification about the Exception. + */ + constructor(message: string); + } + /** + * Length error exception. + * + * This class defines the type of objects thrown as exceptions to report a length error. + * + * It is a standard exception that can be thrown by programs. Some components of the standard library, + * such as vector and string also throw exceptions of this type to signal errors resizing. + * + * + * + * + * @reference http://www.cplusplus.com/reference/stdexcept/length_error + * @author Jeongho Nam + */ + class LengthError extends LogicError { + /** + * Construct from a message. + * + * @param message A message representing specification about the Exception. + */ + constructor(message: string); + } + /** + * Out-of-range exception. + * + * This class defines the type of objects thrown as exceptions to report an out-of-range error. + * + * It is a standard exception that can be thrown by programs. Some components of the standard library, + * such as vector, deque, string and bitset also throw exceptions of this type to signal arguments + * out of range. + * + * + * + * + * @reference http://www.cplusplus.com/reference/stdexcept/out_of_range + * @author Jeongho Nam + */ + class OutOfRange extends LogicError { + /** + * Construct from a message. + * + * @param message A message representing specification about the Exception. + */ + constructor(message: string); + } + /** + * Runtime error exception. + * + * This class defines the type of objects thrown as exceptions to report errors that can only be + * detected during runtime. + * + * It is used as a base class for several runtime error exceptions. + * + * + * + * + * @reference http://www.cplusplus.com/reference/stdexcept/runtime_error + * @author Jeongho Nam + */ + class RuntimeError extends Exception { + /** + * Construct from a message. + * + * @param message A message representing specification about the Exception. + */ + constructor(message: string); + } + /** + * Overflow error exception. + * + * This class defines the type of objects thrown as exceptions to arithmetic overflow errors. + * + * It is a standard exception that can be thrown by programs. Some components of the standard library + * also throw exceptions of this type to signal range errors. + * + * + * + * + * @reference http://www.cplusplus.com/reference/stdexcept/overflow_error + * @author Jeongho Nam + */ + class OverflowError extends RuntimeError { + /** + * Construct from a message. + * + * @param message A message representing specification about the Exception. + */ + constructor(message: string); + } + /** + * Underflow error exception. + * + * This class defines the type of objects thrown as exceptions to arithmetic underflow errors. + * + * No component of the standard library throws exceptions of this type. It is designed as a standard + * exception to be thrown by programs. + * + * + * + * + * @reference http://www.cplusplus.com/reference/stdexcept/underflow_error + * @author Jeongho Nam + */ + class UnderflowError extends RuntimeError { + /** + * Construct from a message. + * + * @param message A message representing specification about the Exception. + */ + constructor(message: string); + } + /** + * Range error exception. + * + * This class defines the type of objects thrown as exceptions to report range errors in internal + * computations. + * + * It is a standard exception that can be thrown by programs. Some components of the standard library + * also throw exceptions of this type to signal range errors. + * + * + * + * + * @reference http://www.cplusplus.com/reference/stdexcept/range_error + * @author Jeongho Nam + */ + class RangeError extends RuntimeError { + /** + * Construct from a message. + * + * @param message A message representing specification about the Exception. + */ + constructor(message: string); + } +} +declare namespace std { + /** + * Function object class for equality comparison. + * + * Binary function object class whose call returns whether its two arguments compare equal (as returned by + * operator ==). + * + * Generically, function objects are instances of a class with member function {@link IComparable.equal_to equal_to} + * defined. This member function allows the object to be used with the same syntax as a function call. + * + * @param x First element to compare. + * @param y Second element to compare. + * + * @return Whether the arguments are equal. + */ + function equal_to(x: T, y: T): boolean; + /** + * Function object class for non-equality comparison. + * + * Binary function object class whose call returns whether its two arguments compare not equal (as returned + * by operator operator!=). + * + * Generically, function objects are instances of a class with member function {@link IComparable.equal_to equal_to} + * defined. This member function allows the object to be used with the same syntax as a function call. + * + * @param x First element to compare. + * @param y Second element to compare. + * + * @return Whether the arguments are not equal. + */ + function not_equal_to(x: T, y: T): boolean; + /** + * Function for less-than inequality comparison. + * + * Binary function returns whether the its first argument compares less than the second. + * + * Generically, function objects are instances of a class with member function {@link IComparable.less less} + * defined. If an object doesn't have the method, then its own uid will be used to compare insteadly. + * This member function allows the object to be used with the same syntax as a function call. + * + * Objects of this class can be used on standard algorithms such as {@link sort sort()}, + * {@link merge merge()} or {@link TreeMap.lower_bound lower_bound()}. + * + * @param Type of arguments to compare by the function call. The type shall supporrt the operation + * operator<() or method {@link IComparable.less less}. + * + * @param x First element, the standard of comparison. + * @param y Second element compare with the first. + * + * @return Whether the first parameter is less than the second. + */ + function less(x: T, y: T): boolean; + /** + * Function object class for less-than-or-equal-to comparison. + * + * Binary function object class whose call returns whether the its first argument compares {@link less less than} or + * {@link equal_to equal to} the second (as returned by operator <=). + * + * Generically, function objects are instances of a class with member function {@link IComparable.less less} + * and {@link IComparable.equal_to equal_to} defined. This member function allows the object to be used with the same + * syntax as a function call. + * + * @param x First element, the standard of comparison. + * @param y Second element compare with the first. + * + * @return Whether the x is {@link less less than} or {@link equal_to equal to} the y. + */ + function less_equal(x: T, y: T): boolean; + /** + * Function for greater-than inequality comparison. + * + * Binary function returns whether the its first argument compares greater than the second. + * + * Generically, function objects are instances of a class with member function {@link less} and + * {@link equal_to equal_to()} defined. If an object doesn't have those methods, then its own uid will be used + * to compare insteadly. This member function allows the object to be used with the same syntax as a function + * call. + * + * Objects of this class can be used on standard algorithms such as {@link sort sort()}, + * {@link merge merge()} or {@link TreeMap.lower_bound lower_bound()}. + * + * @param Type of arguments to compare by the function call. The type shall supporrt the operation + * operator>() or method {@link IComparable.greater greater}. + * + * @return Whether the x is greater than the y. + */ + function greater(x: T, y: T): boolean; + /** + * Function object class for greater-than-or-equal-to comparison. + * + * Binary function object class whose call returns whether the its first argument compares + * {@link greater greater than} or {@link equal_to equal to} the second (as returned by operator >=). + * + * Generically, function objects are instances of a class with member function {@link IComparable.less less} + * defined. If an object doesn't have the method, then its own uid will be used to compare insteadly. + * This member function allows the object to be used with the same syntax as a function call. + * + * @param x First element, the standard of comparison. + * @param y Second element compare with the first. + * + * @return Whether the x is {@link greater greater than} or {@link equal_to equal to} the y. + */ + function greater_equal(x: T, y: T): boolean; + /** + * Logical AND function object class. + * + * Binary function object class whose call returns the result of the logical "and" operation between its two + * arguments (as returned by operator &&). + * + * Generically, function objects are instances of a class with member function operator() defined. This member + * function allows the object to be used with the same syntax as a function call. + * + * @param x First element. + * @param y Second element. + * + * @return Result of logical AND operation. + */ + function logical_and(x: T, y: T): boolean; + /** + * Logical OR function object class. + * + * Binary function object class whose call returns the result of the logical "or" operation between its two + * arguments (as returned by operator ||). + * + * Generically, function objects are instances of a class with member function operator() defined. This member + * function allows the object to be used with the same syntax as a function call. + * + * @param x First element. + * @param y Second element. + * + * @return Result of logical OR operation. + */ + function logical_or(x: T, y: T): boolean; + /** + * Logical NOT function object class. + * + * Unary function object class whose call returns the result of the logical "not" operation on its argument + * (as returned by operator !). + * + * Generically, function objects are instances of a class with member function operator() defined. This member + * function allows the object to be used with the same syntax as a function call. + * + * @param x Target element. + * + * @return Result of logical NOT operation. + */ + function logical_not(x: T): boolean; + /** + * Bitwise AND function object class. + * + * Binary function object class whose call returns the result of applying the bitwise "and" operation between + * its two arguments (as returned by operator &). + * + * @param x First element. + * @param y Second element. + * + * @return Result of bitwise AND operation. + */ + function bit_and(x: number, y: number): number; + /** + * Bitwise OR function object class. + * + * Binary function object class whose call returns the result of applying the bitwise "and" operation between + * its two arguments (as returned by operator &). + * + * @param x First element. + * @param y Second element. + * + * @return Result of bitwise OR operation. + */ + function bit_or(x: number, y: number): number; + /** + * Bitwise XOR function object class. + * + * Binary function object class whose call returns the result of applying the bitwise "exclusive or" + * operation between its two arguments (as returned by operator ^). + * + * @param x First element. + * @param y Second element. + * + * @return Result of bitwise XOR operation. + */ + function bit_xor(x: number, y: number): number; + /** + * Default hash function for number. + * + * Unary function that defines the default hash function used by the standard library. + * + * The functional call returns a hash value of its argument: A hash value is a value that depends solely on + * its argument, returning always the same value for the same argument (for a given execution of a program). The + * value returned shall have a small likelihood of being the same as the one returned for a different argument. + * + * + * @param val Value to be hashed. + * + * @return Returns a hash value for its argument, as a value of type number. The number is an unsigned integer. + */ + function hash(val: number): number; + /** + * Default hash function for string. + * + * Unary function that defines the default hash function used by the standard library. + * + * The functional call returns a hash value of its argument: A hash value is a value that depends solely on + * its argument, returning always the same value for the same argument (for a given execution of a program). The + * value returned shall have a small likelihood of being the same as the one returned for a different argument. + * + * @param str A string to be hashed. + * + * @return Returns a hash value for its argument, as a value of type number. The number is an unsigned integer. + */ + function hash(str: string): number; + /** + * Default hash function for Object. + * + * Unary function that defines the default hash function used by the standard library. + * + * The functional call returns a hash value of its argument: A hash value is a value that depends solely on + * its argument, returning always the same value for the same argument (for a given execution of a program). The + * value returned shall have a small likelihood of being the same as the one returned for a different argument. + * + * + * The default {@link hash} function of Object returns a value returned from {@link hash hash(number)} with + * an unique id of each Object. If you want to specify {@link hash} function of a specific class, then + * define a member function public hashCode(): number in the class. + * + * @param obj Object to be hashed. + * + * @return Returns a hash value for its argument, as a value of type number. The number is an unsigned integer. + */ + function hash(obj: Object): number; + /** + * Exchange contents of {@link IContainers containers}. + * + * The contents of container left are exchanged with those of right. Both container objects must have + * same type of elements (same template parameters), although sizes may differ. + * + * After the call to this member function, the elements in left are those which were in right before + * the call, and the elements of right are those which were in left. All iterators, references and + * pointers remain valid for the swapped objects. + * + * This is an overload of the generic algorithm swap that improves its performance by mutually transferring + * ownership over their assets to the other container (i.e., the containers exchange references to their data, without + * actually performing any element copy or movement): It behaves as if left. + * {@link Container.swap swap}(right) was called. + * + * @param left A {@link Container container} to swap its contents. + * @param right A {@link Container container} to swap its contents. + */ + function swap(left: base.Container, right: base.Container): void; + /** + * Exchange contents of queues. + * + * Exchanges the contents of left and right. + * + * @param left A {@link Queue} container of the same type. Size may differ. + * @param right A {@link Queue} container of the same type. Size may differ. + */ + function swap(left: Queue, right: Queue): void; + /** + * Exchange contents of {@link PriorityQueue PriorityQueues}. + * + * Exchanges the contents of left and right. + * + * @param left A {@link PriorityQueue} container of the same type. Size may differ. + * @param right A {@link PriorityQueue} container of the same type. Size may differ. + */ + function swap(left: PriorityQueue, right: PriorityQueue): void; + /** + * Exchange contents of {@link Stack Stacks}. + * + * Exchanges the contents of left and right. + * + * @param left A {@link Stack} container of the same type. Size may differ. + * @param right A {@link Stack} container of the same type. Size may differ. + */ + function swap(left: Stack, right: Stack): void; + /** + * Exchanges the contents of two {@link UniqueMap unique maps}. + * + * The contents of container left are exchanged with those of right. Both container objects must + * be of the same type (same template parameters), although sizes may differ. + * + * After the call to this member function, the elements in left are those which were in right + * before the call, and the elements of right are those which were in left. All iterators, references + * and pointers remain valid for the swapped objects. + * + * This is an overload of the generic algorithm swap that improves its performance by mutually transferring + * ownership over their assets to the other container (i.e., the containers exchange references to their data, + * without actually performing any element copy or movement): It behaves as if + * left.{@link UniqueMap.swap swap}(right) was called. + * + * @param left An {@link UniqueMap unique map} to swap its conents. + * @param right An {@link UniqueMap unique map} to swap its conents. + */ + function swap(left: base.UniqueMap, right: base.UniqueMap): void; + /** + * Exchanges the contents of two {@link MultiMap multi maps}. + * + * The contents of container left are exchanged with those of right. Both container objects must + * be of the same type (same template parameters), although sizes may differ. + * + * After the call to this member function, the elements in left are those which were in right + * before the call, and the elements of right are those which were in left. All iterators, references + * and pointers remain valid for the swapped objects. + * + * This is an overload of the generic algorithm swap that improves its performance by mutually transferring + * ownership over their assets to the other container (i.e., the containers exchange references to their data, + * without actually performing any element copy or movement): It behaves as if + * left.{@link MultiMap.swap swap}(right) was called. + * + * @param left A {@link MultiMap multi map} to swap its conents. + * @param right A {@link MultiMap multi map} to swap its conents. + */ + function swap(left: base.MultiMap, right: base.MultiMap): void; +} +declare namespace std { + /** + * Bind function arguments. + * + * Returns a function object based on fn, but with its arguments bound to args. + * + * Each argument may either be bound to a value or be a {@link placeholders placeholder}: + *
    + *
  • If bound to a value, calling the returned function object will always use that value as argument.
  • + *
  • + * If a {@link placeholders placeholder}, calling the returned function object forwards an argument passed to the + * call (the one whose order number is specified by the placeholder). + *
  • + *
+ * + * Calling the returned object returns the same type as fn. + * + * @param fn A function object, pointer to function or pointer to member. + * @param args List of arguments to bind: either values, or {@link placeholders}. + * + * @return A function object that, when called, calls fn with its arguments bound to args. If fn is + * a pointer to member, the first argument expected by the returned function is an object of the class fn + * is a member. + */ + function bind(fn: (...args: any[]) => Ret, ...args: any[]): (...args: any[]) => Ret; + /** + * Bind function arguments. + * + * Returns a function object based on fn, but with its arguments bound to args. + * + * Each argument may either be bound to a value or be a {@link placeholders placeholder}: + *
    + *
  • If bound to a value, calling the returned function object will always use that value as argument.
  • + *
  • + * If a {@link placeholders placeholder}, calling the returned function object forwards an argument passed to the + * call (the one whose order number is specified by the placeholder). + *
  • + *
+ * + * Calling the returned object returns the same type as fn. + * + * @param fn A function object, pointer to function or pointer to member. + * @param thisArg This argument, owner object of the member method fn. + * @param args List of arguments to bind: either values, or {@link placeholders}. + * + * @return A function object that, when called, calls fn with its arguments bound to args. If fn is + * a pointer to member, the first argument expected by the returned function is an object of the class fn + * is a member. + */ + function bind(fn: (...args: any[]) => Ret, thisArg: T, ...args: any[]): (...args: any[]) => Ret; +} +/** + * Bind argument placeholders. + * + * This namespace declares an unspecified number of objects: _1, _2, _3, ...
, which are + * used to specify placeholders in calls to function {@link bind}. + * + * When the function object returned by bind is called, an argument with placeholder {@link _1} is replaced by the + * first argument in the call, {@link _2} is replaced by the second argument in the call, and so on... For example: + * + * + * let vec: Vector = new Vector(); + * + * let bind = bind(Vector.insert, _1, vec.end(), _2, _3); + * bind.apply(vec, 5, 1); // vec.insert(vec.end(), 5, 1); + * // [1, 1, 1, 1, 1] + * + * + * When a call to {@link bind} is used as a subexpression in another call to bind, the {@link placeholders} + * are relative to the outermost {@link bind} expression. + * + * @reference http://www.cplusplus.com/reference/functional/placeholders/ + * @author Jeongho Nam + */ +declare namespace std.placeholders { + /** + * @hidden + */ + class PlaceHolder { + private index_; + constructor(index: number); + index(): number; + } + /** + * Replaced by the first argument in the function call. + */ + const _1: PlaceHolder; + /** + * Replaced by the second argument in the function call. + */ + const _2: PlaceHolder; + /** + * Replaced by the third argument in the function call. + */ + const _3: PlaceHolder; + const _4: PlaceHolder; + const _5: PlaceHolder; + const _6: PlaceHolder; + const _7: PlaceHolder; + const _8: PlaceHolder; + const _9: PlaceHolder; + const _10: PlaceHolder; + const _11: PlaceHolder; + const _12: PlaceHolder; + const _13: PlaceHolder; + const _14: PlaceHolder; + const _15: PlaceHolder; + const _16: PlaceHolder; + const _17: PlaceHolder; + const _18: PlaceHolder; + const _19: PlaceHolder; + const _20: PlaceHolder; +} +declare namespace std.HashMap { + type iterator = MapIterator; + type reverse_iterator = MapReverseIterator; +} +declare namespace std { + /** + * Hashed, unordered map. + * + * {@link HashMap}s are associative containers that store elements formed by the combination of a key value + * and a mapped value, and which allows for fast retrieval of individual elements based on their keys. + * + * In an {@link HashMap}, the key value is generally used to uniquely identify the element, while the + * mapped value is an object with the content associated to this key. Types of key and + * mapped value may differ. + * + * Internally, the elements in the {@link HashMap} are not sorted in any particular order with respect to either + * their key or mapped values, but organized into buckets depending on their hash values to allow + * for fast access to individual elements directly by their key values (with a constant average time complexity + * on average). + * + * {@link HashMap} containers are faster than {@link TreeMap} containers to access individual elements by their + * key, although they are generally less efficient for range iteration through a subset of their elements. + * + * + * + * + * ### Container properties + *
+ *
Associative
+ *
Elements in associative containers are referenced by their key and not by their absolute + * position in the container.
+ * + *
Hashed
+ *
Hashed containers organize their elements using hash tables that allow for fast access to elements + * by their key.
+ * + *
Map
+ *
Each element associates a key to a mapped value: + * Keys are meant to identify the elements whose main content is the mapped value.
+ * + *
Unique keys
+ *
No two elements in the container can have equivalent keys.
+ *
+ * + * @param Type of the key values. + * Each element in an {@link HashMap} is uniquely identified by its key value. + * @param Type of the mapped value. + * Each element in an {@link HashMap} is used to store some data as its mapped value. + * + * @reference http://www.cplusplus.com/reference/unordered_map/unordered_map + * @author Jeongho Nam + */ + class HashMap extends base.UniqueMap implements base.IHashMap { + /** + * @hidden + */ + private hash_buckets_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from elements. + */ + constructor(items: Pair[]); + /** + * Contruct from tuples. + * + * @param array Tuples to be contained. + */ + constructor(array: [Key, T][]); + /** + * Copy Constructor. + */ + constructor(container: HashMap); + /** + * Construct from range iterators. + */ + constructor(begin: Iterator>, end: Iterator>); + /** + * @inheritdoc + */ + clear(): void; + /** + * @inheritdoc + */ + find(key: Key): MapIterator; + /** + * @inheritdoc + */ + begin(): MapIterator; + /** + * @inheritdoc + */ + begin(index: number): MapIterator; + /** + * @inheritdoc + */ + end(): MapIterator; + /** + * @inheritdoc + */ + end(index: number): MapIterator; + /** + * @inheritdoc + */ + rbegin(): MapReverseIterator; + /** + * @inheritdoc + */ + rbegin(index: number): MapReverseIterator; + /** + * @inheritdoc + */ + rend(): MapReverseIterator; + /** + * @inheritdoc + */ + rend(index: number): MapReverseIterator; + /** + * @inheritdoc + */ + bucket_count(): number; + /** + * @inheritdoc + */ + bucket_size(index: number): number; + /** + * @inheritdoc + */ + max_load_factor(): number; + /** + * @inheritdoc + */ + max_load_factor(z: number): void; + /** + * @inheritdoc + */ + bucket(key: Key): number; + /** + * @inheritdoc + */ + reserve(n: number): void; + /** + * @inheritdoc + */ + rehash(n: number): void; + /** + * @hidden + */ + protected _Insert_by_pair(pair: Pair): any; + /** + * @hidden + */ + protected _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; + /** + * @hidden + */ + protected _Insert_by_range>>(first: InputIterator, last: InputIterator): void; + /** + * @hidden + */ + protected _Handle_insert(first: MapIterator, last: MapIterator): void; + /** + * @hidden + */ + protected _Handle_erase(first: MapIterator, last: MapIterator): void; + /** + * Swap content. + * + * Exchanges the content of the container by the content of obj, which is another + * {@link HashMap map} of the same type. Sizes abd container type may differ. + * + * After the call to this member function, the elements in this container are those which were + * in obj before the call, and the elements of obj are those which were in this. All + * iterators, references and pointers remain valid for the swapped objects. + * + * Notice that a non-member function exists with the same name, {@link swap swap}, overloading that + * algorithm with an optimization that behaves like this member function. + * + * @param obj Another {@link HashMap map container} of the same type of elements as this (i.e., + * with the same template parameters, Key and T) whose content is swapped + * with that of this {@link HashMap container}. + */ + swap(obj: HashMap): void; + /** + * @inheritdoc + */ + swap(obj: base.Container>): void; + } +} +declare namespace std.HashMultiMap { + type iterator = MapIterator; + type reverse_iterator = MapReverseIterator; +} +declare namespace std { + /** + * Hashed, unordered Multimap. + * + * {@link HashMultiMap}s are associative containers that store elements formed by the combination of + * a key value and a mapped value, much like {@link HashMultiMap} containers, but allowing + * different elements to have equivalent keys. + * + * In an {@link HashMultiMap}, the key value is generally used to uniquely identify the + * element, while the mapped value is an object with the content associated to this key. + * Types of key and mapped value may differ. + * + * Internally, the elements in the {@link HashMultiMap} are not sorted in any particular order with + * respect to either their key or mapped values, but organized into buckets depending on + * their hash values to allow for fast access to individual elements directly by their key values + * (with a constant average time complexity on average). + * + * Elements with equivalent keys are grouped together in the same bucket and in such a way that + * an iterator can iterate through all of them. Iterators in the container are doubly linked iterators. + * + * + * + * + * ### Container properties + *
+ *
Associative
+ *
Elements in associative containers are referenced by their key and not by their absolute + * position in the container.
+ * + *
Hashed
+ *
Hashed containers organize their elements using hash tables that allow for fast access to elements + * by their key.
+ * + *
Map
+ *
Each element associates a key to a mapped value: + * Keys are meant to identify the elements whose main content is the mapped value.
+ * + *
Multiple equivalent keys
+ *
The container can hold multiple elements with equivalent keys.
+ *
+ * + * @param Type of the key values. + * Each element in an {@link HashMultiMap} is identified by a key value. + * @param Type of the mapped value. + * Each element in an {@link HashMultiMap} is used to store some data as its mapped value. + * + * @reference http://www.cplusplus.com/reference/unordered_map/unordered_multimap + * @author Jeongho Nam + */ + class HashMultiMap extends base.MultiMap { + /** + * @hidden + */ + private hash_buckets_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from elements. + */ + constructor(items: Pair[]); + /** + * Contruct from tuples. + * + * @param array Tuples to be contained. + */ + constructor(array: [Key, T][]); + /** + * Copy Constructor. + */ + constructor(container: HashMultiMap); + /** + * Construct from range iterators. + */ + constructor(begin: Iterator>, end: Iterator>); + /** + * @inheritdoc + */ + clear(): void; + /** + * @inheritdoc + */ + find(key: Key): MapIterator; + /** + * @inheritdoc + */ + count(key: Key): number; + /** + * @inheritdoc + */ + begin(): MapIterator; + /** + * @inheritdoc + */ + begin(index: number): MapIterator; + /** + * @inheritdoc + */ + end(): MapIterator; + /** + * @inheritdoc + */ + end(index: number): MapIterator; + /** + * @inheritdoc + */ + rbegin(): MapReverseIterator; + /** + * @inheritdoc + */ + rbegin(index: number): MapReverseIterator; + /** + * @inheritdoc + */ + rend(): MapReverseIterator; + /** + * @inheritdoc + */ + rend(index: number): MapReverseIterator; + /** + * @inheritdoc + */ + bucket_count(): number; + /** + * @inheritdoc + */ + bucket_size(n: number): number; + /** + * @inheritdoc + */ + max_load_factor(): number; + /** + * @inheritdoc + */ + max_load_factor(z: number): void; + /** + * @inheritdoc + */ + bucket(key: Key): number; + /** + * @inheritdoc + */ + reserve(n: number): void; + /** + * @inheritdoc + */ + rehash(n: number): void; + /** + * @hidden + */ + protected _Insert_by_pair(pair: Pair): any; + /** + * @hidden + */ + protected _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; + /** + * @hidden + */ + protected _Insert_by_range>>(first: InputIterator, last: InputIterator): void; + /** + * @hidden + */ + protected _Handle_insert(first: MapIterator, last: MapIterator): void; + /** + * @hidden + */ + protected _Handle_erase(first: MapIterator, last: MapIterator): void; + /** + * Swap content. + * + * Exchanges the content of the container by the content of obj, which is another + * {@link HashMultiMap map} of the same type. Sizes abd container type may differ. + * + * After the call to this member function, the elements in this container are those which were + * in obj before the call, and the elements of obj are those which were in this. All + * iterators, references and pointers remain valid for the swapped objects. + * + * Notice that a non-member function exists with the same name, {@link swap swap}, overloading that + * algorithm with an optimization that behaves like this member function. + * + * @param obj Another {@link HashMultiMap map container} of the same type of elements as this (i.e., + * with the same template parameters, Key and T) whose content is swapped + * with that of this {@link HashMultiMap container}. + */ + swap(obj: HashMultiMap): void; + /** + * @inheritdoc + */ + swap(obj: base.Container>): void; + } +} +declare namespace std.HashMultiSet { + type iterator = SetIterator; + type reverse_iterator = SetReverseIterator; +} +declare namespace std { + /** + * Hashed, unordered Multiset. + * + * {@link HashMultiSet HashMultiSets} are containers that store elements in no particular order, allowing fast + * retrieval of individual elements based on their value, much like {@link HashMultiSet} containers, + * but allowing different elements to have equivalent values. + * + * In an {@link HashMultiSet}, the value of an element is at the same time its key, used to + * identify it. Keys are immutable, therefore, the elements in an {@link HashMultiSet} cannot be + * modified once in the container - they can be inserted and removed, though. + * + * Internally, the elements in the {@link HashMultiSet} are not sorted in any particular, but + * organized into buckets depending on their hash values to allow for fast access to individual + * elements directly by their values (with a constant average time complexity on average). + * + * Elements with equivalent values are grouped together in the same bucket and in such a way that an + * iterator can iterate through all of them. Iterators in the container are doubly linked iterators. + * + * + * + * + * ### Container properties + *
+ *
Associative
+ *
Elements in associative containers are referenced by their key and not by their absolute + * position in the container.
+ * + *
Hashed
+ *
Hashed containers organize their elements using hash tables that allow for fast access to elements + * by their key.
+ * + *
Set
+ *
The value of an element is also the key used to identify it.
+ * + *
Multiple equivalent keys
+ *
The container can hold multiple elements with equivalent keys.
+ *
+ * + * @param Type of the elements. + * Each element in an {@link UnorderedMultiSet} is also identified by this value.. + * + * @reference http://www.cplusplus.com/reference/unordered_set/unordered_multiset + * @author Jeongho Nam + */ + class HashMultiSet extends base.MultiSet { + /** + * @hidden + */ + private hash_buckets_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from elements. + */ + constructor(items: T[]); + /** + * Copy Constructor. + */ + constructor(container: HashMultiSet); + /** + * Construct from range iterators. + */ + constructor(begin: Iterator, end: Iterator); + /** + * @inheritdoc + */ + clear(): void; + /** + * @inheritdoc + */ + find(key: T): SetIterator; + /** + * @inheritdoc + */ + count(key: T): number; + /** + * @inheritdoc + */ + begin(): SetIterator; + /** + * @inheritdoc + */ + begin(index: number): SetIterator; + /** + * @inheritdoc + */ + end(): SetIterator; + /** + * @inheritdoc + */ + end(index: number): SetIterator; + /** + * @inheritdoc + */ + rbegin(): SetReverseIterator; + /** + * @inheritdoc + */ + rbegin(index: number): SetReverseIterator; + /** + * @inheritdoc + */ + rend(): SetReverseIterator; + /** + * @inheritdoc + */ + rend(index: number): SetReverseIterator; + /** + * @inheritdoc + */ + bucket_count(): number; + /** + * @inheritdoc + */ + bucket_size(n: number): number; + /** + * @inheritdoc + */ + max_load_factor(): number; + /** + * @inheritdoc + */ + max_load_factor(z: number): void; + /** + * @inheritdoc + */ + bucket(key: T): number; + /** + * @inheritdoc + */ + reserve(n: number): void; + /** + * @inheritdoc + */ + rehash(n: number): void; + /** + * @hidden + */ + protected _Insert_by_val(val: T): any; + /** + * @hidden + */ + protected _Insert_by_hint(hint: SetIterator, val: T): SetIterator; + /** + * @hidden + */ + protected _Insert_by_range>(first: InputIterator, last: InputIterator): void; + /** + * @hidden + */ + protected _Handle_insert(first: SetIterator, last: SetIterator): void; + /** + * @hidden + */ + protected _Handle_erase(first: SetIterator, last: SetIterator): void; + /** + * Swap content. + * + * Exchanges the content of the container by the content of obj, which is another + * {@link HashMultiSet set} of the same type. Sizes abd container type may differ. + * + * After the call to this member function, the elements in this container are those which were + * in obj before the call, and the elements of obj are those which were in this. All + * iterators, references and pointers remain valid for the swapped objects. + * + * Notice that a non-member function exists with the same name, {@link swap swap}, overloading that + * algorithm with an optimization that behaves like this member function. + * + * @param obj Another {@link HashMultiSet set container} of the same type of elements as this (i.e., + * with the same template parameters, Key and T) whose content is swapped + * with that of this {@link HashMultiSet container}. + */ + swap(obj: HashMultiSet): void; + /** + * @inheritdoc + */ + swap(obj: base.Container): void; + } +} +declare namespace std.HashSet { + type iterator = SetIterator; + type reverse_iterator = SetReverseIterator; +} +declare namespace std { + /** + * Hashed, unordered set. + * + * {@link HashSet}s are containers that store unique elements in no particular order, and which + * allow for fast retrieval of individual elements based on their value. + * + * In an {@link HashSet}, the value of an element is at the same time its key, that + * identifies it uniquely. Keys are immutable, therefore, the elements in an {@link HashSet} cannot be + * modified once in the container - they can be inserted and removed, though. + * + * Internally, the elements in the {@link HashSet} are not sorted in any particular order, but + * organized into buckets depending on their hash values to allow for fast access to individual elements + * directly by their values (with a constant average time complexity on average). + * + * {@link HashSet} containers are faster than {@link TreeSet} containers to access individual + * elements by their key, although they are generally less efficient for range iteration through a + * subset of their elements. + * + * + * + * + * ### Container properties + *
+ *
Associative
+ *
Elements in associative containers are referenced by their key and not by their absolute + * position in the container.
+ * + *
Hashed
+ *
Hashed containers organize their elements using hash tables that allow for fast access to elements + * by their key.
+ * + *
Set
+ *
The value of an element is also the key used to identify it.
+ * + *
Unique keys
+ *
No two elements in the container can have equivalent keys.
+ *
+ * + * @param Type of the elements. + * Each element in an {@link HashSet} is also uniquely identified by this value. + * + * @reference http://www.cplusplus.com/reference/unordered_set/unordered_set + * @author Jeongho Nam + */ + class HashSet extends base.UniqueSet implements base.IHashSet { + /** + * @hidden + */ + private hash_buckets_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from elements. + */ + constructor(items: T[]); + /** + * Copy Constructor. + */ + constructor(container: HashSet); + /** + * Construct from range iterators. + */ + constructor(begin: Iterator, end: Iterator); + /** + * @inheritdoc + */ + clear(): void; + /** + * @inheritdoc + */ + find(key: T): SetIterator; + /** + * @inheritdoc + */ + begin(): SetIterator; + /** + * @inheritdoc + */ + begin(index: number): SetIterator; + /** + * @inheritdoc + */ + end(): SetIterator; + /** + * @inheritdoc + */ + end(index: number): SetIterator; + /** + * @inheritdoc + */ + rbegin(): SetReverseIterator; + /** + * @inheritdoc + */ + rbegin(index: number): SetReverseIterator; + /** + * @inheritdoc + */ + rend(): SetReverseIterator; + /** + * @inheritdoc + */ + rend(index: number): SetReverseIterator; + /** + * @inheritdoc + */ + bucket_count(): number; + /** + * @inheritdoc + */ + bucket_size(n: number): number; + /** + * @inheritdoc + */ + max_load_factor(): number; + /** + * @inheritdoc + */ + max_load_factor(z: number): void; + /** + * @inheritdoc + */ + bucket(key: T): number; + /** + * @inheritdoc + */ + reserve(n: number): void; + /** + * @inheritdoc + */ + rehash(n: number): void; + /** + * @hidden + */ + protected _Insert_by_val(val: T): any; + /** + * @hidden + */ + protected _Insert_by_hint(hint: SetIterator, val: T): SetIterator; + /** + * @hidden + */ + protected _Insert_by_range>(first: InputIterator, last: InputIterator): void; + /** + * @hidden + */ + protected _Handle_insert(first: SetIterator, last: SetIterator): void; + /** + * @hidden + */ + protected _Handle_erase(first: SetIterator, last: SetIterator): void; + /** + * Swap content. + * + * Exchanges the content of the container by the content of obj, which is another + * {@link HashSet set} of the same type. Sizes abd container type may differ. + * + * After the call to this member function, the elements in this container are those which were + * in obj before the call, and the elements of obj are those which were in this. All + * iterators, references and pointers remain valid for the swapped objects. + * + * Notice that a non-member function exists with the same name, {@link swap swap}, overloading that + * algorithm with an optimization that behaves like this member function. + * + * @param obj Another {@link HashSet set container} of the same type of elements as this (i.e., + * with the same template parameters, Key and T) whose content is swapped + * with that of this {@link HashSet container}. + */ + swap(obj: HashSet): void; + /** + * @inheritdoc + */ + swap(obj: base.Container): void; + } +} +declare namespace std { + /** + * Comparable instance. + * + * {@link IComparable} is a common interface for objects who can compare each other. + * + * @reference https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html + * @author Jeongho Nam + */ + interface IComparable extends Object { + /** + * Indicates whether some other object is "equal to" this one. + * + * The {@link equal_to} method implements an equivalence relation on non-null object references: + * + *
    + *
  • + * It is reflexive: for any non-null reference value x, x.equal_to(x) + * should return true. + *
  • + *
  • + * It is symmetric: for any non-null reference values x and y, + * x.equal_to(y) should return true if and only if y.equal_to(x) + * returns true.
  • + *
  • + * It is transitive: for any non-null reference values x, y, and + * z, if x.equal_to(y) returns true and y.equal_to(z) + * returns true, then x.equal_to(z) should return true. + *
  • + *
  • + * It is consistent: for any non-null reference values x and y, multiple + * invocations of x.equal_to(y) consistently return true or consistently return + * false, provided no information used in equal_to comparisons on the objects is modified. + *
  • + *
  • + * For any non-null reference value x, x.equal_to(null) should return + * false. + *
  • + *
+ * + * The {@link equal_to} method for interface {@link IComparable} implements the most discriminating possible + * equivalence relation on objects; that is, for any non-null reference values x and + * y, this method returns true if and only if x and y + * refer to the same object (x == y has the value true). + * + * Note that it is generally necessary to override the {@link hash_code} method whenever this method is + * overridden, so as to maintain the general contract for the {@link hash_code} method, which states that + * equal objects must have equal hash codes. + * + * - {@link IComparable.equal_to} is called by {@link equal_to}. + * + * @param obj the reference object with which to compare. + * + * @return true if this object is the same as the obj argument; false otherwise. + */ + equals(obj: T): boolean; + /** + * Less-than inequality comparison. + * + * Binary method returns whether the the instance compares less than the obj. + * + *
    + *
  • + * {@link IComparable.less} is called by {@link less}. Also, this method can be used on standard + * algorithms such as {@link sort sort()}, {@link merge merge()} or + * {@link TreeMap.lower_bound lower_bound()}. + *
  • + *
+ * + * @param obj the reference object with which to compare. + * + * @return Whether the first parameter is less than the second. + */ + less(obj: T): boolean; + /** + * Issue a hash code. + * + * Returns a hash code value for the object. This method is supported for the benefit of hash tables such + * as those provided by hash containers; {@link HashSet}, {@link HashMap}, {@link MultiHashSet} and + * {@link MultiHashMap}. + * + * As much as is reasonably practical, the {@link hash_code} method defined by interface + * {@link IComparable} does return distinct integers for distinct objects. (This is typically implemented by + * converting the internal address of the object into an integer, but this implementation technique is not + * required by the JavaScript programming language.) + * + *
    + *
  • + * {@link IComparable.hash_code} is called by {@link hash_code}. If you want to keep basically + * provided hash function, then returns {@link Hash.code}; return Hash.code(this); + *
  • + *
+ * + * @return An hash code who represents the object. + */ + hashCode?(): number; + } +} +declare namespace std.List { + type iterator = ListIterator; + type reverse_iterator = ListReverseIterator; +} +declare namespace std { + /** + * Doubly linked list. + * + * {@link List}s are sequence containers that allow constant time insert and erase operations anywhere within the + * sequence, and iteration in both directions. + * + * List containers are implemented as doubly-linked lists; Doubly linked lists can store each of the elements they + * contain in different and unrelated storage locations. The ordering is kept internally by the association to each + * element of a link to the element preceding it and a link to the element following it. + * + * Compared to other base standard sequence containers (array, vector and deque), lists perform generally better + * in inserting, extracting and moving elements in any position within the container for which an iterator has already + * been obtained, and therefore also in algorithms that make intensive use of these, like sorting algorithms. + * + * The main drawback of lists and forward_lists compared to these other sequence containers is that they lack + * direct access to the elements by their position; For example, to access the sixth element in a list, one has to + * iterate from a known position (like the beginning or the end) to that position, which takes linear time in the + * distance between these. They also consume some extra memory to keep the linking information associated to each + * element (which may be an important factor for large lists of small-sized elements). + * + * + * + * + * + * ### Container properties + *
+ *
Sequence
+ *
Elements in sequence containers are ordered in a strict linear sequence. Individual elements are accessed by + * their position in this sequence.
+ * + *
Doubly-linked list
+ *
Each element keeps information on how to locate the next and the previous elements, allowing constant time + * insert and erase operations before or after a specific element (even of entire ranges), but no direct random + * access.
+ *
+ * + * @param Type of the elements. + * + * @reference http://www.cplusplus.com/reference/list/list/ + * @author Jeongho Nam + */ + class List extends base._ListContainer> { + private rend_; + /** + * Default Constructor. + * + * Constructs an empty container, with no elements. + */ + constructor(); + /** + * Initializer list Constructor. + * + * Constructs a container with a copy of each of the elements in array, in the same order. + * + * @param array An array containing elements to be copied and contained. + */ + constructor(items: Array); + /** + * Fill Constructor. + * + * Constructs a container with n elements. Each element is a copy of val (if provided). + * + * @param n Initial container size (i.e., the number of elements in the container at construction). + * @param val Value to fill the container with. Each of the n elements in the container is + * initialized to a copy of this value. + */ + constructor(size: number, val: T); + /** + * Copy Constructor. + * + * Constructs a container with a copy of each of the elements in container, in the same order. + * + * @param container Another container object of the same type (with the same class template + * arguments T), whose contents are either copied or acquired. + */ + constructor(container: List); + /** + * Range Constructor. + * + * Constructs a container with as many elements as the range (begin, end), with each + * element emplace-constructed from its corresponding element in that range, in the same order. + * + * @param begin Input interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. + */ + constructor(begin: Iterator, end: Iterator); + /** + * @hidden + */ + protected _Create_iterator(prev: ListIterator, next: ListIterator, val: T): ListIterator; + /** + * @hidden + */ + protected _Set_begin(it: ListIterator): void; + /** + * @inheritdoc + */ + assign(n: number, val: T): void; + /** + * @inheritdoc + */ + assign>(begin: InputIterator, end: InputIterator): void; + /** + * @inheritdoc + */ + rbegin(): ListReverseIterator; + /** + * @inheritdoc + */ + rend(): ListReverseIterator; + /** + * @inheritdoc + */ + front(): T; + /** + * @inheritdoc + */ + back(): T; + /** + * Insert an element. + * + * The container is extended by inserting a new element before the element at the specified + * position. This effectively increases the {@link List.size List size} by the amount of elements + * inserted. + * + * Unlike other standard sequence containers, {@link List} is specifically designed to be efficient + * inserting and removing elements in any position, even in the middle of the sequence. + * + * @param position Position in the container where the new element is inserted. + * {@link iterator}> is a member type, defined as a + * {@link ListIterator bidirectional iterator} type that points to elements. + * @param val Value to be inserted as an element. + * + * @return An iterator that points to the newly inserted element; val. + */ + insert(position: ListIterator, val: T): ListIterator; + /** + * Insert elements by repeated filling. + * + * The container is extended by inserting a new element before the element at the specified + * position. This effectively increases the {@link List.size List size} by the amount of elements + * inserted. + * + * Unlike other standard sequence containers, {@link List} is specifically designed to be efficient + * inserting and removing elements in any position, even in the middle of the sequence. + * + * @param position Position in the container where the new elements are inserted. The {@link iterator} is a + * member type, defined as a {@link ListIterator bidirectional iterator} type that points to + * elements. + * @param size Number of elements to insert. + * @param val Value to be inserted as an element. + * + * @return An iterator that points to the first of the newly inserted elements. + */ + insert(position: ListIterator, size: number, val: T): ListIterator; + /** + * Insert elements by range iterators. + * + * The container is extended by inserting a new element before the element at the specified + * position. This effectively increases the {@link List.size List size} by the amount of elements + * inserted. + * + * Unlike other standard sequence containers, {@link List} is specifically designed to be efficient + * inserting and removing elements in any position, even in the middle of the sequence. + * + * @param position Position in the container where the new elements are inserted. The {@link iterator} is a + * member type, defined as a {@link ListIterator bidirectional iterator} type that points to + * elements. + * @param begin An iterator specifying range of the begining element. + * @param end An iterator specifying range of the ending element. + * + * @return An iterator that points to the first of the newly inserted elements. + */ + insert>(position: ListIterator, begin: InputIterator, end: InputIterator): ListIterator; + /** + * Insert an element. + * + * The container is extended by inserting a new element before the element at the specified + * position. This effectively increases the {@link List.size List size} by the amount of elements + * inserted. + * + * Unlike other standard sequence containers, {@link List} is specifically designed to be efficient + * inserting and removing elements in any position, even in the middle of the sequence. + * + * @param position Position in the container where the new element is inserted. + * {@link iterator}> is a member type, defined as a + * {@link ListReverseIterator bidirectional iterator} type that points to elements. + * @param val Value to be inserted as an element. + * + * @return An iterator that points to the newly inserted element; val. + */ + insert(position: ListReverseIterator, val: T): ListReverseIterator; + /** + * Insert elements by repeated filling. + * + * The container is extended by inserting a new element before the element at the specified + * position. This effectively increases the {@link List.size List size} by the amount of elements + * inserted. + * + * Unlike other standard sequence containers, {@link List} is specifically designed to be efficient + * inserting and removing elements in any position, even in the middle of the sequence. + * + * @param position Position in the container where the new elements are inserted. The {@link iterator} is a + * member type, defined as a {@link ListReverseIterator bidirectional iterator} type that points to + * elements. + * @param size Number of elements to insert. + * @param val Value to be inserted as an element. + * + * @return An iterator that points to the first of the newly inserted elements. + */ + insert(position: ListReverseIterator, size: number, val: T): ListReverseIterator; + /** + * Insert elements by range iterators. + * + * The container is extended by inserting a new element before the element at the specified + * position. This effectively increases the {@link List.size List size} by the amount of elements + * inserted. + * + * Unlike other standard sequence containers, {@link List} is specifically designed to be efficient + * inserting and removing elements in any position, even in the middle of the sequence. + * + * @param position Position in the container where the new elements are inserted. The {@link iterator} is a + * member type, defined as a {@link ListReverseIterator bidirectional iterator} type that points to + * elements. + * @param begin An iterator specifying range of the begining element. + * @param end An iterator specifying range of the ending element. + * + * @return An iterator that points to the first of the newly inserted elements. + */ + insert>(position: ListReverseIterator, begin: InputIterator, end: InputIterator): ListReverseIterator; + /** + * Erase an element. + * + * Removes from the {@link List} either a single element; position. + * + * This effectively reduces the container size by the number of element removed. + * + * Unlike other standard sequence containers, {@link List} objects are specifically designed to be + * efficient inserting and removing elements in any position, even in the middle of the sequence. + * + * @param position Iterator pointing to a single element to be removed from the {@link List}. + * + * @return An iterator pointing to the element that followed the last element erased by the function call. + * This is the {@link end end()} if the operation erased the last element in the sequence. + */ + erase(position: ListIterator): ListIterator; + /** + * Erase elements. + * + * Removes from the {@link List} container a range of elements. + * + * This effectively reduces the container {@link size} by the number of elements removed. + * + * Unlike other standard sequence containers, {@link List} objects are specifically designed to be + * efficient inserting and removing elements in any position, even in the middle of the sequence. + * + * @param begin An iterator specifying a range of beginning to erase. + * @param end An iterator specifying a range of end to erase. + * + * @return An iterator pointing to the element that followed the last element erased by the function call. + * This is the {@link end end()} if the operation erased the last element in the sequence. + */ + erase(begin: ListIterator, end: ListIterator): ListIterator; + /** + * Erase an element. + * + * Removes from the {@link List} either a single element; position. + * + * This effectively reduces the container size by the number of element removed. + * + * Unlike other standard sequence containers, {@link List} objects are specifically designed to be + * efficient inserting and removing elements in any position, even in the middle of the sequence. + * + * @param position Iterator pointing to a single element to be removed from the {@link List}. + * + * @return An iterator pointing to the element that followed the last element erased by the function call. + * This is the {@link rend rend()} if the operation erased the last element in the sequence. + */ + erase(position: ListReverseIterator): ListReverseIterator; + /** + * Erase elements. + * + * Removes from the {@link List} container a range of elements. + * + * This effectively reduces the container {@link size} by the number of elements removed. + * + * Unlike other standard sequence containers, {@link List} objects are specifically designed to be + * efficient inserting and removing elements in any position, even in the middle of the sequence. + * + * @param begin An iterator specifying a range of beginning to erase. + * @param end An iterator specifying a range of end to erase. + * + * @return An iterator pointing to the element that followed the last element erased by the function call. + * This is the {@link rend rend()} if the operation erased the last element in the sequence. + */ + erase(begin: ListReverseIterator, end: ListReverseIterator): ListReverseIterator; + /** + * Remove duplicate values. + * + * Removes all but the first element from every consecutive group of equal elements in the + * + * Notice that an element is only removed from the {@link List} container if it compares equal to the + * element immediately preceding it. Thus, this function is especially useful for sorted lists. + */ + unique(): void; + /** + * Remove duplicate values. + * + * Removes all but the first element from every consecutive group of equal elements in the + * + * The argument binary_pred is a specific comparison function that determine the uniqueness + * of an element. In fact, any behavior can be implemented (and not only an equality comparison), but notice + * that the function will call binary_pred(it.value, it.prev().value) for all pairs of elements + * (where it is an iterator to an element, starting from the second) and remove it + * from the {@link List} if the predicate returns true. + * + * Notice that an element is only removed from the {@link List} container if it compares equal to the + * element immediately preceding it. Thus, this function is especially useful for sorted lists. + * + * @param binary_pred Binary predicate that, taking two values of the same type than those contained in the + * {@link List}, returns true to remove the element passed as first argument + * from the container, and false otherwise. This shall be a function pointer + * or a function object. + */ + unique(binary_pred: (left: T, right: T) => boolean): void; + /** + * Remove elements with specific value. + * + * Removes from the container all the elements that compare equal to val. This calls the + * destructor of these objects and reduces the container {@link size} by the number of elements removed. + * + * Unlike member function {@link List.erase}, which erases elements by their position (using an + * iterator), this function ({@link List.remove}) removes elements by their value. + * + * A similar function, {@link List.remove_if}, exists, which allows for a condition other than an + * equality comparison to determine whether an element is removed. + * + * @param val Value of the elements to be removed. + */ + remove(val: T): void; + /** + * Remove elements fulfilling condition. + * + * Removes from the container all the elements for which pred returns true. This + * calls the destructor of these objects and reduces the container {@link size} by the number of elements + * removed. + * + * The function calls pred(it.value) for each element (where it is an iterator + * to that element). Any of the elements in the list for which this returns true, are removed + * from the + * + * @param pred Unary predicate that, taking a value of the same type as those contained in the forward_list + * object, returns true for those values to be removed from the container, and + * false for those remaining. This can either be a function pointer or a function + * object. + */ + remove_if(pred: (val: T) => boolean): void; + /** + * Merge sorted {@link List Lists}. + * + * Merges obj into the {@link List} by transferring all of its elements at their respective + * ordered positions into the container (both containers shall already be ordered). + * + * + * This effectively removes all the elements in obj (which becomes {@link empty}), and inserts + * them into their ordered position within container (which expands in {@link size} by the number of elements + * transferred). The operation is performed without constructing nor destroying any element: they are + * transferred, no matter whether obj is an lvalue or an rvalue, or whether the value_type supports + * move-construction or not. + * + * This function requires that the {@link List} containers have their elements already ordered by value + * ({@link less}) before the call. For an alternative on unordered {@link List Lists}, see + * {@link List.splice}. + * + * Assuming such ordering, each element of obj is inserted at the position that corresponds to its + * value according to the strict weak ordering defined by {@link less}. The resulting order of equivalent + * elements is stable (i.e., equivalent elements preserve the relative order they had before the call, and + * existing elements precede those equivalent inserted from obj). + * + * The function does nothing if this == obj. + * + * @param obj A {@link List} object of the same type (i.e., with the same template parameters, T). + * Note that this function modifies obj no matter whether an lvalue or rvalue reference is + * passed. + */ + merge(obj: List): void; + /** + * Merge sorted {@link List Lists}. + * + * Merges obj into the {@link List} by transferring all of its elements at their respective + * ordered positions into the container (both containers shall already be ordered). + * + * + * This effectively removes all the elements in obj (which becomes {@link empty}), and inserts + * them into their ordered position within container (which expands in {@link size} by the number of elements + * transferred). The operation is performed without constructing nor destroying any element: they are + * transferred, no matter whether obj is an lvalue or an rvalue, or whether the value_type supports + * move-construction or not. + * + * The argument compare is a specific predicate to perform the comparison operation between + * elements. This comparison shall produce a strict weak ordering of the elements (i.e., a consistent + * transitive comparison, without considering its reflexiveness). + * + * This function requires that the {@link List} containers have their elements already ordered by + * compare before the call. For an alternative on unordered {@link List Lists}, see + * {@link List.splice}. + * + * Assuming such ordering, each element of obj is inserted at the position that corresponds to its + * value according to the strict weak ordering defined by compare. The resulting order of equivalent + * elements is stable (i.e., equivalent elements preserve the relative order they had before the call, and + * existing elements precede those equivalent inserted from obj). + * + * The function does nothing if this == obj. + * + * @param obj A {@link List} object of the same type (i.e., with the same template parameters, T). + * Note that this function modifies obj no matter whether an lvalue or rvalue reference is + * passed. + * @param compare Binary predicate that, taking two values of the same type than those contained in the + * {@link list}, returns true if the first argument is considered to go before + * the second in the strict weak ordering it defines, and false otherwise. + * This shall be a function pointer or a function object. + */ + merge(obj: List, compare: (left: T, right: T) => boolean): void; + /** + * Transfer elements from {@link List} to {@link List}. + * + * Transfers elements from obj into the container, inserting them at position. + * + * This effectively inserts all elements into the container and removes them from obj, altering + * the sizes of both containers. The operation does not involve the construction or destruction of any + * element. They are transferred, no matter whether obj is an lvalue or an rvalue, or whether the + * value_type supports move-construction or not. + * + * This first version (1) transfers all the elements of obj into the + * + * @param position Position within the container where the elements of obj are inserted. + * @param obj A {@link List} object of the same type (i.e., with the same template parameters, T). + */ + splice(position: ListIterator, obj: List): void; + /** + * Transfer an element from {@link List} to {@link List}. + * + * Transfers an element from obj, which is pointed by an {@link ListIterator iterator} it, + * into the container, inserting the element at specified position. + * + * This effectively inserts an element into the container and removes it from obj, altering the + * sizes of both containers. The operation does not involve the construction or destruction of any element. + * They are transferred, no matter whether obj is an lvalue or an rvalue, or whether the value_type + * supports move-construction or not. + * + * This second version (2) transfers only the element pointed by it from obj into the + * + * + * @param position Position within the container where the element of obj is inserted. + * @param obj A {@link List} object of the same type (i.e., with the same template parameters, T). + * This parameter may be this if position points to an element not actually + * being spliced. + * @param it {@link ListIterator Iterator} to an element in obj. Only this single element is + * transferred. + */ + splice(position: ListIterator, obj: List, it: ListIterator): void; + /** + * Transfer elements from {@link List} to {@link List}. + * + * Transfers elements from obj into the container, inserting them at position. + * + * This effectively inserts those elements into the container and removes them from obj, altering + * the sizes of both containers. The operation does not involve the construction or destruction of any + * element. They are transferred, no matter whether obj is an lvalue or an rvalue, or whether the + * value_type supports move-construction or not. + * + * This third version (3) transfers the range [begin, end) from obj into the + * + * + * @param position Position within the container where the elements of obj are inserted. + * @param obj A {@link List} object of the same type (i.e., with the same template parameters, T). + * This parameter may be this if position points to an element not actually + * being spliced. + * @param begin {@link ListIterator An Iterator} specifying initial position of a range of elements in + * obj. Transfers the elements in the range [begin, end) to + * position. + * @param end {@link ListIterator An Iterator} specifying final position of a range of elements in + * obj. Transfers the elements in the range [begin, end) to + * position. Notice that the range includes all the elements between begin and + * end, including the element pointed by begin but not the one pointed by end. + */ + splice(position: ListIterator, obj: List, begin: ListIterator, end: ListIterator): void; + /** + * Sort elements in + * + * Sorts the elements in the {@link List}, altering their position within the + * + * The sorting is performed by applying an algorithm that uses {@link less}. This comparison shall + * produce a strict weak ordering of the elements (i.e., a consistent transitive comparison, without + * considering its reflexiveness). + * + * The resulting order of equivalent elements is stable: i.e., equivalent elements preserve the relative + * order they had before the call. + * + * The entire operation does not involve the construction, destruction or copy of any element object. + * Elements are moved within the + */ + sort(): void; + /** + * Sort elements in + * + * Sorts the elements in the {@link List}, altering their position within the + * + * The sorting is performed by applying an algorithm that uses compare. This comparison shall + * produce a strict weak ordering of the elements (i.e., a consistent transitive comparison, without + * considering its reflexiveness). + * + * The resulting order of equivalent elements is stable: i.e., equivalent elements preserve the relative + * order they had before the call. + * + * The entire operation does not involve the construction, destruction or copy of any element object. + * Elements are moved within the + * + * @param compare Binary predicate that, taking two values of the same type of those contained in the + * {@link List}, returns true if the first argument goes before the second + * argument in the strict weak ordering it defines, and false otherwise. This + * shall be a function pointer or a function object. + */ + sort(compare: (left: T, right: T) => boolean): void; + /** + * @hidden + */ + private _Quick_sort(first, last, compare); + /** + * @hidden + */ + private _Quick_sort_partition(first, last, compare); + /** + * Reverse the order of elements. + * + * Reverses the order of the elements in the list container. + */ + reverse(): void; + /** + * Swap content. + * + * Exchanges the content of the container by the content of obj, which is another + * {@link List container} object with same type of elements. Sizes and container type may differ. + * + * After the call to this member function, the elements in this container are those which were in obj + * before the call, and the elements of obj are those which were in this. All iterators, references and + * pointers remain valid for the swapped objects. + * + * Notice that a non-member function exists with the same name, {@link swap swap}, overloading that + * algorithm with an optimization that behaves like this member function. + * + * @param obj Another {@link List container} of the same type of elements (i.e., instantiated + * with the same template parameter, T) whose content is swapped with that of this + * {@link List container}. + */ + swap(obj: List): void; + /** + * @inheritdoc + */ + swap(obj: base.Container): void; + } +} +declare namespace std { + /** + * An iterator, node of a List. + * + * + * + * + * @author Jeongho Nam + */ + class ListIterator extends base._ListIteratorBase { + /** + * Initializer Constructor. + * + * #### Note + * Do not create the iterator directly, by yourself. + * + * Use {@link List.begin begin()}, {@link List.end end()} in {@link List container} instead. + * + * @param source The source {@link List container} to reference. + * @param prev A refenrece of previous node ({@link ListIterator iterator}). + * @param next A refenrece of next node ({@link ListIterator iterator}). + * @param value Value to be stored in the node (iterator). + */ + constructor(source: List, prev: ListIterator, next: ListIterator, value: T); + /** + * @inheritdoc + */ + source(): List; + /** + * @inheritdoc + */ + /** + * Set value of the iterator is pointing to. + * + * @param val Value to set. + */ + value: T; + /** + * @inheritdoc + */ + prev(): ListIterator; + /** + * @inheritdoc + */ + next(): ListIterator; + /** + * @inheritdoc + */ + advance(step: number): ListIterator; + /** + * @inheritdoc + */ + equals(obj: ListIterator): boolean; + /** + * @inheritdoc + */ + swap(obj: ListIterator): void; + } +} +declare namespace std { + /** + * A reverse-iterator of List. + * + * + * + * + * @param Type of the elements. + * + * @author Jeongho Nam + */ + class ListReverseIterator extends ReverseIterator, ListIterator, ListReverseIterator> implements base.ILinearIterator { + /** + * Construct from base iterator. + * + * @param base A reference of the base iterator, which iterates in the opposite direction. + */ + constructor(base: ListIterator); + /** + * @hidden + */ + protected _Create_neighbor(base: ListIterator): ListReverseIterator; + /** + * @inheritdoc + */ + /** + * Set value of the iterator is pointing to. + * + * @param val Value to set. + */ + value: T; + } +} +declare namespace std.Vector { + type iterator = VectorIterator; + type reverse_iterator = VectorReverseIterator; +} +declare namespace std { + /** + * Vector, the dynamic array. + * + * {@link Vector}s are sequence containers representing arrays that can change in size. + * + * Just like arrays, {@link Vector}s use contiguous storage locations for their elements, which means that + * their elements can also be accessed using offsets on regular pointers to its elements, and just as efficiently + * as in arrays. But unlike arrays, their size can change dynamically, with their storage being handled + * automatically by the container. + * + * Internally, {@link Vector}s use a dynamically allocated array to store their elements. This array may need + * to be reallocated in order to grow in size when new elements are inserted, which implies allocating a new + * array and moving all elements to it. This is a relatively expensive task in terms of processing time, and + * thus, {@link Vector}s do not reallocate each time an element is added to the container. + * + * Compared to the other dynamic sequence containers ({@link Deque}s, {@link List}s), {@link Vector Vectors} + * are very efficient accessing its elements (just like arrays) and relatively efficient adding or removing + * elements from its end. For operations that involve inserting or removing elements at positions other than the + * end, they perform worse than the others, and have less consistent iterators and references than {@link List}s. + * + * + * + * + * + * ### Container properties + *
+ *
Sequence
+ *
+ * Elements in sequence containers are ordered in a strict linear sequence. Individual elements are + * accessed by their position in this sequence. + *
+ * + *
Dynamic array
+ *
+ * Allows direct access to any element in the sequence, even through pointer arithmetics, and provides + * relatively fast addition/removal of elements at the end of the sequence. + *
+ *
+ * + * @param Type of the elements. + * + * @reference http://www.cplusplus.com/reference/vector/vector + * @author Jeongho Nam + */ + class Vector extends base.Container implements base.IArrayContainer { + /** + * @hidden + */ + private data_; + /** + * @hidden + */ + private begin_; + /** + * @hidden + */ + private end_; + /** + * @hidden + */ + private rend_; + /** + * Default Constructor. + * + * Constructs an empty container, with no elements. + */ + constructor(); + /** + * @inheritdoc + */ + constructor(array: Array); + /** + * Initializer list Constructor. + * + * Constructs a container with a copy of each of the elements in array, in the same order. + * + * @param array An array containing elements to be copied and contained. + */ + constructor(n: number); + /** + * Fill Constructor. + * + * Constructs a container with n elements. Each element is a copy of val (if provided). + * + * @param n Initial container size (i.e., the number of elements in the container at construction). + * @param val Value to fill the container with. Each of the n elements in the container is + * initialized to a copy of this value. + */ + constructor(n: number, val: T); + /** + * Copy Constructor. + * + * Constructs a container with a copy of each of the elements in container, in the same order. + * + * @param container Another container object of the same type (with the same class template + * arguments T), whose contents are either copied or acquired. + */ + constructor(container: Vector); + /** + * Range Constructor. + * + * Constructs a container with as many elements as the range (begin, end), with each + * element emplace-constructed from its corresponding element in that range, in the same order. + * + * @param begin Input interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. + */ + constructor(begin: Iterator, end: Iterator); + /** + * @inheritdoc + */ + assign>(begin: InputIterator, end: InputIterator): void; + /** + * @inheritdoc + */ + assign(n: number, val: T): void; + /** + * @inheritdoc + */ + clear(): void; + /** + * @inheritdoc + */ + begin(): VectorIterator; + /** + * @inheritdoc + */ + end(): VectorIterator; + /** + * @inheritdoc + */ + rbegin(): VectorReverseIterator; + /** + * @inheritdoc + */ + rend(): VectorReverseIterator; + /** + * @inheritdoc + */ + size(): number; + /** + * @inheritdoc + */ + empty(): boolean; + /** + * @inheritdoc + */ + at(index: number): T; + /** + * @inheritdoc + */ + set(index: number, val: T): T; + /** + * @inheritdoc + */ + front(): T; + /** + * @inheritdoc + */ + back(): T; + /** + * Access data. + * + * Returns a direct array which is used internally by the {@link vector} to store its owned elements. + * + * @returns An array. + */ + data(): Array; + /** + * @inheritdoc + */ + push(...items: T[]): number; + /** + * @inheritdoc + */ + push_back(val: T): void; + /** + * Insert an element. + * + * The {@link Vector} is extended by inserting new element before the element at the specified + * position, effectively increasing the container size by one. + * + * Because {@link Vector}s use an Array as their underlying storage, inserting element in + * positions other than the {@link end end()} causes the container to relocate all the elements that were + * after position to its new position. This is generally an inefficient operation compared to the one + * performed for the same operation by other kinds of sequence containers (such as {@link List}). + * + * @param position Position in the {@link Vector} where the new element is inserted. + * {@link iterator} is a member type, defined as a + * {@link VectorIterator random access iterator} type that points to elements. + * @param val Value to be copied to the inserted element. + * + * @return An iterator that points to the newly inserted element. + */ + insert(position: VectorIterator, val: T): VectorIterator; + /** + * Insert elements by repeated filling. + * + * The {@link Vector} is extended by inserting new elements before the element at the specified + * position, effectively increasing the container size by the number of elements inserted. + * + * Because {@link Vector}s use an Array as their underlying storage, inserting elements in + * positions other than the {@link end end()} causes the container to relocate all the elements that were + * after position to their new positions. This is generally an inefficient operation compared to the + * one performed for the same operation by other kinds of sequence containers (such as {@link List}). + * + * @param position Position in the {@link Vector} where the new elements are inserted. + * {@link iterator} is a member type, defined as a + * {@link VectorIterator random access iterator} type that points to elements. + * @param n Number of elements to insert. Each element is initialized to a copy of val. + * @param val Value to be copied (or moved) to the inserted elements. + * + * @return An iterator that points to the first of the newly inserted elements. + */ + insert(position: VectorIterator, n: number, val: T): VectorIterator; + /** + * Insert elements by range iterators. + * + * The {@link Vector} is extended by inserting new elements before the element at the specified + * position, effectively increasing the container size by the number of elements inserted by range + * iterators. + * + * Because {@link Vector}s use an Array as their underlying storage, inserting elements in + * positions other than the {@link end end()} causes the container to relocate all the elements that were + * after position to their new positions. This is generally an inefficient operation compared to the + * one performed for the same operation by other kinds of sequence containers (such as {@link List}). + * + * @param position Position in the {@link Vector} where the new elements are inserted. + * {@link iterator} is a member type, defined as a + * {@link VectorIterator random access iterator} type that points to elements. + * @param begin Input interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. + * + * @return An iterator that points to the first of the newly inserted elements. + */ + insert>(position: VectorIterator, begin: InputIterator, end: InputIterator): VectorIterator; + /** + * Insert an element. + * + * The {@link Vector} is extended by inserting new element before the element at the specified + * position, effectively increasing the container size by one. + * + * Because {@link Vector}s use an Array as their underlying storage, inserting element in + * positions other than the {@link end end()} causes the container to relocate all the elements that were + * after position to its new position. This is generally an inefficient operation compared to the one + * performed for the same operation by other kinds of sequence containers (such as {@link List}). + * + * @param position Position in the {@link Vector} where the new element is inserted. + * {@link iterator} is a member type, defined as a + * {@link VectorIterator random access iterator} type that points to elements. + * @param val Value to be copied to the inserted element. + * + * @return An iterator that points to the newly inserted element. + */ + insert(position: VectorReverseIterator, val: T): VectorReverseIterator; + /** + * Insert elements by repeated filling. + * + * The {@link Vector} is extended by inserting new elements before the element at the specified + * position, effectively increasing the container size by the number of elements inserted. + * + * Because {@link Vector}s use an Array as their underlying storage, inserting elements in + * positions other than the {@link end end()} causes the container to relocate all the elements that were + * after position to their new positions. This is generally an inefficient operation compared to the + * one performed for the same operation by other kinds of sequence containers (such as {@link List}). + * + * @param position Position in the {@link Vector} where the new elements are inserted. + * {@link iterator} is a member type, defined as a + * {@link VectorIterator random access iterator} type that points to elements. + * @param n Number of elements to insert. Each element is initialized to a copy of val. + * @param val Value to be copied (or moved) to the inserted elements. + * + * @return An iterator that points to the first of the newly inserted elements. + */ + insert(position: VectorReverseIterator, n: number, val: T): VectorReverseIterator; + /** + * Insert elements by range iterators. + * + * The {@link Vector} is extended by inserting new elements before the element at the specified + * position, effectively increasing the container size by the number of elements inserted by range + * iterators. + * + * Because {@link Vector}s use an Array as their underlying storage, inserting elements in + * positions other than the {@link end end()} causes the container to relocate all the elements that were + * after position to their new positions. This is generally an inefficient operation compared to the + * one performed for the same operation by other kinds of sequence containers (such as {@link List}). + * + * @param position Position in the {@link Vector} where the new elements are inserted. + * {@link iterator} is a member type, defined as a + * {@link VectorIterator random access iterator} type that points to elements. + * @param begin Input interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. + * + * @return An iterator that points to the first of the newly inserted elements. + */ + insert>(position: VectorReverseIterator, begin: InputIterator, end: InputIterator): VectorReverseIterator; + /** + * @hidden + */ + private _Insert_by_val(position, val); + /** + * @hidden + */ + private _Insert_by_repeating_val(position, n, val); + /** + * @hidden + */ + protected _Insert_by_range>(position: VectorIterator, first: InputIterator, last: InputIterator): VectorIterator; + /** + * @inheritdoc + */ + pop_back(): void; + /** + * Erase element. + * + * Removes from the {@link Vector} either a single element; position. + * + * This effectively reduces the container size by the number of element removed. + * + * Because {@link Vector}s use an Array as their underlying storage, erasing an element in + * position other than the {@link end end()} causes the container to relocate all the elements after the + * segment erased to their new positions. This is generally an inefficient operation compared to the one + * performed for the same operation by other kinds of sequence containers (such as {@link List}). + * + * @param position Iterator pointing to a single element to be removed from the {@link Vector}. + * + * @return An iterator pointing to the new location of the element that followed the last element erased by + * the function call. This is the {@link end end()} if the operation erased the last element in the + * sequence. + */ + erase(position: VectorIterator): VectorIterator; + /** + * Erase element. + * + * Removes from the Vector either a single element; position. + * + * This effectively reduces the container size by the number of elements removed. + * + * Because {@link Vector}s use an Array as their underlying storage, erasing elements in + * position other than the {@link end end()} causes the container to relocate all the elements after the + * segment erased to their new positions. This is generally an inefficient operation compared to the one + * performed for the same operation by other kinds of sequence containers (such as {@link List}). + * + * @param begin An iterator specifying a range of beginning to erase. + * @param end An iterator specifying a range of end to erase. + * + * @return An iterator pointing to the new location of the element that followed the last element erased by + * the function call. This is the {@link rend rend()} if the operation erased the last element in the + * sequence. + */ + erase(first: VectorIterator, last: VectorIterator): VectorIterator; + /** + * Erase element. + * + * Removes from the {@link Vector} either a single element; position. + * + * This effectively reduces the container size by the number of element removed. + * + * Because {@link Vector}s use an Array as their underlying storage, erasing an element in + * position other than the {@link end end()} causes the container to relocate all the elements after the + * segment erased to their new positions. This is generally an inefficient operation compared to the one + * performed for the same operation by other kinds of sequence containers (such as {@link List}). + * + * @param position Iterator pointing to a single element to be removed from the {@link Vector}. + * + * @return An iterator pointing to the new location of the element that followed the last element erased by + * the function call. This is the {@link rend rend()} if the operation erased the last element in the + * sequence. + */ + erase(position: VectorReverseIterator): VectorReverseIterator; + /** + * Erase element. + * + * Removes from the Vector either a single element; position. + * + * This effectively reduces the container size by the number of elements removed. + * + * Because {@link Vector}s use an Array as their underlying storage, erasing elements in + * position other than the {@link end end()} causes the container to relocate all the elements after the + * segment erased to their new positions. This is generally an inefficient operation compared to the one + * performed for the same operation by other kinds of sequence containers (such as {@link List}). + * + * @param begin An iterator specifying a range of beginning to erase. + * @param end An iterator specifying a range of end to erase. + * + * @return An iterator pointing to the new location of the element that followed the last element erased by + * the function call. This is the {@link end end()} if the operation erased the last element in the + * sequence. + */ + erase(first: VectorReverseIterator, last: VectorReverseIterator): VectorReverseIterator; + /** + * @hidden + */ + protected _Erase_by_range(first: VectorIterator, last: VectorIterator): VectorIterator; + /** + * Swap content. + * + * Exchanges the content of the container by the content of obj, which is another + * {@link Vector container} object with same type of elements. Sizes and container type may differ. + * + * After the call to this member function, the elements in this container are those which were in obj + * before the call, and the elements of obj are those which were in this. All iterators, references and + * pointers remain valid for the swapped objects. + * + * Notice that a non-member function exists with the same name, {@link swap swap}, overloading that + * algorithm with an optimization that behaves like this member function. + * + * @param obj Another {@link Vector container} of the same type of elements (i.e., instantiated + * with the same template parameter, T) whose content is swapped with that of this + * {@link Vector container}. + */ + swap(obj: Vector): void; + /** + * @inheritdoc + */ + swap(obj: base.Container): void; + } +} +declare namespace std { + /** + * An iterator of Vector. + * + * + * + * + * @param Type of the elements. + * + * @author Jeongho Nam + */ + class VectorIterator extends Iterator implements base.IArrayIterator { + /** + * @hidden + */ + private index_; + /** + * Construct from the source {@link Vector container}. + * + * #### Note + * Do not create the iterator directly, by yourself. + * + * Use {@link Vector.begin begin()}, {@link Vector.end end()} in {@link Vector container} instead. + * + * @param source The source {@link Vector container} to reference. + * @param index Sequence number of the element in the source {@link Vector}. + */ + constructor(source: Vector, index: number); + /** + * @inheritdoc + */ + source(): Vector; + /** + * @inheritdoc + */ + index(): number; + /** + * @inheritdoc + */ + /** + * Set value of the iterator is pointing to. + * + * @param val Value to set. + */ + value: T; + /** + * @inheritdoc + */ + prev(): VectorIterator; + /** + * @inheritdoc + */ + next(): VectorIterator; + /** + * @inheritdoc + */ + advance(n: number): VectorIterator; + /** + * @inheritdoc + */ + equals(obj: VectorIterator): boolean; + /** + * @inheritdoc + */ + swap(obj: VectorIterator): void; + } +} +declare namespace std { + /** + * A reverse-iterator of Vector. + * + * + * + * + * @param Type of the elements. + * + * @author Jeongho Nam + */ + class VectorReverseIterator extends ReverseIterator, VectorIterator, VectorReverseIterator> implements base.IArrayIterator { + /** + * Construct from base iterator. + * + * @param base A reference of the base iterator, which iterates in the opposite direction. + */ + constructor(base: VectorIterator); + /** + * @hidden + */ + protected _Create_neighbor(base: VectorIterator): VectorReverseIterator; + /** + * @inheritdoc + */ + index(): number; + /** + * @inheritdoc + */ + /** + * Set value of the iterator is pointing to. + * + * @param val Value to set. + */ + value: T; + } +} +declare namespace std { + /** + * FIFO queue. + * + * {@link Queue}s are a type of container adaptor, specifically designed to operate in a FIFO context + * (first-in first-out), where elements are inserted into one end of the container and extracted from the other. + * + * {@link Queue}s are implemented as containers adaptors, which are classes that use an encapsulated object of + * a specific container class as its underlying container, providing a specific set of member functions to access + * its elements. Elements are pushed into the {@link IDeque.back back()} of the specific container and popped from + * its {@link IDeque.front front()}. + * + * {@link container_ The underlying container} may be one of the standard container class template or some + * other specifically designed container class. This underlying container shall support at least the following + * operations: + * + * - {@link IDequeContainer.empty empty} + * - {@link IDequeContainer.size size} + * - {@link IDequeContainer.front front} + * - {@link IDequeContainer.back back} + * - {@link IDequeContainer.push_back push_back} + * - {@link IDequeContainer.pop_front pop_front} + * + * The standard container classes {@link Deque} and {@link List} fulfill these requirements. + * By default, if no container class is specified for a particular {@link Queue} class instantiation, the standard + * container {@link List} is used. + * + * + * + * + * @param Type of elements. + * + * @reference http://www.cplusplus.com/reference/queue/queue + * @author Jeongho Nam + */ + class Queue { + /** + * The underlying object for implementing the FIFO + */ + private container_; + /** + * Default Constructor. + */ + constructor(); + /** + * Copy Constructor. + */ + constructor(container: Queue); + /** + * Return size. + * + * Returns the number of elements in the {@link Queue}. + * + * This member function effectively calls member {@link IDeque.size size()} of the + * {@link container_ underlying container} object. + * + * @return The number of elements in the {@link container_ underlying container}. + */ + size(): number; + /** + * Test whether container is empty. + * + * returns whether the {@link Queue} is empty: i.e. whether its size is zero. + * + * This member function efeectively calls member {@link IDeque.empty empty()} of the + * {@link container_ underlying container} object. + * + * @return true if the {@link container_ underlying container}'s size is 0, + * false otherwise. + */ + empty(): boolean; + /** + * Access next element. + * + * Returns a value of the next element in the {@link Queue}. + * + * The next element is the "oldest" element in the {@link Queue} and the same element that is popped out + * from the queue when {@link pop Queue.pop()} is called. + * + * This member function effectively calls member {@link IDeque.front front()} of the + * {@link container_ underlying container} object. + * + * @return A value of the next element in the {@link Queue}. + */ + front(): T; + /** + * Access last element. + * + * Returns a vaue of the last element in the queue. This is the "newest" element in the queue (i.e. the + * last element pushed into the queue). + * + * This member function effectively calls the member function {@link IDeque.back back()} of the + * {@link container_ underlying container} object. + * + * @return A value of the last element in the {@link Queue}. + */ + back(): T; + /** + * Insert element. + * + * Inserts a new element at the end of the {@link Queue}, after its current last element. + * The content of this new element is initialized to val. + * + * This member function effectively calls the member function {@link IDeque.push_back push_back()} of the + * {@link container_ underlying container} object. + * + * @param val Value to which the inserted element is initialized. + */ + push(val: T): void; + /** + * Remove next element. + * + * Removes the next element in the {@link Queue}, effectively reducing its size by one. + * + * The element removed is the "oldest" element in the {@link Queue} whose value can be retrieved by calling + * member {@link front Queue.front()}. + * + * This member function effectively calls the member function {@link IDeque.pop_front pop_front()} of the + * {@link container_ underlying container} object. + */ + pop(): void; + /** + * Swap contents. + * + * Exchanges the contents of the container adaptor (this) by those of obj. + * + * This member function calls the non-member function {@link Container.swap swap} (unqualified) to swap + * the {@link container_ underlying containers}. + * + * @param obj Another {@link Queue} container adaptor of the same type (i.e., instantiated with the same + * template parameter, T). Sizes may differ. + */ + swap(obj: Queue): void; + } +} +declare namespace std { + /** + * Priority queue. + * + * {@link PriorityQueue Priority queues} are a type of container adaptors, specifically designed such that its + * first element is always the greatest of the elements it contains, according to some strict weak ordering + * criterion. + * + * This context is similar to a heap, where elements can be inserted at any moment, and only the + * max heap element can be retrieved (the one at the top in the {@link PriorityQueue priority queue}). + * + * {@link PriorityQueue Priority queues} are implemented as container adaptors, which are classes that + * use an encapsulated object of a specific container class as its {@link container_ underlying container}, + * providing a specific set of member functions to access its elements. Elements are popped from the "back" + * of the specific container, which is known as the top of the {@link PriorityQueue Priority queue}. + * + * The {@link container_ underlying container} may be any of the standard container class templates or some + * other specifically designed container class. The container shall be accessible through + * {@link IArrayIterator random access iterators} and support the following operations: + * + * - {@link IArrayContainer.empty empty()} + * - {@link IArrayContainer.size size()} + * - {@link IArrayContainer.front front()} + * - {@link IArrayContainer.push_back push_back()} + * - {@link IArrayContainer.pop_back pop_back()} + * + * The standard container classes {@link Vector} and {@link Deque} fulfill these requirements. By default, if + * no container class is specified for a particular {@link PriorityQueue} class instantiation, the standard + * container {@link Vector} is used. + * + * Support of {@link IArrayIterator random access iterators} is required to keep a heap structure internally + * at all times. This is done automatically by the container adaptor by automatically calling the algorithm + * functions make_heap, push_heap and pop_heap when needed. + * + * @param Type of the elements. + * + * @reference http://www.cplusplus.com/reference/queue/priority_queue/ + * @author Jeongho Nam + */ + class PriorityQueue { + /** + * @hidden + */ + private container_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from compare. + * + * @param compare A binary predicate determines order of elements. + */ + constructor(compare: (left: T, right: T) => boolean); + /** + * Contruct from elements. + * + * @param array Elements to be contained. + */ + constructor(array: Array); + /** + * Contruct from elements with compare. + * + * @param array Elements to be contained. + * @param compare A binary predicate determines order of elements. + */ + constructor(array: Array, compare: (left: T, right: T) => boolean); + /** + * Copy Constructor. + */ + constructor(container: base.Container); + /** + * Copy Constructor with compare. + * + * @param container A container to be copied. + * @param compare A binary predicate determines order of elements. + */ + constructor(container: base.Container, compare: (left: T, right: T) => boolean); + /** + * Range Constructor. + * + * @param begin Input interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. + */ + constructor(begin: Iterator, end: Iterator); + /** + * Range Constructor with compare. + * + * @param begin Input interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. + * @param compare A binary predicate determines order of elements. + */ + constructor(begin: Iterator, end: Iterator, compare: (left: T, right: T) => boolean); + /** + * Return size. + * + * Returns the number of elements in the {@link PriorityQueue}. + * + * This member function effectively calls member {@link IArrayContainer.size size} of the + * {@link IArrayContainer underlying container} object. + * + * @return The number of elements in the underlying + */ + size(): number; + /** + * Test whether container is empty. + * + * Returns whether the {@link PriorityQueue} is empty: i.e. whether its {@link size} is zero. + * + * This member function effectively calls member {@link IARray.empty empty} of the + * {@link IArrayContainer underlying container} object. + */ + empty(): boolean; + /** + * Access top element. + * + * Returns a constant reference to the top element in the {@link PriorityQueue}. + * + * The top element is the element that compares higher in the {@link PriorityQueue}, and the next that is + * removed from the container when {@link PriorityQueue.pop} is called. + * + * This member function effectively calls member {@link IArrayContainer.front front} of the + * {@link IArrayContainer underlying container} object. + * + * @return A reference to the top element in the {@link PriorityQueue}. + */ + top(): T; + /** + * Insert element. + * + * Inserts a new element in the {@link PriorityQueue}. The content of this new element is initialized to + * val. + * + * This member function effectively calls the member function {@link IArrayContainer.push_back push_back} of the + * {@link IArrayContainer underlying container} object, and then reorders it to its location in the heap by calling + * the push_heap algorithm on the range that includes all the elements of the + * + * @param val Value to which the inserted element is initialized. + */ + push(val: T): void; + /** + * Remove top element. + * + * Removes the element on top of the {@link PriorityQueue}, effectively reducing its {@link size} by one. + * The element removed is the one with the highest (or lowest) value. + * + * The value of this element can be retrieved before being popped by calling member + * {@link PriorityQueue.top}. + * + * This member function effectively calls the pop_heap algorithm to keep the heap property of + * {@link PriorityQueue PriorityQueues} and then calls the member function {@link IArrayContainer.pop_back pop_back} of + * the {@link IArrayContainer underlying container} object to remove the element. + */ + pop(): void; + /** + * Swap contents. + * + * Exchanges the contents of the container adaptor by those of obj, swapping both the + * {@link IArrayContainer underlying container} value and their comparison function using the corresponding + * {@link swap swap} non-member functions (unqualified). + * + * This member function has a noexcept specifier that matches the combined noexcept of the + * {@link IArrayContainer.swap swap} operations on the {@link IArrayContainer underlying container} and the comparison + * functions. + * + * @param obj {@link PriorityQueue} container adaptor of the same type (i.e., instantiated with the same + * template parameters, T). Sizes may differ. + */ + swap(obj: PriorityQueue): void; + } +} +declare namespace std { + /** + * LIFO stack. + * + * {@link Stack}s are a type of container adaptor, specifically designed to operate in a LIFO context + * (last-in first-out), where elements are inserted and extracted only from one end of the + * + * {@link Stack}s are implemented as containers adaptors, which are classes that use an encapsulated object of + * a specific container class as its underlying container, providing a specific set of member functions to + * access its elements. Elements are pushed/popped from the {@link ILinearContainer.back back()} of the + * {@link ILinearContainer specific container}, which is known as the top of the {@link Stack}. + * + * {@link container_ The underlying container} may be any of the standard container class templates or some + * other specifically designed container class. The container shall support the following operations: + * + * - {@link ILinearContainer.empty empty} + * - {@link ILinearContainer.size size} + * - {@link ILinearContainer.front front} + * - {@link ILinearContainer.back back} + * - {@link ILinearContainer.push_back push_back} + * - {@link ILinearContainer.pop_back pop_back} + * + * The standard container classes {@link Vector}, {@link Deque} and {@link List} fulfill these requirements. + * By default, if no container class is specified for a particular {@link Stack} class instantiation, the standard + * container {@link List} is used. + * + * + * + * + * @param Type of elements. + * + * @reference http://www.cplusplus.com/reference/stack/stack + * @author Jeongho Nam + */ + class Stack { + /** + * The underlying object for implementing the LIFO + */ + private container_; + /** + * Default Constructor. + */ + constructor(); + /** + * Copy Constructor. + */ + constructor(stack: Stack); + /** + * Return size. + * + * Returns the number of elements in the {@link Stack}. + * + * This member function effectively calls member {@link ILinearContainer.size size()} of the + * {@link container_ underlying container} object. + * + * @return The number of elements in the {@link container_ underlying container}. + */ + size(): number; + /** + * Test whether container is empty. + * + * returns whether the {@link Stack} is empty: i.e. whether its size is zero. + * + * This member function effectively calls member {@link ILinearContainer.empty empty()} of the + * {@link container_ underlying container} object. + * + * @return true if the underlying container's size is 0, + * false otherwise. + */ + empty(): boolean; + /** + * Access next element. + * + * Returns a value of the top element in the {@link Stack}. + * + * Since {@link Stack}s are last-in first-out containers, the top element is the last element inserted into + * the {@link Stack}. + * + * This member function effectively calls member {@link ILinearContainer.back back()} of the + * {@link container_ underlying container} object. + * + * @return A value of the top element in the {@link Stack}. + */ + top(): T; + /** + * Insert element. + * + * Inserts a new element at the top of the {@link Stack}, above its current top element. + * + * This member function effectively calls the member function + * {@link ILinearContainer.push_back push_back()} of the {@link container_ underlying container} object. + * + * @param val Value to which the inserted element is initialized. + */ + push(val: T): void; + /** + * Remove top element. + * + * Removes the element on top of the {@link Stack}, effectively reducing its size by one. + * + * The element removed is the latest element inserted into the {@link Stack}, whose value can be retrieved + * by calling member {@link top Stack.top()}. + * + * This member function effectively calls the member function {@link ILinearContainer.pop_back pop_back()} + * of the {@link container_ underlying container} object. + */ + pop(): void; + /** + * Swap contents. + * + * Exchanges the contents of the container adaptor (this) by those of obj. + * + * This member function calls the non-member function {@link Container.swap swap} (unqualified) to swap + * the {@link container_ underlying containers}. + * + * @param obj Another {@link Stack} container adaptor of the same type (i.e., instantiated with the same + * template parameter, T). Sizes may differ. + */ + swap(obj: Stack): void; + } +} +declare namespace std.TreeSet { + type iterator = SetIterator; + type reverse_iterator = SetReverseIterator; +} +declare namespace std { + /** + * Tree-structured set, std::set of STL. + * + * {@link TreeSet}s are containers that store unique elements following a specific order. + * + * In a {@link TreeSet}, the value of an element also identifies it (the value is itself the + * key, of type T), and each value must be unique. The value of the elements in a + * {@link TreeSet} cannot be modified once in the container (the elements are always const), but they + * can be inserted or removed from the container. + * + * Internally, the elements in a {@link TreeSet} are always sorted following a specific strict weak + * ordering criterion indicated by its internal comparison method (of {@link less}). + * + * {@link TreeSet} containers are generally slower than {@link HashSet} containers to access + * individual elements by their key, but they allow the direct iteration on subsets based on their + * order. + * + * {@link TreeSet}s are typically implemented as binary search trees. + * + * + *

+ * + * ### Container properties + *
+ *
Associative
+ *
+ * Elements in associative containers are referenced by their key and not by their absolute + * position in the container. + *
+ * + *
Ordered
+ *
+ * The elements in the container follow a strict order at all times. All inserted elements are + * given a position in this order. + *
+ * + *
Set
+ *
The value of an element is also the key used to identify it.
+ * + *
Unique keys
+ *
No two elements in the container can have equivalent keys.
+ *
+ * + * @param Type of the elements. + * Each element in an {@link TreeSet} is also uniquely identified by this value. + * + * @reference http://www.cplusplus.com/reference/set/set + * @author Jeongho Nam + */ + class TreeSet extends base.UniqueSet implements base.ITreeSet { + /** + * @hidden + */ + private tree_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from compare. + * + * @param compare A binary predicate determines order of elements. + */ + constructor(compare: (x: T, y: T) => boolean); + /** + * Contruct from elements. + * + * @param array Elements to be contained. + */ + constructor(array: Array); + /** + * Contruct from elements with compare. + * + * @param array Elements to be contained. + * @param compare A binary predicate determines order of elements. + */ + constructor(array: Array, compare: (x: T, y: T) => boolean); + /** + * Copy Constructor. + */ + constructor(container: TreeMultiSet); + /** + * Copy Constructor with compare. + * + * @param container A container to be copied. + * @param compare A binary predicate determines order of elements. + */ + constructor(container: TreeMultiSet, compare: (x: T, y: T) => boolean); + /** + * Range Constructor. + * + * @param begin Input interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. + */ + constructor(begin: Iterator, end: Iterator); + /** + * Construct from range and compare. + * + * @param begin Input interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. + * @param compare A binary predicate determines order of elements. + */ + constructor(begin: Iterator, end: Iterator, compare: (x: T, y: T) => boolean); + /** + * @inheritdoc + */ + clear(): void; + /** + * @inheritdoc + */ + find(val: T): SetIterator; + /** + * @inheritdoc + */ + key_comp(): (x: T, y: T) => boolean; + /** + * @inheritdoc + */ + value_comp(): (x: T, y: T) => boolean; + /** + * @inheritdoc + */ + lower_bound(val: T): SetIterator; + /** + * @inheritdoc + */ + upper_bound(val: T): SetIterator; + /** + * @inheritdoc + */ + equal_range(val: T): Pair, SetIterator>; + /** + * @hidden + */ + protected _Insert_by_val(val: T): any; + protected _Insert_by_hint(hint: SetIterator, val: T): SetIterator; + /** + * @hidden + */ + protected _Insert_by_range>(first: InputIterator, last: InputIterator): void; + /** + * @hidden + */ + protected _Handle_insert(first: SetIterator, last: SetIterator): void; + /** + * @hidden + */ + protected _Handle_erase(first: SetIterator, last: SetIterator): void; + /** + * Swap content. + * + * Exchanges the content of the container by the content of obj, which is another + * {@link TreeSet set} of the same type. Sizes abd container type may differ. + * + * After the call to this member function, the elements in this container are those which were + * in obj before the call, and the elements of obj are those which were in this. All + * iterators, references and pointers remain valid for the swapped objects. + * + * Notice that a non-member function exists with the same name, {@link swap swap}, overloading that + * algorithm with an optimization that behaves like this member function. + * + * @param obj Another {@link TreeSet set container} of the same type of elements as this (i.e., + * with the same template parameters, Key and T) whose content is swapped + * with that of this {@link TreeSet container}. + */ + swap(obj: TreeSet): void; + /** + * @inheritdoc + */ + swap(obj: base.Container): void; + } +} +declare namespace std.TreeMap { + type iterator = MapIterator; + type reverse_iterator = MapReverseIterator; +} +declare namespace std { + /** + * Tree-structured map, std::map of STL. + * + * {@link TreeMap TreeMaps} are associative containers that store elements formed by a combination of a + * key value (Key) and a mapped value (T), following order. + * + * In a {@link TreeMap}, the key values are generally used to sort and uniquely identify the elements, + * while the mapped values store the content associated to this key. The types of key and + * mapped value may differ, and are grouped together in member type value_type, which is a {@link Pair} + * type combining both: + * + * typedef Pair value_type; + * + * Internally, the elements in a {@link TreeMap} are always sorted by its key following a + * strict weak ordering criterion indicated by its internal comparison method {@link less}. + * + * {@link TreeMap} containers are generally slower than {@link HashMap HashMap} containers to access individual + * elements by their key, but they allow the direct iteration on subsets based on their order. + * + * {@link TreeMap}s are typically implemented as binary search trees. + * + * + *

+ * + * ### Container properties + *
+ *
Associative
+ *
Elements in associative containers are referenced by their key and not by their absolute + * position in the container.
+ * + *
Ordered
+ *
The elements in the container follow a strict order at all times. All inserted elements are + * given a position in this order.
+ * + *
Map
+ *
Each element associates a key to a mapped value: + * Keys are meant to identify the elements whose main content is the mapped value.
+ * + *
Unique keys
+ *
No two elements in the container can have equivalent keys.
+ *
+ * + * @param Type of the keys. Each element in a map is uniquely identified by its key value. + * @param Type of the mapped value. Each element in a map stores some data as its mapped value. + * + * @reference http://www.cplusplus.com/reference/map/map + * @author Jeongho Nam + */ + class TreeMap extends base.UniqueMap implements base.ITreeMap { + /** + * @hidden + */ + private tree_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from compare. + * + * @param compare A binary predicate determines order of elements. + */ + constructor(compare: (x: Key, y: Key) => boolean); + /** + * Contruct from elements. + * + * @param array Elements to be contained. + */ + constructor(array: Array>); + /** + * Contruct from elements. + * + * @param array Elements to be contained. + * @param compare A binary predicate determines order of elements. + */ + constructor(array: Array>, compare: (x: Key, y: Key) => boolean); + /** + * Contruct from tuples. + * + * @param array Tuples to be contained. + */ + constructor(array: Array<[Key, T]>); + /** + * Contruct from tuples. + * + * @param array Tuples to be contained. + * @param compare A binary predicate determines order of elements. + */ + constructor(array: Array<[Key, T]>, compare: (x: Key, y: Key) => boolean); + /** + * Copy Constructor. + * + * @param container Another map to copy. + */ + constructor(container: TreeMap); + /** + * Copy Constructor. + * + * @param container Another map to copy. + * @param compare A binary predicate determines order of elements. + */ + constructor(container: TreeMap, compare: (x: Key, y: Key) => boolean); + /** + * Range Constructor. + * + * @param begin nput interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. + */ + constructor(begin: Iterator>, end: Iterator>); + /** + * Range Constructor. + * + * @param begin nput interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. + * @param compare A binary predicate determines order of elements. + */ + constructor(begin: Iterator>, end: Iterator>, compare: (x: Key, y: Key) => boolean); + /** + * @inheritdoc + */ + clear(): void; + /** + * @inheritdoc + */ + find(key: Key): MapIterator; + /** + * @inheritdoc + */ + key_comp(): (x: Key, y: Key) => boolean; + /** + * @inheritdoc + */ + value_comp(): (x: Pair, y: Pair) => boolean; + /** + * @inheritdoc + */ + lower_bound(key: Key): MapIterator; + /** + * @inheritdoc + */ + upper_bound(key: Key): MapIterator; + /** + * @inheritdoc + */ + equal_range(key: Key): Pair, MapIterator>; + /** + * @hidden + */ + protected _Insert_by_pair(pair: Pair): any; + /** + * @hidden + */ + protected _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; + /** + * @hidden + */ + protected _Insert_by_range>>(first: InputIterator, last: InputIterator): void; + /** + * @hidden + */ + protected _Handle_insert(first: MapIterator, last: MapIterator): void; + /** + * @hidden + */ + protected _Handle_erase(first: MapIterator, last: MapIterator): void; + /** + * Swap content. + * + * Exchanges the content of the container by the content of obj, which is another + * {@link TreeMap map} of the same type. Sizes abd container type may differ. + * + * After the call to this member function, the elements in this container are those which were + * in obj before the call, and the elements of obj are those which were in this. All + * iterators, references and pointers remain valid for the swapped objects. + * + * Notice that a non-member function exists with the same name, {@link swap swap}, overloading that + * algorithm with an optimization that behaves like this member function. + * + * @param obj Another {@link TreeMap map container} of the same type of elements as this (i.e., + * with the same template parameters, Key and T) whose content is swapped + * with that of this {@link TreeMap container}. + */ + swap(obj: TreeMap): void; + /** + * @inheritdoc + */ + swap(obj: base.Container>): void; + } +} +declare namespace std.TreeMultiSet { + type iterator = SetIterator; + type reverse_iterator = SetReverseIterator; +} +declare namespace std { + /** + * Tree-structured multiple-key set. + * + * {@link TreeMultiSet TreeMultiSets} are containers that store elements following a specific order, and + * where multiple elements can have equivalent values. + * + * In a {@link TreeMultiSet}, the value of an element also identifies it (the value is itself + * the key, of type T). The value of the elements in a {@link TreeMultiSet} cannot + * be modified once in the container (the elements are always const), but they can be inserted or removed + * from the container. + * + * Internally, the elements in a {@link TreeMultiSet TreeMultiSets} are always sorted following a strict + * weak ordering criterion indicated by its internal comparison method (of {@link IComparable.less less}). + * + * {@link TreeMultiSet} containers are generally slower than {@link HashMultiSet} containers + * to access individual elements by their key, but they allow the direct iteration on subsets based on + * their order. + * + * {@link TreeMultiSet TreeMultiSets} are typically implemented as binary search trees. + * + * + *

+ * + * ### Container properties + *
+ *
Associative
+ *
+ * Elements in associative containers are referenced by their key and not by their absolute + * position in the container. + *
+ * + *
Ordered
+ *
+ * The elements in the container follow a strict order at all times. All inserted elements are + * given a position in this order. + *
+ * + *
Set
+ *
The value of an element is also the key used to identify it.
+ * + *
Multiple equivalent keys
+ *
Multiple elements in the container can have equivalent keys.
+ *
+ * + * @param Type of the elements. Each element in a {@link TreeMultiSet} container is also identified + * by this value (each value is itself also the element's key). + * + * @reference http://www.cplusplus.com/reference/set/multiset + * @author Jeongho Nam + */ + class TreeMultiSet extends base.MultiSet implements base.ITreeSet { + /** + * @hidden + */ + private tree_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from compare. + * + * @param compare A binary predicate determines order of elements. + */ + constructor(compare: (x: T, y: T) => boolean); + /** + * Contruct from elements. + * + * @param array Elements to be contained. + */ + constructor(array: Array); + /** + * Contruct from elements with compare. + * + * @param array Elements to be contained. + * @param compare A binary predicate determines order of elements. + */ + constructor(array: Array, compare: (x: T, y: T) => boolean); + /** + * Copy Constructor. + */ + constructor(container: TreeMultiSet); + /** + * Copy Constructor with compare. + * + * @param container A container to be copied. + * @param compare A binary predicate determines order of elements. + */ + constructor(container: TreeMultiSet, compare: (x: T, y: T) => boolean); + /** + * Range Constructor. + * + * @param begin Input interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. + */ + constructor(begin: Iterator, end: Iterator); + /** + * Construct from range and compare. + * + * @param begin Input interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. + * @param compare A binary predicate determines order of elements. + */ + constructor(begin: Iterator, end: Iterator, compare: (x: T, y: T) => boolean); + /** + * @inheritdoc + */ + clear(): void; + /** + * @inheritdoc + */ + find(val: T): SetIterator; + /** + * @inheritdoc + */ + count(val: T): number; + /** + * @inheritdoc + */ + key_comp(): (x: T, y: T) => boolean; + /** + * @inheritdoc + */ + value_comp(): (x: T, y: T) => boolean; + /** + * @inheritdoc + */ + lower_bound(val: T): SetIterator; + /** + * @inheritdoc + */ + upper_bound(val: T): SetIterator; + /** + * @inheritdoc + */ + equal_range(val: T): Pair, SetIterator>; + /** + * @hidden + */ + protected _Insert_by_val(val: T): any; + /** + * @hidden + */ + protected _Insert_by_hint(hint: SetIterator, val: T): SetIterator; + /** + * @hidden + */ + protected _Insert_by_range>(first: InputIterator, last: InputIterator): void; + /** + * @hidden + */ + protected _Handle_insert(first: SetIterator, last: SetIterator): void; + /** + * @hidden + */ + protected _Handle_erase(first: SetIterator, last: SetIterator): void; + /** + * Swap content. + * + * Exchanges the content of the container by the content of obj, which is another + * {@link TreeMultiSet set} of the same type. Sizes abd container type may differ. + * + * After the call to this member function, the elements in this container are those which were + * in obj before the call, and the elements of obj are those which were in this. All + * iterators, references and pointers remain valid for the swapped objects. + * + * Notice that a non-member function exists with the same name, {@link swap swap}, overloading that + * algorithm with an optimization that behaves like this member function. + * + * @param obj Another {@link TreeMultiSet set container} of the same type of elements as this (i.e., + * with the same template parameters, Key and T) whose content is swapped + * with that of this {@link TreeMultiSet container}. + */ + swap(obj: TreeMultiSet): void; + /** + * @inheritdoc + */ + swap(obj: base.Container): void; + } +} +declare namespace std.TreeMultiMap { + type iterator = MapIterator; + type reverse_iterator = MapReverseIterator; +} +declare namespace std { + /** + * Tree-structured multiple-key map. + * + * {@link TreeMultiMap TreeMultiMaps} are associative containers that store elements formed by a combination of + * a key value and a mapped value, following a specific order, and where multiple elements can + * have equivalent keys. + * + * In a {@link TreeMultiMap}, the key values are generally used to sort and uniquely identify + * the elements, while the mapped values store the content associated to this key. The types of + * key and mapped value may differ, and are grouped together in member type + * value_type, which is a {@link Pair} type combining both: + * + * typedef Pair value_type; + * + * Internally, the elements in a {@link TreeMultiMap}are always sorted by its key following a + * strict weak ordering criterion indicated by its internal comparison method (of {@link less}). + * + * {@link TreeMultiMap}containers are generally slower than {@link HashMap} containers + * to access individual elements by their key, but they allow the direct iteration on subsets based + * on their order. + * + * {@link TreeMultiMap TreeMultiMaps} are typically implemented as binary search trees. + * + * < + * img src="http://samchon.github.io/tstl/images/design/class_diagram/map_containers.png" style="max-width: 100%" />

+ * + * ### Container properties + *
+ *
Associative
+ *
+ * Elements in associative containers are referenced by their key and not by their absolute + * position in the container. + *
+ * + *
Ordered
+ *
+ * The elements in the container follow a strict order at all times. All inserted elements are + * given a position in this order. + *
+ * + *
Map
+ *
+ * Each element associates a key to a mapped value: + * Keys are meant to identify the elements whose main content is the mapped value. + *
+ * + *
Multiple equivalent keys
+ *
Multiple elements in the container can have equivalent keys.
+ *
+ * + * @param Type of the keys. Each element in a map is uniquely identified by its key value. + * @param Type of the mapped value. Each element in a map stores some data as its mapped value. + * + * @reference http://www.cplusplus.com/reference/map/multimap + * @author Jeongho Nam + */ + class TreeMultiMap extends base.MultiMap implements base.ITreeMap { + /** + * @hidden + */ + private tree_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from compare. + * + * @param compare A binary predicate determines order of elements. + */ + constructor(compare: (x: Key, y: Key) => boolean); + /** + * Contruct from elements. + * + * @param array Elements to be contained. + */ + constructor(array: Array>); + /** + * Contruct from elements. + * + * @param array Elements to be contained. + * @param compare A binary predicate determines order of elements. + */ + constructor(array: Array>, compare: (x: Key, y: Key) => boolean); + /** + * Contruct from tuples. + * + * @param array Tuples to be contained. + */ + constructor(array: Array<[Key, T]>); + /** + * Contruct from tuples. + * + * @param array Tuples to be contained. + * @param compare A binary predicate determines order of elements. + */ + constructor(array: Array<[Key, T]>, compare: (x: Key, y: Key) => boolean); + /** + * Copy Constructor. + * + * @param container Another map to copy. + */ + constructor(container: TreeMultiMap); + /** + * Copy Constructor. + * + * @param container Another map to copy. + * @param compare A binary predicate determines order of elements. + */ + constructor(container: TreeMultiMap, compare: (x: Key, y: Key) => boolean); + /** + * Range Constructor. + * + * @param begin nput interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. + */ + constructor(begin: Iterator>, end: Iterator>); + /** + * Range Constructor. + * + * @param begin nput interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. + * @param compare A binary predicate determines order of elements. + */ + constructor(begin: Iterator>, end: Iterator>, compare: (x: Key, y: Key) => boolean); + /** + * @inheritdoc + */ + clear(): void; + /** + * @inheritdoc + */ + find(key: Key): MapIterator; + /** + * @inheritdoc + */ + count(key: Key): number; + /** + * @inheritdoc + */ + key_comp(): (x: Key, y: Key) => boolean; + /** + * @inheritdoc + */ + value_comp(): (x: Pair, y: Pair) => boolean; + /** + * @inheritdoc + */ + lower_bound(key: Key): MapIterator; + /** + * @inheritdoc + */ + upper_bound(key: Key): MapIterator; + /** + * @inheritdoc + */ + equal_range(key: Key): Pair, MapIterator>; + /** + * @hidden + */ + protected _Insert_by_pair(pair: Pair): any; + /** + * @hidden + */ + protected _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; + /** + * @hidden + */ + protected _Insert_by_range>>(first: InputIterator, last: InputIterator): void; + /** + * @hidden + */ + protected _Handle_insert(first: MapIterator, last: MapIterator): void; + /** + * @hidden + */ + protected _Handle_erase(first: MapIterator, last: MapIterator): void; + /** + * Swap content. + * + * Exchanges the content of the container by the content of obj, which is another + * {@link TreeMapMulti map} of the same type. Sizes abd container type may differ. + * + * After the call to this member function, the elements in this container are those which were + * in obj before the call, and the elements of obj are those which were in this. All + * iterators, references and pointers remain valid for the swapped objects. + * + * Notice that a non-member function exists with the same name, {@link swap swap}, overloading that + * algorithm with an optimization that behaves like this member function. + * + * @param obj Another {@link TreeMapMulti map container} of the same type of elements as this (i.e., + * with the same template parameters, Key and T) whose content is swapped + * with that of this {@link TreeMapMulti container}. + */ + swap(obj: TreeMultiMap): void; + /** + * @inheritdoc + */ + swap(obj: base.Container>): void; + } +} +declare namespace std { + /** + * System error exception. + * + * This class defines the type of objects thrown as exceptions to report conditions originating during + * runtime from the operating system or other low-level application program interfaces which have an + * associated {@link ErrorCode}. + * + * The class inherits from {@link RuntimeError}, to which it adds an {@link ErrorCode} as + * member code (and defines a specialized what member). + * + * + * + * + * @reference http://www.cplusplus.com/reference/system_error/system_error + * @author Jeongho Nam + */ + class SystemError extends RuntimeError { + /** + * @hidden + */ + protected code_: ErrorCode; + /** + * Construct from an error code. + * + * @param code An {@link ErrorCode} object. + */ + constructor(code: ErrorCode); + /** + * Construct from an error code and message. + * + * @param code An {@link ErrorCode} object. + * @param message A message incorporated in the string returned by member {@link what what()}. + */ + constructor(code: ErrorCode, message: string); + /** + * Construct from a numeric value and error category. + * + * @param val A numerical value identifying an error code. + * @param category A reference to an {@link ErrorCode} object. + */ + constructor(val: number, category: ErrorCategory); + /** + * Construct from a numeric value, error category and message. + * + * @param val A numerical value identifying an error code. + * @param category A reference to an {@link ErrorCode} object. + * @param message A message incorporated in the string returned by member {@link what what()}. + */ + constructor(val: number, category: ErrorCategory, message: string); + /** + * Get error code. + * + * Returns the {@link ErrorCode} object associated with the exception. + * + * This value is either the {@link ErrorCode} passed to the construction or its equivalent + * (if constructed with a value and a {@link category}. + * + * @return The {@link ErrorCode} associated with the object. + */ + code(): ErrorCode; + } +} +declare namespace std { + /** + * Error category. + * + * This type serves as a base class for specific category types. + * + * Category types are used to identify the source of an error. They also define the relation between + * {@link ErrorCode} and {@link ErrorCondition}objects of its category, as well as the message set for {@link ErrorCode} + * objects. + * + * Objects of these types have no distinct values and are not-copyable and not-assignable, and thus can only be + * passed by reference. As such, only one object of each of these types shall exist, each uniquely identifying its own + * category: all error codes and conditions of a same category shall return a reference to same object. + * + * + * + * + * @reference http://www.cplusplus.com/reference/system_error/error_category + * @author Jeongho Nam + */ + abstract class ErrorCategory { + /** + * Default Constructor. + */ + constructor(); + /** + * Return category name. + * + * In derived classes, the function returns a string naming the category. + * + * In {@link ErrorCategory}, it is a pure virtual member function. + * + *
    + *
  • In the {@link GenericCategory} object, it returns "generic".
  • + *
  • In the {@link SystemCategory} object, it returns "system".
  • + *
  • In the {@link IOStreamCategory} object, it returns "iostream".
  • + *
+ * + * @return The category name. + */ + abstract name(): string; + /** + * Error message. + * + * In derived classes, the function returns a string object with a message describing the error condition + * denoted by val. + * + * In {@link ErrorCategory}, it is a pure virtual member function. + * + * This function is called both by {@link ErrorCode.message ErrorCode.message()} and + * {@link ErrorCondition.message ErrorCondition.message()} to obtain the corresponding message in the + * {@link category}. Therefore, numerical values used by custom error codes and + * {@link ErrorCondition error conditions} should only match for a category if they describe the same error. + * + * @param val A numerical value identifying an error condition. + * If the {@link ErrorCategory} object is the {@link GenericCategory}, this argument is equivalent to an + * {@link errno} value. + * + * @return A string object with the message. + */ + abstract message(val: number): string; + /** + * Default error condition. + * + * Returns the default {@link ErrorCondition}object of this category that is associated with the + * {@link ErrorCode} identified by a value of val. + * + * Its definition in the base class {@link ErrorCategory} returns the same as constructing an + * {@link ErrorCondition} object with: + * + * new ErrorCondition(val, *this); + * + * As a virtual member function, this behavior can be overriden in derived classes. + * + * This function is called by the default definition of member {@link equivalent equivalent()}, which is used to + * compare {@link ErrorCondition error conditions} with error codes. + * + * @param val A numerical value identifying an error condition. + * + * @return The default {@link ErrorCondition}object associated with condition value val for this category. + */ + default_error_condition(val: number): ErrorCondition; + /** + * Check error code equivalence. + * + * Checks whether, for the category, an {@link ErrorCode error code} is equivalent to an + * {@link ErrorCondition error condition. + * + * This function is called by the overloads of comparison operators when an {@link ErrorCondition} object is + * compared to an {@link ErrorCode} object to check for equality or inequality. If either one of those objects' + * {@link ErrorCategory categories} considers the other equivalent using this function, they are considered + * equivalent by the operator. + * + * As a virtual member function, this behavior can be overridden in derived classes to define a different + * correspondence mechanism for each {@link ErrorCategory} type. + * + * @param val_code A numerical value identifying an error code. + * @param cond An object of an {@link ErrorCondition} type. + * + * @return true if the arguments are considered equivalent. false otherwise. + */ + equivalent(val_code: number, cond: ErrorCondition): boolean; + /** + * Check error code equivalence. + * + * Checks whether, for the category, an {@link ErrorCode error code} is equivalent to an + * {@link ErrorCondition error condition. + * + * This function is called by the overloads of comparison operators when an {@link ErrorCondition} object is + * compared to an {@link ErrorCode} object to check for equality or inequality. If either one of those objects' + * {@link ErrorCategory categories} considers the other equivalent using this function, they are considered + * equivalent by the operator. + * + * As a virtual member function, this behavior can be overridden in derived classes to define a different + * correspondence mechanism for each {@link ErrorCategory} type. + * + * @param code An object of an {@link ErrorCode} type. + * @param val_cond A numerical value identifying an error code. + * + * @return true if the arguments are considered equivalent. false otherwise. + */ + equivalent(code: ErrorCode, val_cond: number): boolean; + } +} +declare namespace std { + /** + * Error condition. + * + * Objects of this type hold a condition {@link value} associated with a {@link category}. + * + * Objects of this type describe errors in a generic way so that they may be portable across different + * systems. This is in contrast with {@link ErrorCode} objects, that may contain system-specific + * information. + * + * Because {@link ErrorCondition}objects can be compared with error_code objects directly by using + * relational operators, {@link ErrorCondition}objects are generally used to check whether + * a particular {@link ErrorCode} obtained from the system matches a specific error condition no matter + * the system. + * + * The {@link ErrorCategory categories} associated with the {@link ErrorCondition} and the + * {@link ErrorCode} define the equivalences between them. + * + * + * + * + * @reference http://www.cplusplus.com/reference/system_error/error_condition + * @author Jeongho Nam + */ + class ErrorCondition extends base.ErrorInstance { + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from a numeric value and error category. + * + * @param val A numerical value identifying an error condition. + * @param category A reference to an {@link ErrorCategory} object. + */ + constructor(val: number, category: ErrorCategory); + } +} +declare namespace std { + /** + * Error code. + * + * Objects of this type hold an error code {@link value} associated with a {@link category}. + * + * The operating system and other low-level applications and libraries generate numerical error codes to + * represent possible results. These numerical values may carry essential information for a specific platform, + * but be non-portable from one platform to another. + * + * Objects of this class associate such numerical codes to {@link ErrorCategory error categories}, so that they + * can be interpreted when needed as more abstract (and portable) {@link ErrorCondition error conditions}. + * + * + * + * + * @reference http://www.cplusplus.com/reference/system_error/error_code + * @author Jeongho Nam + */ + class ErrorCode extends base.ErrorInstance { + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from a numeric value and error category. + * + * @param val A numerical value identifying an error code. + * @param category A reference to an {@link ErrorCategory} object. + */ + constructor(val: number, category: ErrorCategory); + } +} +declare namespace std { + /** + * Running on Node. + * + * Test whether the JavaScript is running on Node. + * + * @references http://stackoverflow.com/questions/17575790/environment-detection-node-js-or-browser + */ + function is_node(): boolean; + /** + * Pair of values. + * + * This class couples together a pair of values, which may be of different types (T1 and + * T2). The individual values can be accessed through its public members {@link first} and + * {@link second}. + * + * @param Type of member {@link first}. + * @param Type of member {@link second}. + * + * @reference http://www.cplusplus.com/reference/utility/pair + * @author Jeongho Nam + */ + class Pair implements IComparable> { + /** + * A first value in the Pair. + */ + first: T1; + /** + * A second value in the Pair. + */ + second: T2; + /** + * Construct from pair values. + * + * @param first The first value of the Pair + * @param second The second value of the Pair + */ + constructor(first: T1, second: T2); + /** + * Whether a Pair is equal with the Pair. + * + * Compare each first and second value of two Pair(s) and returns whether they are equal or not. + * + * If stored key and value in a Pair are not number or string but an object like a class or struct, + * the comparison will be executed by a member method (SomeObject)::equals(). If the object does not have + * the member method equal_to(), only address of pointer will be compared. + * + * @param obj A Map to compare + * @return Indicates whether equal or not. + */ + equals(pair: Pair): boolean; + /** + * @inheritdoc + */ + less(pair: Pair): boolean; + } + /** + * Construct {@link Pair} object. + * + * Constructs a {@link Pair} object with its {@link Pair.first first} element set to x and its + * {@link Pair.second second} element set to y. + * + * The template types can be implicitly deduced from the arguments passed to {@link make_pair}. + * + * {@link Pair} objects can be constructed from other {@link Pair} objects containing different types, if the + * respective types are implicitly convertible. + * + * @param x Value for member {@link Pair.first first}. + * @param y Value for member {@link Pair.second second}. + * + * @return A {@link Pair} object whose elements {@link Pair.first first} and {@link Pair.second second} are set to + * x and y respectivelly. + */ + function make_pair(x: T1, y: T2): Pair; +} +declare namespace std { + /** + * Type definition of {@link Vector} and it's the original name used in C++. + */ + export import vector = Vector; + /** + * Type definition of {@link List} and it's the original name used in C++. + */ + export import list = List; + /** + * Type definition of {@link Deque} and it's the original name used in C++. + */ + export import deque = Deque; + /** + * Type definition of {@link Stack} and it's the original name used in C++. + */ + type stack = Stack; + /** + * Type definition of {@link Queue} and it's the original name used in C++. + */ + type queue = Queue; + /** + * Type definition of {@link PriorityQueue} and it's the original name used in C++. + */ + type priority_queue = PriorityQueue; + var stack: typeof Stack; + var queue: typeof Queue; + var priority_queue: typeof PriorityQueue; + /** + * Type definition of {@link TreeSet} and it's the original name used in C++. + */ + export import set = TreeSet; + /** + * Type definition of {@link TreeMultiSet} and it's the original name used in C++. + */ + export import multiset = TreeMultiSet; + /** + * Type definition of {@link HashSet} and it's the original name used in C++. + */ + export import unordered_set = HashSet; + /** + * Type definition of {@link HashMultiSet} and it's the original name used in C++. + */ + export import unordered_multiset = HashMultiSet; + /** + * Type definition of {@link TreeMap} and it's the original name used in C++. + */ + export import map = TreeMap; + /** + * Type definition of {@link TreeMultiMap} and it's the original name used in C++. + */ + export import multimap = TreeMultiMap; + /** + * Type definition of {@link HashMap} and it's the original name used in C++. + */ + export import unordered_map = HashMap; + /** + * Type definition of {@link HashMultiMap} and it's the original name used in C++. + */ + export import unordered_multimap = HashMultiMap; + type exception = Exception; + type logic_error = LogicError; + type domain_error = DomainError; + type invalid_argument = InvalidArgument; + type length_error = LengthError; + type out_of_range = OutOfRange; + type runtime_error = RuntimeError; + type overflow_error = OverflowError; + type underflow_error = UnderflowError; + type range_error = RangeError; + type system_error = SystemError; + type error_category = ErrorCategory; + type error_condition = ErrorCondition; + type error_code = ErrorCode; + var exception: typeof Exception; + var logic_error: typeof LogicError; + var domain_error: typeof DomainError; + var invalid_argument: typeof InvalidArgument; + var length_error: typeof LengthError; + var out_of_range: typeof OutOfRange; + var runtime_error: typeof RuntimeError; + var overflow_error: typeof OverflowError; + var underflow_error: typeof UnderflowError; + var range_error: typeof RangeError; + var system_error: typeof SystemError; + var error_category: typeof ErrorCategory; + var error_condition: typeof ErrorCondition; + var error_code: typeof ErrorCode; +} diff --git a/raven-js/tsconfig.json b/tstl/tsconfig.json similarity index 94% rename from raven-js/tsconfig.json rename to tstl/tsconfig.json index 9b2f3354cf..b5f47406d8 100644 --- a/raven-js/tsconfig.json +++ b/tstl/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "raven-js-tests.ts" + "tstl-tests.ts" ] } \ No newline at end of file diff --git a/tstl/tstl-tests.ts b/tstl/tstl-tests.ts new file mode 100644 index 0000000000..ec42d087b4 --- /dev/null +++ b/tstl/tstl-tests.ts @@ -0,0 +1,2 @@ +import std = require("tstl"); +console.log(std); \ No newline at end of file diff --git a/typescript-stl/index.d.ts b/typescript-stl/index.d.ts index bd6886deed..bbd6c5ca57 100644 --- a/typescript-stl/index.d.ts +++ b/typescript-stl/index.d.ts @@ -1,12485 +1,13 @@ -// Type definitions for TypeScript-STL v1.2.4 -// Project: https://github.com/samchon/typescript-stl +// Type definitions for TSTL v1.3.x +// Project: https://github.com/samchon/tstl // Definitions by: Jeongho Nam // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// +// TypeScript-STL is renamed to TSTL + declare module "typescript-stl" { + import std = require("tstl"); export = std; -} - -/** - *

TypeScript-STL

- *

- *

- * - *

STL (Standard Template Library) Containers and Algorithms for TypeScript.

- * - *

TypeScript-STL is a TypeScript's Standard Template Library who is migrated from C++ STL. Most of classes - * and functions of STL have implemented. Just enjoy it.

- * - * @git https://github.com/samchon/typescript-stl - * @author Jeongho Nam - */ -declare namespace std { -} -/** - * Base classes composing STL in background. - * - * @author Jeongho Nam - */ -declare namespace std.base { -} -declare namespace std { - /** - *

Apply function to range.

- * - *

Applies function fn to each of the elements in the range [first, last).

- * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), - * which contains all the elements between first and last, including the element pointed by - * first but not the element pointed by last. - * @param fn Unary function that accepts an element in the range as argument. This can either be a function p - * ointer or a move constructible function object. Its return value, if any, is ignored. - */ - function for_each, Func extends (val: T) => any>(first: InputIterator, last: InputIterator, fn: Func): Func; - /** - * Apply function to range. - * - * Applies function *fn* to each of the elements in the range [*first*, *first + n*). - * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param n the number of elements to apply the function to - * @param fn Unary function that accepts an element in the range as argument. This can either be a function p - * ointer or a move constructible function object. Its return value, if any, is ignored. - * - * @return first + n - */ - function for_each_n>(first: InputIterator, n: number, fn: (val: T) => any): InputIterator; - /** - *

Test condition on all elements in range.

- * - *

Returns true if pred returns true for all the elements in the range - * [first, last) or if the range is {@link IContainer.empty empty}, and false otherwise. - *

- * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), - * which contains all the elements between first and last, including the element pointed by - * first but not the element pointed by last. - * @param pred Unary function that accepts an element in the range as argument and returns a value convertible to - * boolean. The value returned indicates whether the element fulfills the condition - * checked by this function. The function shall not modify its argument. - * - * @return true if pred returns true for all the elements in the range or if the range is - * {@link IContainer.empty empty}, and false otherwise. - */ - function all_of>(first: InputIterator, last: InputIterator, pred: (val: T) => boolean): boolean; - /** - *

Test if any element in range fulfills condition.

- * - *

Returns true if pred returns true for any of the elements in the range - * [first, last), and false otherwise.

- * - *

If [first, last) is an {@link IContainer.empty empty} range, the function returns - * false.

- * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), - * which contains all the elements between first and last, including the element pointed by - * first but not the element pointed by last. - * @param pred Unary function that accepts an element in the range as argument and returns a value convertible to - * boolean. The value returned indicates whether the element fulfills the condition - * checked by this function. The function shall not modify its argument. - * - * @return true if pred returns true for any of the elements in the range - * [first, last), and false otherwise. If [first, last) is an - * {@link IContainer.empty empty} range, the function returns false. - */ - function any_of>(first: InputIterator, last: InputIterator, pred: (val: T) => boolean): boolean; - /** - *

Test if no elements fulfill condition.

- * - *

Returns true if pred returns false for all the elements in the range - * [first, last) or if the range is {@link IContainer.empty empty}, and false otherwise. - *

- * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), - * which contains all the elements between first and last, including the element pointed by - * first but not the element pointed by last. - * @param pred Unary function that accepts an element in the range as argument and returns a value convertible to - * boolean. The value returned indicates whether the element fulfills the condition - * checked by this function. The function shall not modify its argument. - * - * @return true if pred returns false for all the elements in the range - * [first, last) or if the range is {@link IContainer.empty empty}, and false - * otherwise. - */ - function none_of>(first: InputIterator, last: InputIterator, pred: (val: T) => boolean): boolean; - /** - *

Test whether the elements in two ranges are equal.

- * - *

Compares the elements in the range [first1, last1) with those in the range beginning at - * first2, and returns true if all of the elements in both ranges match.

- * - * @param first1 An {@link Iterator} to the initial position of the first sequence. - * @param last1 An {@link Iterator} to the final position in a sequence. The range used is - * [first1, last1), including the element pointed by first1, but not the element - * pointed by last1. - * @param first2 An {@link Iterator} to the initial position of the second sequence. The comparison includes up to - * as many elements of this sequence as those in the range [first1, last1). - * - * @return true if all the elements in the range [first1, last1) compare equal to those - * of the range starting at first2, and false otherwise. - */ - function equal>(first1: InputIterator, last1: InputIterator, first2: Iterator): boolean; - /** - *

Test whether the elements in two ranges are equal.

- * - *

Compares the elements in the range [first1, last1) with those in the range beginning at - * first2, and returns true if all of the elements in both ranges match.

- * - * @param first1 An {@link Iterator} to the initial position of the first sequence. - * @param last1 An {@link Iterator} to the final position in a sequence. The range used is - * [first1, last1), including the element pointed by first1, but not the element - * pointed by last1. - * @param first2 An {@link Iterator} to the initial position of the second sequence. The comparison includes up to - * as many elements of this sequence as those in the range [first1, last1). - * @param pred Binary function that accepts two elements as argument (one of each of the two sequences, in the same - * order), and returns a value convertible to bool. The value returned indicates whether - * the elements are considered to match in the context of this function. - * - * @return true if all the elements in the range [first1, last1) compare equal to those - * of the range starting at first2, and false otherwise. - */ - function equal>(first1: InputIterator, last1: InputIterator, first2: Iterator, pred: (x: T, y: T) => boolean): boolean; - /** - *

Lexicographical less-than comparison.

- * - *

Returns true if the range [first1, last1) compares lexicographically less - * than the range [first2, last2).

- * - *

A lexicographical comparison is the kind of comparison generally used to sort words alphabetically in - * dictionaries; It involves comparing sequentially the elements that have the same position in both ranges against - * each other until one element is not equivalent to the other. The result of comparing these first non-matching - * elements is the result of the lexicographical comparison.

- * - *

If both sequences compare equal until one of them ends, the shorter sequence is lexicographically less - * than the longer one.

- * - * @param first1 An {@link Iterator} to the initial position of the first sequence. - * @param last1 An {@link Iterator} to the final position in a sequence. The range used is - * [first1, last1), including the element pointed by first1, but not the element - * pointed by last1. - * @param first2 An {@link Iterator} to the initial position of the second sequence. - * @param last2 An {@link Iterator} to the final position of the second sequence. The ranged used is - * [first2, last2). - * - * @return true if the first range compares lexicographically less than than the second. - * false otherwise (including when all the elements of both ranges are equivalent). - */ - function lexicographical_compare, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, last2: Iterator2): boolean; - /** - *

Lexicographical comparison.

- * - *

Returns true if the range [first1, last1) compares lexicographically - * relationship than the range [first2, last2).

- * - *

A lexicographical comparison is the kind of comparison generally used to sort words alphabetically in - * dictionaries; It involves comparing sequentially the elements that have the same position in both ranges against - * each other until one element is not equivalent to the other. The result of comparing these first non-matching - * elements is the result of the lexicographical comparison.

- * - *

If both sequences compare equal until one of them ends, the shorter sequence is lexicographically - * relationship than the longer one.

- * - * @param first1 An {@link Iterator} to the initial position of the first sequence. - * @param last1 An {@link Iterator} to the final position in a sequence. The range used is - * [first1, last1), including the element pointed by first1, but not the element - * pointed by last1. - * @param first2 An {@link Iterator} to the initial position of the second sequence. - * @param last2 An {@link Iterator} to the final position of the second sequence. The ranged used is - * [first2, last2). - * @param compare Binary function that accepts two arguments of the types pointed by the iterators, and returns a - * value convertible to bool. The value returned indicates whether the first argument is - * considered to go before the second in the specific strict weak ordering it defines. - * - * @return true if the first range compares lexicographically relationship than than the - * second. false otherwise (including when all the elements of both ranges are equivalent). - */ - function lexicographical_compare, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, last2: Iterator2, compare: (x: T, y: T) => boolean): boolean; - /** - *

Find value in range.

- * - *

Returns an iterator to the first element in the range [first, last) that compares equal to - * val. If no such element is found, the function returns last.

- * - *

The function uses {@link equal_to equal_to} to compare the individual elements to val.

- * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), - * which contains all the elements between first and last, including the element pointed by - * first but not the element pointed by last. - * @param val Value to search for in the range. - * - * @return An {@link Iterator} to the first element in the range that compares equal to val. If no elements - * match, the function returns last. - */ - function find>(first: InputIterator, last: InputIterator, val: T): InputIterator; - /** - *

Find element in range.

- * - *

Returns an iterator to the first element in the range [first, last) for which pred returns - * true. If no such element is found, the function returns last.

- * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), - * which contains all the elements between first and last, including the element pointed by - * first but not the element pointed by last. - * @param pred Unary function that accepts an element in the range as argument and returns a value convertible - * to bool. The value returned indicates whether the element is considered a match in - * the context of this function. The function shall not modify its argument. - * - * @return An {@link Iterator} to the first element in the range for which pred does not return - * false. If pred is false for all elements, the function returns - * last. - */ - function find_if>(first: InputIterator, last: InputIterator, pred: (val: T) => boolean): InputIterator; - /** - *

Find element in range.

- * - *

Returns an iterator to the first element in the range [first, last) for which pred returns - * true. If no such element is found, the function returns last.

- * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), - * which contains all the elements between first and last, including the element pointed by - * first but not the element pointed by last. - * @param pred Unary function that accepts an element in the range as argument and returns a value convertible - * to bool. The value returned indicates whether the element is considered a match in - * the context of this function. The function shall not modify its argument. - * - * @return An {@link Iterator} to the first element in the range for which pred returns false. - * If pred is true for all elements, the function returns last. - */ - function find_if_not>(first: InputIterator, last: InputIterator, pred: (val: T) => boolean): InputIterator; - /** - *

Find last subsequence in range.

- * - *

Searches the range [first1, last1) for the last occurrence of the sequence defined by - * [first2, last2), and returns an {@link Iterator} to its first element, or last1,/i> if no - * occurrences are found.

- * - *

The elements in both ranges are compared sequentially using {@link equal_to}: A subsequence of - * [first1, last1) is considered a match only when this is true for all the elements of - * [first2, last2).

- * - *

This function returns the last of such occurrences. For an algorithm that returns the first instead, see - * {@link search}.

- * - * @param first1 An {@link Iterator} to the initial position of the first sequence. - * @param last1 An {@link Iterator} to the final position in a sequence. The range used is - * [first1, last1), including the element pointed by first1, but not the element - * pointed by last1. - * @param first2 An {@link Iterator} to the initial position of the element values to be searched for. - * @param last2 An {@link Iterator} to the final position of the element values to be searched for. The range used - * is [first2, last2). - * @param pred Binary function that accepts two elements as arguments (one of each of the two sequences, in the - * same order), and returns a value convertible to bool. The value returned indicates - * whether the elements are considered to match in the context of this function. - * - * @return An {@link Iterator} to the first element of the last occurrence of [first2, last2) in - * [first1, last1). If the sequence is not found, the function returns ,i>last1
. Otherwise - * [first2, last2) is an empty range, the function returns last1. - */ - function find_end, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, last2: Iterator2): Iterator1; - /** - *

Find last subsequence in range.

- * - *

Searches the range [first1, last1) for the last occurrence of the sequence defined by - * [first2, last2), and returns an {@link Iterator} to its first element, or last1,/i> if no - * occurrences are found.

- * - *

The elements in both ranges are compared sequentially using pred: A subsequence of - * [first1, last1) is considered a match only when this is true for all the elements of - * [first2, last2).

- * - *

This function returns the last of such occurrences. For an algorithm that returns the first instead, see - * {@link search}.

- * - * @param first1 An {@link Iterator} to the initial position of the first sequence. - * @param last1 An {@link Iterator} to the final position in a sequence. The range used is - * [first1, last1), including the element pointed by first1, but not the element - * pointed by last1. - * @param first2 An {@link Iterator} to the initial position of the element values to be searched for. - * @param last2 An {@link Iterator} to the final position of the element values to be searched for. The range used - * is [first2, last2). - * @param pred Binary function that accepts two elements as arguments (one of each of the two sequences, in the - * same order), and returns a value convertible to bool. The value returned indicates - * whether the elements are considered to match in the context of this function. - * - * @return An {@link Iterator} to the first element of the last occurrence of [first2, last2) in - * [first1, last1). If the sequence is not found, the function returns ,i>last1
. Otherwise - * [first2, last2) is an empty range, the function returns last1. - */ - function find_end, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, last2: Iterator2, pred: (x: T, y: T) => boolean): Iterator1; - /** - *

Find element from set in range.

- * - *

Returns an iterator to the first element in the range [first1, last1) that matches any of the - * elements in [first2, last2). If no such element is found, the function returns last1.

- * - *

The elements in [first1, last1) are sequentially compared to each of the values in - * [first2, last2) using {@link equal_to}, until a pair matches.

- * - * @param first1 An {@link Iterator} to the initial position of the first sequence. - * @param last1 An {@link Iterator} to the final position in a sequence. The range used is - * [first1, last1), including the element pointed by first1, but not the element - * pointed by last1. - * @param first2 An {@link Iterator} to the initial position of the element values to be searched for. - * @param last2 An {@link Iterator} to the final position of the element values to be searched for. The range used - * is [first2, last2). - * - * @return An {@link Iterator} to the first element in [first1, last1) that is part of - * [first2, last2). If no matches are found, the function returns last1. - */ - function find_first_of, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, last2: Iterator2): Iterator1; - /** - *

Find element from set in range.

- * - *

Returns an iterator to the first element in the range [first1, last1) that matches any of the - * elements in [first2, last2). If no such element is found, the function returns last1.

- * - *

The elements in [first1, last1) are sequentially compared to each of the values in - * [first2, last2) using pred, until a pair matches.

- * - * @param first1 An {@link Iterator} to the initial position of the first sequence. - * @param last1 An {@link Iterator} to the final position in a sequence. The range used is - * [first1, last1), including the element pointed by first1, but not the element - * pointed by last1. - * @param first2 An {@link Iterator} to the initial position of the element values to be searched for. - * @param last2 An {@link Iterator} to the final position of the element values to be searched for. The range used - * is [first2, last2). - * @param pred Binary function that accepts two elements as arguments (one of each of the two sequences, in the - * same order), and returns a value convertible to bool. The value returned indicates - * whether the elements are considered to match in the context of this function. - * - * @return An {@link Iterator} to the first element in [first1, last1) that is part of - * [first2, last2). If no matches are found, the function returns last1. - */ - function find_first_of, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, last2: Iterator2, pred: (x: T, y: T) => boolean): Iterator1; - /** - *

Find equal adjacent elements in range.

- * - *

Searches the range [first, last) for the first occurrence of two consecutive elements that match, - * and returns an {@link Iterator} to the first of these two elements, or last if no such pair is found.

- * - *

Two elements match if they compare equal using {@link equal_to}.

- * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), - * which contains all the elements between first and last, including the element pointed by - * first but not the element pointed by last. - * - * @return An {@link Iterator} to the first element of the first pair of matching consecutive elements in the range - * [first, last). If no such pair is found, the function returns last. - */ - function adjacent_find>(first: InputIterator, last: InputIterator): InputIterator; - /** - *

Find equal adjacent elements in range.

- * - *

Searches the range [first, last) for the first occurrence of two consecutive elements that match, - * and returns an {@link Iterator} to the first of these two elements, or last if no such pair is found.

- * - *

Two elements match if they compare equal using pred.

- * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), - * which contains all the elements between first and last, including the element pointed by - * first but not the element pointed by last. - * @param pred Unary function that accepts an element in the range as argument and returns a value convertible to - * bool. The value returned indicates whether the element is considered a match in the - * context of this function. The function shall not modify its argument. - * - * @return An {@link Iterator} to the first element of the first pair of matching consecutive elements in the range - * [first, last). If no such pair is found, the function returns last. - */ - function adjacent_find>(first: InputIterator, last: InputIterator, pred: (x: T, y: T) => boolean): InputIterator; - /** - *

Search range for subsequence.

- * - *

Searches the range [first1, last1) for the first occurrence of the sequence defined by - * [first2, last2), and returns an iterator to its first element, or last1 if no occurrences are - * found.

- * - *

The elements in both ranges are compared sequentially using {@link equal_to}: A subsequence of - * [first1, last1) is considered a match only when this is true for all the elements of - * [first2, last2).

- * - *

This function returns the first of such occurrences. For an algorithm that returns the last instead, see - * {@link find_end}.

- * - * @param first1 {@link Iterator Forward iterator} to the initial position of the searched sequence. - * @param last1 {@link Iterator Forward iterator} to the final position of the searched sequence. The range used is - * [first1, last1), which contains all the elements between first1 and last1, - * including the element pointed by first1 but not the element pointed by last1. - * @param first2 {@link Iterator Forward iterator} to the initial position of the sequence to be searched for. - * @param last2 {@link Iterator Forward iterator} to the final position of the sequence to be searched for. The range - * used is [first2, last2). - * - * @return An iterator to the first element of the first occurrence of [first2, last2) in first1 - * and last1. If the sequence is not found, the function returns last1. Otherwise - * [first2, last2) is an empty range, the function returns first1. - */ - function search, ForwardIterator2 extends Iterator>(first1: ForwardIterator1, last1: ForwardIterator1, first2: ForwardIterator2, last2: ForwardIterator2): ForwardIterator1; - /** - *

Search range for subsequence.

- * - *

Searches the range [first1, last1) for the first occurrence of the sequence defined by - * [first2, last2), and returns an iterator to its first element, or last1 if no occurrences are - * found.

- * - *

The elements in both ranges are compared sequentially using pred: A subsequence of - * [first1, last1) is considered a match only when this is true for all the elements of - * [first2, last2).

- * - *

This function returns the first of such occurrences. For an algorithm that returns the last instead, see - * {@link find_end}.

- * - * @param first1 {@link Iterator Forward iterator} to the initial position of the searched sequence. - * @param last1 {@link Iterator Forward iterator} to the final position of the searched sequence. The range used is - * [first1, last1), which contains all the elements between first1 and last1, - * including the element pointed by first1 but not the element pointed by last1. - * @param first2 {@link Iterator Forward iterator} to the initial position of the sequence to be searched for. - * @param last2 {@link Iterator Forward iterator} to the final position of the sequence to be searched for. The range - * used is [first2, last2). - * @param pred Binary function that accepts two elements as arguments (one of each of the two sequences, in the same - * order), and returns a value convertible to bool. The returned value indicates whether the elements are - * considered to match in the context of this function. The function shall not modify any of its - * arguments. - * - * @return An iterator to the first element of the first occurrence of [first2, last2) in - * [first1, last1). If the sequence is not found, the function returns last1. Otherwise - * [first2, last2) is an empty range, the function returns first1. - */ - function search, ForwardIterator2 extends Iterator>(first1: ForwardIterator1, last1: ForwardIterator1, first2: ForwardIterator2, last2: ForwardIterator2, pred: (x: T, y: T) => boolean): ForwardIterator1; - /** - *

Search range for elements.

- * - *

Searches the range [first, last) for a sequence of count elements, each comparing equal to - * val.

- * - *

The function returns an iterator to the first of such elements, or last if no such sequence is found. - *

- * - * @param first {@link Iterator Forward iterator} to the initial position of the searched sequence. - * @param last {@link Iterator Forward iterator} to the final position of the searched sequence. The range used is - * [first, last), which contains all the elements between first and last, - * including the element pointed by first but not the element pointed by last. - * @param count Minimum number of successive elements to match. - * @param val Individual value to be compared, or to be used as argument for {@link equal_to}. - * - * @return An iterator to the first element of the sequence. If no such sequence is found, the function returns - * last. - */ - function search_n>(first: ForwardIterator, last: ForwardIterator, count: number, val: T): ForwardIterator; - /** - *

Search range for elements.

- * - *

Searches the range [first, last) for a sequence of count elements, each comparing equal to - * val.

- * - *

The function returns an iterator to the first of such elements, or last if no such sequence is found. - *

- * - * @param first {@link Iterator Forward iterator} to the initial position of the searched sequence. - * @param last {@link Iterator Forward iterator} to the final position of the searched sequence. The range used is - * [first, last), which contains all the elements between first and last, - * including the element pointed by first but not the element pointed by last. - * @param count Minimum number of successive elements to match. - * @param val Individual value to be compared, or to be used as argument for pred. - * @param pred Binary function that accepts two arguments (one element from the sequence as first, and val as - * second), and returns a value convertible to bool. The value returned indicates whether the - * element is considered a match in the context of this function. The function shall not modify any of its - * arguments. - * - * @return An {@link Iterator} to the first element of the sequence. If no such sequence is found, the function - * returns last. - */ - function search_n>(first: ForwardIterator, last: ForwardIterator, count: number, val: T, pred: (x: T, y: T) => boolean): ForwardIterator; - /** - *

Return first position where two ranges differ.

- * - *

Compares the elements in the range [first1, last1) with those in the range beginning at - * first2, and returns the first element of both sequences that does not match.

- * - *

The function returns a {@link Pair} of {@link iterators Iterator} to the first element in each range that - * does not match.

- * - * @param first1 An {@link Iterator} to the initial position of the first sequence. - * @param last1 An {@link Iterator} to the final position in a sequence. The range used is - * [first1, last1), including the element pointed by first1, but not the element - * pointed by last1. - * @param first2 An {@link Iterator} to the initial position of the second sequence. The comparison includes up to - * as many elements of this sequence as those in the range [first1, last1). - * - * @return A {@link Pair}, where its members {@link Pair.first first} and {@link Pair.second second} point to the - * first element in both sequences that did not compare equal to each other. If the elements compared in - * both sequences have all matched, the function returns a {@link Pair} with {@link Pair.first first} set - * to last1 and {@link Pair.second second} set to the element in that same relative position in the - * second sequence. If none matched, it returns {@link make_pair}(first1, first2). - */ - function mismatch, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2): Pair; - /** - *

Return first position where two ranges differ.

- * - *

Compares the elements in the range [first1, last1) with those in the range beginning at - * first2, and returns the first element of both sequences that does not match.

- * - *

The function returns a {@link Pair} of {@link iterators Iterator} to the first element in each range that - * does not match.

- * - * @param first1 An {@link Iterator} to the initial position of the first sequence. - * @param last1 An {@link Iterator} to the final position in a sequence. The range used is - * [first1, last1), including the element pointed by first1, but not the element - * pointed by last1. - * @param first2 An {@link Iterator} to the initial position of the second sequence. The comparison includes up to - * as many elements of this sequence as those in the range [first1, last1). - * @param pred Binary function that accepts two elements as argument (one of each of the two sequences, in the same - * order), and returns a value convertible to bool. The value returned indicates whether - * the elements are considered to match in the context of this function. - * - * @return A {@link Pair}, where its members {@link Pair.first first} and {@link Pair.second second} point to the - * first element in both sequences that did not compare equal to each other. If the elements compared in - * both sequences have all matched, the function returns a {@link Pair} with {@link Pair.first first} set - * to last1 and {@link Pair.second second} set to the element in that same relative position in the - * second sequence. If none matched, it returns {@link make_pair}(first1, first2). - */ - function mismatch, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, compare: (x: T, y: T) => boolean): Pair; - /** - *

Count appearances of value in range.

- * - *

Returns the number of elements in the range [first, last) that compare equal to val.

- * - *

The function uses {@link equal_to} to compare the individual elements to val.

- * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), - * which contains all the elements between first and last, including the element pointed by - * first but not the element pointed by last. - * @param val Value to match. - * - * @return The number of elements in the range [first, last) that compare equal to val. - */ - function count>(first: InputIterator, last: InputIterator, val: T): number; - /** - *

Return number of elements in range satisfying condition.

- * - *

Returns the number of elements in the range [first, last) for which pred is true. - *

- * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), - * which contains all the elements between first and last, including the element pointed by - * first but not the element pointed by last. - * @param pred Unary function that accepts an element in the range as argument, and returns a value convertible - * to bool. The value returned indicates whether the element is counted by this function. - * The function shall not modify its argument. This can either be a function pointer or a function - * object. - */ - function count_if>(first: InputIterator, last: InputIterator, pred: (val: T) => boolean): number; -} -declare namespace std { - /** - *

Copy range of elements.

- * - *

Copies the elements in the range [first, last) into the range beginning at result.

- * - *

The function returns an iterator to the end of the destination range (which points to the element following the - * last element copied).

- * - *

The ranges shall not overlap in such a way that result points to an element in the range - * [first, last). For such cases, see {@link copy_backward}.

- * - * @param first {@link Iterator Input iterator} to the initial position in a sequence to be copied. - * @param last {@link Iterator Input iterator} to the initial position in a sequence to be copied. The range used is - * [first, last), which contains all the elements between first and last, - * including the element pointed by first but not the element pointed by last. - * @param result {@link Iterator Output iterator} to the initial position in the destination sequence. This shall not - * point to any element in the range [first, last). - * - * @return An iterator to the end of the destination range where elements have been copied. - */ - function copy, OutputIterator extends base.ILinearIterator>(first: InputIterator, last: InputIterator, result: OutputIterator): OutputIterator; - /** - *

Copy elements.

- * - *

Copies the first n elements from the range beginning at first into the range beginning at - * result.

- * - *

The function returns an iterator to the end of the destination range (which points to one past the last element - * copied).

- * - *

If n is negative, the function does nothing.

- * - *

If the ranges overlap, some of the elements in the range pointed by result may have undefined but valid values. - *

- * - * @param first {@link Iterator Input iterator} to the initial position in a sequence of at least n elements to - * be copied. InputIterator shall point to a type assignable to the elements pointed by - * OutputIterator. - * @param n Number of elements to copy. If this value is negative, the function does nothing. - * @param result {@link Iterator Output iterator} to the initial position in the destination sequence of at least - * n elements. This shall not point to any element in the range [first, last]. - * - * @return An iterator to the end of the destination range where elements have been copied. - */ - function copy_n, OutputIterator extends base.ILinearIterator>(first: InputIterator, n: number, result: OutputIterator): OutputIterator; - /** - *

Copy certain elements of range.

- * - *

Copies the elements in the range [first, last) for which pred returns true to the - * range beginning at result.

- * - * @param first {@link Iterator Input iterator} to the initial position in a sequence to be copied. - * @param last {@link Iterator Input iterator} to the initial position in a sequence to be copied. The range used is - * [first, last), which contains all the elements between first and last, - * including the element pointed by first but not the element pointed by last. - * @param result {@link Iterator Output iterator} to the initial position in the destination sequence. This shall not - * point to any element in the range [first, last). - * @param pred Unary function that accepts an element in the range as argument, and returns a value convertible to - * bool. The value returned indicates whether the element is to be copied (if - * true, it is copied). The function shall not modify any of its arguments. - * - * @return An iterator to the end of the destination range where elements have been copied. - */ - function copy_if, OutputIterator extends base.ILinearIterator>(first: InputIterator, last: InputIterator, result: OutputIterator, pred: (x: T) => boolean): OutputIterator; - /** - *

Copy range of elements backward.

- * - *

Copies the elements in the range [first, last) starting from the end into the range terminating - * at result.

- * - *

The function returns an iterator to the first element in the destination range.

- * - *

The resulting range has the elements in the exact same order as [first, last). To reverse their - * order, see {@link reverse_copy}.

- * - *

The function begins by copying *(last-1) into *(result-1), and then follows backward - * by the elements preceding these, until first is reached (and including it).

- * - *

The ranges shall not overlap in such a way that result (which is the past-the-end element in the - * destination range) points to an element in the range (first,last]. For such cases, see {@link copy}.

- * - * @param first {@link Iterator Bidirectional iterator} to the initial position in a sequence to be copied. - * @param last {@link Iterator Bidirectional iterator} to the initial position in a sequence to be copied. The range - * used is [first, last), which contains all the elements between first and - * last, including the element pointed by first but not the element pointed by last. - * @param result {@link Iterator Bidirectional iterator} to the initial position in the destination sequence. This - * shall not point to any element in the range [first, last). - * - * @return An iterator to the first element of the destination sequence where elements have been copied. - */ - function copy_backward, BidirectionalIterator2 extends base.ILinearIterator>(first: BidirectionalIterator1, last: BidirectionalIterator1, result: BidirectionalIterator2): BidirectionalIterator2; - /** - *

Fill range with value.

- * - *

Assigns val to all the elements in the range [first, last).

- * - * @param first {@link Iterator Forward iterator} to the initial position in a sequence of elements that support being - * assigned a value of type T. - * @param last {@link Iterator Forward iterator} to the final position in a sequence of elements that support being - * assigned a value of type T.. The range filled is [first, last), which contains - * all the elements between first and last, including the element pointed by first - * but not the element pointed by last. - * @param val Value to assign to the elements in the filled range. - */ - function fill>(first: ForwardIterator, last: ForwardIterator, val: T): void; - /** - *

Fill sequence with value.

- * - *

Assigns val to the first n elements of the sequence pointed by first.

- * - * @param first {@link Iterator Output iterator} to the initial position in a sequence of elements that support being - * assigned a value of type T. - * @param n Number of elements to fill. If negative, the function does nothing. - * @param val Value to be used to fill the range. - * - * @return An iterator pointing to the element that follows the last element filled. - */ - function fill_n>(first: OutputIterator, n: number, val: T): OutputIterator; - /** - *

Transform range.

- * - *

Applies op to each of the elements in the range [first, last) and stores the value returned - * by each operation in the range that begins at result.

- * - * @param first {@link Iterator Input iterator} to the initial position in a sequence to be transformed. - * @param last {@link Iterator Input iterator} to the initial position in a sequence to be transformed. The range - * used is [first, last), which contains all the elements between first and - * last, including the element pointed by first but not the element pointed by last. - * @param result {@link Iterator Output} iterator to the initial position of the range where the operation results are - * stored. The range includes as many elements as [first, last). - * @param op Unary function that accepts one element of the type pointed to by InputIterator as argument, and - * returns some result value convertible to the type pointed to by OutputIterator. - * - * @return An iterator pointing to the element that follows the last element written in the result sequence. - */ - function transform, OutputIterator extends base.ILinearIterator>(first: InputIterator, last: InputIterator, result: OutputIterator, op: (val: T) => T): OutputIterator; - /** - *

Transform range.

- * - *

Calls binary_op using each of the elements in the range [first1, last1) as first argument, - * and the respective argument in the range that begins at first2 as second argument. The value returned by - * each call is stored in the range that begins at result.

- * - * @param first1 {@link Iterator Input iterator} to the initial position of the first sequence. - * @param last1 {@link Iterator Input iterator} to the final position of the first sequence. The range used is - * [first1, last1), including the element pointed by first1, but not the element - * pointed by last1. - * @param first2 {@link Iterator Input iterator} to the initial position of the second range. The range includes as - * many elements as [first1, last1). - * @param result {@link Iterator Output} iterator to the initial position of the range where the operation results are - * stored. The range includes as many elements as [first1, last1). - * @param binary_op Binary function that accepts two elements as argument (one of each of the two sequences), and - * returns some result value convertible to the type pointed to by OutputIterator. - * - * @return An iterator pointing to the element that follows the last element written in the result sequence. - */ - function transform, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, result: OutputIterator, binary_op: (x: T, y: T) => T): OutputIterator; - /** - *

Generate values for range with function.

- * - *

Assigns the value returned by successive calls to gen to the elements in the range [first, last). - *

- * - * @param first {@link Iterator Forward iterator} to the initial position in a sequence. - * @param last {@link Iterator Forward iterator} to the final position in a sequence. The range affected is - * [first, last), which contains all the elements between first and last, - * including the element pointed by first but not the element pointed by last. - * @param gen Generator function that is called with no arguments and returns some value of a type convertible to - * those pointed by the iterators. - */ - function generate>(first: ForwardIterator, last: ForwardIterator, gen: () => T): void; - /** - *

Generate values for sequence with function.

- * - *

Assigns the value returned by successive calls to gen to the first n elements of the sequence - * pointed by first.

- * - * @param first {@link Iterator Output iterator} to the initial position in a sequence of at least n elements - * that support being assigned a value of the type returned by gen. - * @param n Number of values to generate. If negative, the function does nothing. - * @param gen Generator function that is called with no arguments and returns some value of a type convertible to - * those pointed by the iterators. - * - * @return An iterator pointing to the element that follows the last element whose value has been generated. - */ - function generate_n>(first: ForwardIterator, n: number, gen: () => T): ForwardIterator; - /** - *

Remove consecutive duplicates in range.

- * - *

Removes all but the first element from every consecutive group of equivalent elements in the range - * [first, last).

- * - *

The function cannot alter the properties of the object containing the range of elements (i.e., it cannot - * alter the size of an array or a container): The removal is done by replacing the duplicate elements by the next - * element that is not a duplicate, and signaling the new size of the shortened range by returning an iterator to - * the element that should be considered its new past-the-last element.

- * - *

The relative order of the elements not removed is preserved, while the elements between the returned - * iterator and last are left in a valid but unspecified state.

- * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), - * which contains all the elements between first and last, including the element pointed by - * first but not the element pointed by last. - * - * @return An iterator to the element that follows the last element not removed. The range between first and - * this iterator includes all the elements in the sequence that were not considered duplicates. - */ - function unique>(first: InputIterator, last: InputIterator): InputIterator; - /** - *

Remove consecutive duplicates in range.

- * - *

Removes all but the first element from every consecutive group of equivalent elements in the range - * [first, last).

- * - *

The function cannot alter the properties of the object containing the range of elements (i.e., it cannot - * alter the size of an array or a container): The removal is done by replacing the duplicate elements by the next - * element that is not a duplicate, and signaling the new size of the shortened range by returning an iterator to - * the element that should be considered its new past-the-last element.

- * - *

The relative order of the elements not removed is preserved, while the elements between the returned - * iterator and last are left in a valid but unspecified state.

- * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), - * which contains all the elements between first and last, including the element pointed by - * first but not the element pointed by last. - * @param pred Binary function that accepts two elements in the range as argument, and returns a value convertible - * to bool. The value returned indicates whether both arguments are considered equivalent - * (if true, they are equivalent and one of them is removed). The function shall not modify - * any of its arguments. - * - * @return An iterator to the element that follows the last element not removed. The range between first and - * this iterator includes all the elements in the sequence that were not considered duplicates. - */ - function unique>(first: InputIterator, last: InputIterator, pred: (left: t, right: t) => boolean): InputIterator; - /** - *

Copy range removing duplicates.

- * - *

Copies the elements in the range [first, last) to the range beginning at result, except - * consecutive duplicates (elements that compare equal to the element preceding).

- * - *

Only the first element from every consecutive group of equivalent elements in the range - * [first, last) is copied.

- * - *

The comparison between elements is performed by applying {@lnk equal_to}.

- * - * @param first {@link Iterator Forward iterator} to the initial position in a sequence. - * @param last {@link Iterator Forward iterator} to the final position in a sequence. The range used is - * [first, last), which contains all the elements between first and last, - * including the element pointed by first but not the element pointed by last. - * @param result Output iterator to the initial position of the range where the resulting range of values is stored. - * The pointed type shall support being assigned the value of an element in the range - * [first, last). - * - * @return An iterator pointing to the end of the copied range, which contains no consecutive duplicates. - */ - function unique_copy, OutputIterator extends base.ILinearIterator>(first: InputIterator, last: InputIterator, result: OutputIterator): OutputIterator; - /** - *

Copy range removing duplicates.

- * - *

Copies the elements in the range [first, last) to the range beginning at result, except - * consecutive duplicates (elements that compare equal to the element preceding).

- * - *

Only the first element from every consecutive group of equivalent elements in the range - * [first, last) is copied.

- * - *

The comparison between elements is performed by applying pred.

- * - * @param first {@link Iterator Forward iterator} to the initial position in a sequence. - * @param last {@link Iterator Forward iterator} to the final position in a sequence. The range used is - * [first, last), which contains all the elements between first and last, - * including the element pointed by first but not the element pointed by last. - * @param result Output iterator to the initial position of the range where the resulting range of values is stored. - * The pointed type shall support being assigned the value of an element in the range - * [first, last). - * @param pred Binary function that accepts two elements in the range as argument, and returns a value convertible to - * bool. The value returned indicates whether both arguments are considered equivalent (if - * true, they are equivalent and one of them is removed). The function shall not modify any - * of its arguments. - * - * @return An iterator pointing to the end of the copied range, which contains no consecutive duplicates. - */ - function unique_copy, OutputIterator extends base.ILinearIterator>(first: InputIterator, last: InputIterator, result: OutputIterator, pred: (x: T, y: T) => boolean): OutputIterator; - /** - *

Remove value from range.

- * - *

Transforms the range [first, last) into a range with all the elements that compare equal to - * val removed, and returns an iterator to the new last of that range.

- * - *

The function cannot alter the properties of the object containing the range of elements (i.e., it cannot alter - * the size of an array or a container): The removal is done by replacing the elements that compare equal to - * val by the next element that does not, and signaling the new size of the shortened range by returning an - * iterator to the element that should be considered its new past-the-last element.

- * - *

The relative order of the elements not removed is preserved, while the elements between the returned iterator - * and last are left in a valid but unspecified state.

- * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), - * which contains all the elements between first and last, including the element pointed by - * first but not the element pointed by last. - * @param val Value to be removed. - */ - function remove>(first: InputIterator, last: InputIterator, val: T): InputIterator; - /** - *

Remove elements from range.

- * - *

Transforms the range [first, last) into a range with all the elements for which pred returns - * true removed, and returns an iterator to the new last of that range.

- * - *

The function cannot alter the properties of the object containing the range of elements (i.e., it cannot - * alter the size of an array or a container): The removal is done by replacing the elements for which pred returns - * true by the next element for which it does not, and signaling the new size of the shortened range - * by returning an iterator to the element that should be considered its new past-the-last element.

- * - *

The relative order of the elements not removed is preserved, while the elements between the returned - * iterator and last are left in a valid but unspecified state.

- * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), - * which contains all the elements between first and last, including the element pointed by - * first but not the element pointed by last. - * @param pred Unary function that accepts an element in the range as argument, and returns a value convertible to - * bool. The value returned indicates whether the element is to be removed (if - * true, it is removed). The function shall not modify its argument. - */ - function remove_if>(first: InputIterator, last: InputIterator, pred: (left: T) => boolean): InputIterator; - /** - *

Copy range removing value.

- * - *

Copies the elements in the range [first, last) to the range beginning at result, except - * those elements that compare equal to val.

- * - *

The resulting range is shorter than [first, last) by as many elements as matches in the sequence, - * which are "removed".

- * - *

The function uses {@link equal_to} to compare the individual elements to val.

- * - * @param first {@link Iterator InputIterator} to the initial position in a sequence. - * @param last {@link Iterator InputIterator} to the final position in a sequence. The range used is - * [first, last), which contains all the elements between first and last, - * including the element pointed by first but not the element pointed by last. - * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is - * stored. The pointed type shall support being assigned the value of an element in the range - * [first, last). - * @param val Value to be removed. - * - * @return An iterator pointing to the end of the copied range, which includes all the elements in - * [first, last) except those that compare equal to val. - */ - function remove_copy, OutputIterator extends base.ILinearIterator>(first: InputIterator, last: InputIterator, result: OutputIterator, val: T): OutputIterator; - /** - *

Copy range removing values.

- * - *

Copies the elements in the range [first, last) to the range beginning at result, except - * those elements for which pred returns true.

- * - *

The resulting range is shorter than [first, last) by as many elements as matches, which are - * "removed".

- * - * @param first {@link Iterator InputIterator} to the initial position in a sequence. - * @param last {@link Iterator InputIterator} to the final position in a sequence. The range used is - * [first, last), which contains all the elements between first and last, - * including the element pointed by first but not the element pointed by last. - * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is - * stored. The pointed type shall support being assigned the value of an element in the range - * [first, last). - * @param pred Unary function that accepts an element in the range as argument, and returns a value convertible to - * bool. The value returned indicates whether the element is to be removed from the copy (if - * true, it is not copied). The function shall not modify its argument. - * - * @return An iterator pointing to the end of the copied range, which includes all the elements in - * [first, last) except those for which pred returns true. - */ - function remove_copy_if, OutputIterator extends base.ILinearIterator>(first: InputIterator, last: InputIterator, result: OutputIterator, pred: (val: T) => boolean): OutputIterator; - /** - *

Replace value in range.

- * - *

Assigns new_val to all the elements in the range [first, last) that compare equal to - * old_val.

- * - *

The function uses {@link equal_to} to compare the individual elements to old_val.

- * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), - * which contains all the elements between first and last, including the element pointed by - * first but not the element pointed by last. - * @param old_val Value to be replaced. - * @param new_val Replacement value. - */ - function replace>(first: InputIterator, last: InputIterator, old_val: T, new_val: T): void; - /** - *

Replace value in range.

- * - *

Assigns new_val to all the elements in the range [first, last) for which pred returns - * true.

- * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), - * which contains all the elements between first and last, including the element pointed by - * first but not the element pointed by last. - * @param pred Unary function that accepts an element in the range as argument, and returns a value convertible to - * bool. The value returned indicates whether the element is to be replaced (if - * true, it is replaced). The function shall not modify its argument. - * @param new_val Value to assign to replaced elements. - */ - function replace_if>(first: InputIterator, last: InputIterator, pred: (val: T) => boolean, new_val: T): void; - /** - *

Copy range replacing value.

- * - *

Copies the elements in the range [first, last) to the range beginning at result, replacing - * the appearances of old_value by new_value.

- * - *

The function uses {@link std.equal_to} to compare the individual elements to old_value.

- * - *

The ranges shall not overlap in such a way that result points to an element in the range - * [first, last).

- * - * @param first {@link Iterator InputIterator} to the initial position in a sequence. - * @param last {@link Iterator InputIterator} to the final position in a sequence. The range used is - * [first, last), which contains all the elements between first and last, - * including the element pointed by first but not the element pointed by last. - * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is - * stored. The pointed type shall support being assigned the value of an element in the range - * [first, last). - * @param old_val Value to be replaced. - * @param new_val Replacement value. - * - * @return An iterator pointing to the element that follows the last element written in the result sequence. - */ - function replace_copy, OutputIterator extends base.ILinearIterator>(first: InputIterator, last: InputIterator, result: OutputIterator, old_val: T, new_val: T): OutputIterator; - /** - *

Copy range replacing value.

- * - *

Copies the elements in the range [first, last) to the range beginning at result, replacing - * those for which pred returns true by new_value.

- * - * @param first {@link Iterator InputIterator} to the initial position in a sequence. - * @param last {@link Iterator InputIterator} to the final position in a sequence. The range used is - * [first, last), which contains all the elements between first and last, - * including the element pointed by first but not the element pointed by last. - * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is - * stored. The pointed type shall support being assigned the value of an element in the range - * [first, last). - * @param pred Unary function that accepts an element in the range as argument, and returns a value convertible to - * bool. The value returned indicates whether the element is to be removed from the copy (if - * true, it is not copied). The function shall not modify its argument. - * @param new_val Value to assign to replaced values. - * - * @return An iterator pointing to the element that follows the last element written in the result sequence. - */ - function replace_copy_if, OutputIterator extends base.ILinearIterator>(first: InputIterator, last: InputIterator, result: OutputIterator, pred: (val: T) => boolean, new_val: T): OutputIterator; - /** - *

Exchange values of objects pointed to by two iterators.

- * - *

Swaps the elements pointed to by x and y.

- * - *

The function calls {@link Iterator.swap} to exchange the elements.

- * - * @param x {@link Iterator Forward iterator} to the objects to swap. - * @param y {@link Iterator Forward iterator} to the objects to swap. - */ - function iter_swap(x: Iterator, y: Iterator): void; - /** - *

Exchange values of two ranges.

- * - *

Exchanges the values of each of the elements in the range [first1, last1) with those of their - * respective elements in the range beginning at first2.

- * - *

The function calls {@link Iterator.swap} to exchange the elements.

- * - * @param first1 {@link Iterator Forward iterator} to the initial position of the first sequence. - * @param last1 {@link Iterator Forward iterator} to the final position of the first sequence. The range used is - * [first1, last1), including the element pointed by first1, but not the element - * pointed by last1. - * @param first2 {@link Iterator Forward iterator} to the initial position of the second range. The range includes as - * many elements as [first1, last1). The two ranges shall not overlap. - * - * @return An iterator to the last element swapped in the second sequence. - */ - function swap_ranges, ForwardIterator2 extends Iterator>(first1: ForwardIterator1, last1: ForwardIterator1, first2: ForwardIterator2): ForwardIterator2; - /** - *

Reverse range.

- * - *

Reverses the order of the elements in the range [first, last).

- * - *

The function calls {@link iter_swap} to swap the elements to their new locations.

- * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), - * which contains all the elements between first and last, including the element pointed by - * first but not the element pointed by last. - */ - function reverse>(first: InputIterator, last: InputIterator): void; - /** - *

Copy range reversed.

- * - *

Copies the elements in the range [first, last) to the range beginning at result, but in - * reverse order.

- * - * @param first {@link Iterator Bidirectional iterator} to the initial position in a sequence to be copied. - * @param last {@link Iterator Bidirectional iterator} to the initial position in a sequence to be copied. The range - * used is [first, last), which contains all the elements between first and - * last, including the element pointed by first but not the element pointed by last. - * @param result {@link Iterator Output iterator} to the initial position of the range where the reserved range is - * stored. The pointed type shall support being assigned the value of an element in the range - * [first, last). - * - * @return An output iterator pointing to the end of the copied range, which contains the same elements in reverse - * order. - */ - function reverse_copy, OutputIterator extends base.ILinearIterator>(first: BidirectionalIterator, last: BidirectionalIterator, result: OutputIterator): OutputIterator; - /** - *

Rotate left the elements in range.

- * - *

Rotates the order of the elements in the range [first, last), in such a way that the element - * pointed by middle becomes the new first element.

- * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param middle An {@link Iterator} pointing to the element within the range [first, last) that is - * moved to the first position in the range. - * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), - * which contains all the elements between first and last, including the element pointed by - * first but not the element pointed by last. - * - * @return An iterator pointing to the element that now contains the value previously pointed by first. - */ - function rotate>(first: InputIterator, middle: InputIterator, last: InputIterator): InputIterator; - /** - *

Copy range rotated left.

- * - *

Copies the elements in the range [first, last) to the range beginning at result, but - * rotating the order of the elements in such a way that the element pointed by middle becomes the first - * element in the resulting range.

- * - * @param first {@link Iterator Forward iterator} to the initial position of the range to be copy-rotated. - * @param middle Forward iterator pointing to the element within the range [first, last) that is copied as the first element in the resulting range. - * @param last {@link Iterator Forward iterator} to the final positions of the range to be copy-rotated. The range - * used is [first, last), which contains all the elements between first and - * last, including the element pointed by first but not the element pointed by last. - * Notice that in this function, these are not consecutive parameters, but the first and third ones. - * @param result {@link Iterator Output iterator} to the initial position of the range where the reserved range is - * stored. The pointed type shall support being assigned the value of an element in the range - * [first, last). - * - * @return An output iterator pointing to the end of the copied range. - */ - function rotate_copy, OutputIterator extends base.ILinearIterator>(first: ForwardIterator, middle: ForwardIterator, last: ForwardIterator, result: OutputIterator): OutputIterator; - /** - *

Randomly rearrange elements in range.

- * - *

Rearranges the elements in the range [first, last) randomly.

- * - *

The function swaps the value of each element with that of some other randomly picked element. When provided, - * the function gen determines which element is picked in every case. Otherwise, the function uses some unspecified - * source of randomness.

- * - *

To specify a uniform random generator, see {@link shuffle}.

- * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), - * which contains all the elements between first and last, including the element pointed by - * first but not the element pointed by last. - */ - function random_shuffle>(first: RandomAccessIterator, last: RandomAccessIterator): void; - /** - *

Randomly rearrange elements in range using generator.

- * - *

Rearranges the elements in the range [first, last) randomly, using g as uniform random - * number generator.

- * - *

The function swaps the value of each element with that of some other randomly picked element. The function - * determines the element picked by calling g().

- * - *

To shuffle the elements of the range without such a generator, see {@link random_shuffle} instead.

- * - *
Note
- *

Using random generator engine is not implemented yet.

- * - * @param first An {@link Iterator} to the initial position in a sequence. - * @param last An {@link Iterator} to the final position in a sequence. The range used is [first, last), - * which contains all the elements between first and last, including the element pointed by - * first but not the element pointed by last. - */ - function shuffle>(first: RandomAccessIterator, last: RandomAccessIterator): void; -} -declare namespace std { - /** - *

Sort elements in range.

- * - *

Sorts the elements in the range [first, last) into ascending order. The elements are compared - * using {@link less}.

- * - * @param first {@link IArrayIterator Random-access iterator} to the initial position of the sequence to be sorted. - * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence to be sorted. - * The range used is [first, last), which contains all the elements between first - * and last, including the element pointed by first but not the element pointed by - * last. {@link IArrayIterator RandomAccessIterator} shall point to a type for which - * {@link Iterator.swap swap} is properly defined. - */ - function sort>(first: RandomAccessIterator, last: RandomAccessIterator): void; - /** - *

Sort elements in range.

- * - *

Sorts the elements in the range [first, last) into specific order. The elements are compared - * using compare.

- * - * @param first {@link IArrayIterator Random-access iterator} to the initial position of the sequence to be sorted. - * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence to be sorted. - * The range used is [first, last), which contains all the elements between first - * and last, including the element pointed by first but not the element pointed by - * last. {@link IArrayIterator RandomAccessIterator} shall point to a type for which - * {@link Iterator.swap swap} is properly defined. - * @param compare Binary function that accepts two elements in the range as arguments, and returns a value - * convertible to boolean. The value returned indicates whether the element passed as first - * argument is considered to go before the second in the specific strict weak ordering it defines. The - * function shall not modify any of its arguments. This can either be a function pointer or a function - * object. - */ - function sort>(first: RandomAccessIterator, last: RandomAccessIterator, compare: (left: T, right: T) => boolean): void; - /** - *

Partially sort elements in range.

- * - *

Rearranges the elements in the range [first, last), in such a way that the elements before - * middle are the smallest elements in the entire range and are sorted in ascending order, while the remaining - * elements are left without any specific order.

- * - *

The elements are compared using {@link less}.

- * - * @param last {@link IArrayIterator Random-access iterator} to the first position of the sequence to be sorted. - * @param middle {@link IArrayIterator Random-access iterator} pointing to the element within the range [first, last) that is used as the upper boundary of the elements that are fully sorted. - * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence to be sorted. - * The range used is [first, last), which contains all the elements between first - * and last, including the element pointed by first but not the element pointed by - * last. - */ - function partial_sort>(first: RandomAccessIterator, middle: RandomAccessIterator, last: RandomAccessIterator): void; - /** - *

Partially sort elements in range.

- * - *

Rearranges the elements in the range [first, last), in such a way that the elements before - * middle are the smallest elements in the entire range and are sorted in ascending order, while the remaining - * elements are left without any specific order.

- * - *

The elements are compared using comp.

- * - * @param last {@link IArrayIterator Random-access iterator} to the first position of the sequence to be sorted. - * @param middle {@link IArrayIterator Random-access iterator} pointing to the element within the range [first, last) that is used as the upper boundary of the elements that are fully sorted. - * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence to be sorted. - * The range used is [first, last), which contains all the elements between first - * and last, including the element pointed by first but not the element pointed by - * last. - * @param compare Binary function that accepts two elements in the range as arguments, and returns a value - * convertible to boolean. The value returned indicates whether the element passed as - * first argument is considered to go before the second in the specific strict weak ordering it - * defines. The function shall not modify any of its arguments. - */ - function partial_sort>(first: RandomAccessIterator, middle: RandomAccessIterator, last: RandomAccessIterator, compare: (x: T, y: T) => boolean): void; - /** - *

Copy and partially sort range.

- * - *

Copies the smallest elements in the range [first, last) to - * [result_first, result_last), sorting the elements copied. The number of elements copied is the same - * as the {@link distance} between result_first and result_last (unless this is more than the amount of - * elements in [first, last)).

- * - *

The range [first, last) is not modified.

- * - *

The elements are compared using {@link less}.

- * - * @param first {@link Iterator Input iterator} to the initial position of the sequence to copy from. - * @param last {@link Iterator Input iterator} to the final position of the sequence to copy from. The range used is - * [first, last), which contains all the elements between first and last, - * including the element pointed by first but not the element pointed by last. - * InputIterator shall point to a type assignable to the elements pointed by - * RandomAccessIterator. - * @param result_first {@link Iterator Random-access iterator} to the initial position of the destination sequence. - * @param result_last {@link Iterator Random-access iterator} to the final position of the destination sequence. - * The range used is [result_first, result_last). - * @param compare Binary function that accepts two elements in the result range as arguments, and returns a value - * convertible to bool. The value returned indicates whether the element passed as first - * argument is considered to go before the second in the specific strict weak ordering it - * defines. The function shall not modify any of its arguments. - * - * @return An iterator pointing to the element that follows the last element written in the result sequence. - */ - function partial_sort_copy, RandomAccessIterator extends Iterator>(first: InputIterator, last: InputIterator, result_first: RandomAccessIterator, result_last: RandomAccessIterator): RandomAccessIterator; - /** - *

Copy and partially sort range.

- * - *

Copies the smallest (or largest) elements in the range [first, last) to - * [result_first, result_last), sorting the elements copied. The number of elements copied is the same - * as the {@link distance} between result_first and result_last (unless this is more than the amount of - * elements in [first, last)).

- * - *

The range [first, last) is not modified.

- * - *

The elements are compared using compare.

- * - * @param first {@link Iterator Input iterator} to the initial position of the sequence to copy from. - * @param last {@link Iterator Input iterator} to the final position of the sequence to copy from. The range used is - * [first, last), which contains all the elements between first and last, - * including the element pointed by first but not the element pointed by last. - * InputIterator shall point to a type assignable to the elements pointed by - * RandomAccessIterator. - * @param result_first {@link Iterator Random-access iterator} to the initial position of the destination sequence. - * @param result_last {@link Iterator Random-access iterator} to the final position of the destination sequence. - * The range used is [result_first, result_last). - * @param compare Binary function that accepts two elements in the result range as arguments, and returns a value - * convertible to bool. The value returned indicates whether the element passed as first - * argument is considered to go before the second in the specific strict weak ordering it - * defines. The function shall not modify any of its arguments. - * - * @return An iterator pointing to the element that follows the last element written in the result sequence. - */ - function partial_sort_copy, RandomAccessIterator extends Iterator>(first: InputIterator, last: InputIterator, result_first: RandomAccessIterator, result_last: RandomAccessIterator, compare: (x: T, y: T) => boolean): RandomAccessIterator; - /** - *

Check whether range is sorted.

- * - *

Returns true if the range [first, last) is sorted into ascending order.

- * - *

The elements are compared using {@link less}.

- * - * @param first {@link Iterator Forward iterator} to the initial position of the sequence. - * @param last {@link Iterator Forward iterator} to the final position of the sequence. The range checked is - * [first, last), which contains all the elements between first and last, - * including the element pointed by first but not the element pointed by last. - * - * @return true if the range [first, last) is sorted into ascending order, - * false otherwise. If the range [first, last) contains less than two elements, - * the function always returns true. - */ - function is_sorted>(first: ForwardIterator, last: ForwardIterator): boolean; - /** - *

Check whether range is sorted.

- * - *

Returns true if the range [first, last) is sorted into ascending order.

- * - *

The elements are compared using compare.

- * - * @param first {@link Iterator Forward iterator} to the initial position of the sequence. - * @param last {@link Iterator Forward iterator} to the final position of the sequence. The range checked is - * [first, last), which contains all the elements between first and last, - * including the element pointed by first but not the element pointed by last. - * @param compare Binary function that accepts two elements in the range as arguments, and returns a value convertible - * to bool. The value returned indicates whether the element passed as first argument is - * considered to go before the second in the specific strict weak ordering it defines. The function - * shall not modify any of its arguments. - * - * @return true if the range [first, last) is sorted into ascending order, - * false otherwise. If the range [first, last) contains less than two elements, - * the function always returns true. - */ - function is_sorted>(first: ForwardIterator, last: ForwardIterator, compare: (x: T, y: T) => boolean): boolean; - /** - *

Find first unsorted element in range.

- * - *

Returns an iterator to the first element in the range [first, last) which does not follow an - * ascending order.

- * - *

The range between first and the iterator returned {@link is_sorted is sorted}.

- * - *

If the entire range is sorted, the function returns last.

- * - *

The elements are compared using {@link equal_to}.

- * - * @param first {@link Iterator Forward iterator} to the initial position of the sequence. - * @param last {@link Iterator Forward iterator} to the final position of the sequence. The range checked is - * [first, last), which contains all the elements between first and last, - * including the element pointed by first but not the element pointed by last. - * @param compare Binary function that accepts two elements in the range as arguments, and returns a value convertible - * to bool. The value returned indicates whether the element passed as first argument is - * considered to go before the second in the specific strict weak ordering it defines. The function - * shall not modify any of its arguments. - * - * @return An iterator to the first element in the range which does not follow an ascending order, or last if - * all elements are sorted or if the range contains less than two elements. - */ - function is_sorted_until>(first: ForwardIterator, last: ForwardIterator): ForwardIterator; - /** - *

Find first unsorted element in range.

- * - *

Returns an iterator to the first element in the range [first, last) which does not follow an - * ascending order.

- * - *

The range between first and the iterator returned {@link is_sorted is sorted}.

- * - *

If the entire range is sorted, the function returns last.

- * - *

The elements are compared using compare.

- * - * @param first {@link Iterator Forward iterator} to the initial position of the sequence. - * @param last {@link Iterator Forward iterator} to the final position of the sequence. The range checked is - * [first, last), which contains all the elements between first and last, - * including the element pointed by first but not the element pointed by last. - * @param compare Binary function that accepts two elements in the range as arguments, and returns a value convertible - * to bool. The value returned indicates whether the element passed as first argument is - * considered to go before the second in the specific strict weak ordering it defines. The function - * shall not modify any of its arguments. - * - * @return An iterator to the first element in the range which does not follow an ascending order, or last if - * all elements are sorted or if the range contains less than two elements. - */ - function is_sorted_until>(first: ForwardIterator, last: ForwardIterator, compare: (x: T, y: T) => boolean): ForwardIterator; -} -declare namespace std { - /** - *

Make heap from range.

- * - *

Rearranges the elements in the range [first, last) in such a way that they form a heap.

- * - *

A heap is a way to organize the elements of a range that allows for fast retrieval of the element with the - * highest value at any moment (with {@link pop_heap}), even repeatedly, while allowing for fast insertion of new - * elements (with {@link push_heap}).

- * - *

The element with the highest value is always pointed by first. The order of the other elements depends on the - * particular implementation, but it is consistent throughout all heap-related functions of this header.

- * - *

The elements are compared using {@link less}: The element with the highest value is an element for which this - * would return false when compared to every other element in the range.

- * - *

The standard container adaptor {@link PriorityQueue} calls {@link make_heap}, {@link push_heap} and - * {@link pop_heap} automatically to maintain heap properties for a container.

- * - * @param first {@link IArrayIterator Random-access iterator} to the initial position of the sequence to be - * transformed into a heap. - * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence to be transformed - * into a heap. The range used is [first, last), which contains all the elements between - * first and last, including the element pointed by first but not the element pointed - * by last. {@link IArrayIterator RandomAccessIterator} shall point to a type for which - * {@link Iterator.swap swap} is properly defined. - */ - function make_heap>(first: RandomAccessIterator, last: RandomAccessIterator): void; - /** - *

Make heap from range.

- * - *

Rearranges the elements in the range [first, last) in such a way that they form a heap.

- * - *

A heap is a way to organize the elements of a range that allows for fast retrieval of the element with the - * highest value at any moment (with {@link pop_heap}), even repeatedly, while allowing for fast insertion of new - * elements (with {@link push_heap}).

- * - *

The element with the highest value is always pointed by first. The order of the other elements depends on the - * particular implementation, but it is consistent throughout all heap-related functions of this header.

- * - *

The elements are compared using compare: The element with the highest value is an element for which this - * would return false when compared to every other element in the range.

- * - *

The standard container adaptor {@link PriorityQueue} calls {@link make_heap}, {@link push_heap} and - * {@link pop_heap} automatically to maintain heap properties for a container.

- * - * @param first {@link IArrayIterator Random-access iterator} to the initial position of the sequence to be - * transformed into a heap. - * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence to be transformed - * into a heap. The range used is [first, last), which contains all the elements between - * first and last, including the element pointed by first but not the element pointed - * by last. {@link IArrayIterator RandomAccessIterator} shall point to a type for which - * {@link Iterator.swap swap} is properly defined. - * @param compare Binary function that accepts two elements in the range as arguments, and returns a value - * convertible to boolean. The value returned indicates whether the element passed as - * first argument is considered to go before the second in the specific strict weak ordering it defines. - * The function shall not modify any of its arguments. This can either be a function pointer or a - * function object. - */ - function make_heap>(first: RandomAccessIterator, last: RandomAccessIterator, compare: (x: T, y: T) => boolean): void; - /** - *

Push element into heap range.

- * - *

Given a heap in the range [first, last - 1), this function extends the range considered a heap to - * [first, last) by placing the value in (last - 1) into its corresponding location within it. - *

- * - *

A range can be organized into a heap by calling {@link make_heap}. After that, its heap properties are - * preserved if elements are added and removed from it using {@link push_heap} and {@link pop_heap}, respectively. - *

- * - * @param first {@link IArrayIterator Random-access iterator} to the initial position of the new heap range, including - * the pushed element. - * @param last {@link IArrayIterator Random-access iterator} to the final position of the new heap range, including - * the pushed element. The range used is [first, last), which contains all the elements - * between first and last, including the element pointed by first but not the element - * pointed by last. {@link IArrayIterator RandomAccessIterator} shall point to a type for which - * {@link Iterator.swap swap} is properly defined. - */ - function push_heap>(first: RandomAccessIterator, last: RandomAccessIterator): void; - /** - *

Push element into heap range.

- * - *

Given a heap in the range [first, last - 1), this function extends the range considered a heap to - * [first, last) by placing the value in (last - 1) into its corresponding location within it. - *

- * - *

A range can be organized into a heap by calling {@link make_heap}. After that, its heap properties are - * preserved if elements are added and removed from it using {@link push_heap} and {@link pop_heap}, respectively. - *

- * - * @param first {@link IArrayIterator Random-access iterator} to the initial position of the new heap range, including - * the pushed element. - * @param last {@link IArrayIterator Random-access iterator} to the final position of the new heap range, including - * the pushed element. The range used is [first, last), which contains all the elements - * between first and last, including the element pointed by first but not the element - * pointed by last. {@link IArrayIterator RandomAccessIterator} shall point to a type for which - * {@link Iterator.swap swap} is properly defined. - * @param compare Binary function that accepts two elements in the range as arguments, and returns a value - * convertible to boolean. The value returned indicates whether the element passed as - * first argument is considered to go before the second in the specific strict weak ordering it defines. - * The function shall not modify any of its arguments. This can either be a function pointer or a - * function object. - */ - function push_heap>(first: RandomAccessIterator, last: RandomAccessIterator, compare: (x: T, y: T) => boolean): void; - /** - *

Pop element from heap range.

- * - *

Rearranges the elements in the heap range [first, last) in such a way that the part considered a - * heap is shortened by one: The element with the highest value is moved to (last - 1).

- * - *

While the element with the highest value is moved from first to (last - 1) (which now is out of the - * heap), the other elements are reorganized in such a way that the range [first, last - 1) preserves - * the properties of a heap.

- * - *

A range can be organized into a heap by calling {@link make_heap}. After that, its heap properties are - * preserved if elements are added and removed from it using {@link push_heap} and {@link pop_heap}, respectively. - *

- * - * @param first {@link IArrayIterator Random-access iterator} to the initial position of the heap to be shrank by one. - * @param last {@link IArrayIterator Random-access iterator} to the final position of the heap to be shrank by one. - * The range used is [first, last), which contains all the elements between first and - * last, including the element pointed by first but not the element pointed by last. - * {@link IArrayIterator RandomAccessIterator} shall point to a type for which {@link Iterator.swap swap} - * is properly defined. - */ - function pop_heap>(first: RandomAccessIterator, last: RandomAccessIterator): void; - /** - *

Pop element from heap range.

- * - *

Rearranges the elements in the heap range [first, last) in such a way that the part considered a - * heap is shortened by one: The element with the highest value is moved to (last - 1).

- * - *

While the element with the highest value is moved from first to (last - 1) (which now is out of the - * heap), the other elements are reorganized in such a way that the range [first, last - 1) preserves - * the properties of a heap.

- * - *

A range can be organized into a heap by calling {@link make_heap}. After that, its heap properties are - * preserved if elements are added and removed from it using {@link push_heap} and {@link pop_heap}, respectively. - *

- * - * @param first {@link IArrayIterator Random-access iterator} to the initial position of the heap to be shrank by one. - * @param last {@link IArrayIterator Random-access iterator} to the final position of the heap to be shrank by one. - * The range used is [first, last), which contains all the elements between first and - * last, including the element pointed by first but not the element pointed by last. - * {@link IArrayIterator RandomAccessIterator} shall point to a type for which {@link Iterator.swap swap} - * is properly defined. - * @param compare Binary function that accepts two elements in the range as arguments, and returns a value - * convertible to boolean. The value returned indicates whether the element passed as - * first argument is considered to go before the second in the specific strict weak ordering it defines. - * The function shall not modify any of its arguments. This can either be a function pointer or a - * function object. - */ - function pop_heap>(first: RandomAccessIterator, last: RandomAccessIterator, compare: (x: T, y: T) => boolean): void; - /** - *

Test if range is heap.

- * - *

Returns true if the range [first, last) forms a heap, as if constructed with {@link make_heap}. - *

- * - *

The elements are compared using {@link less}.

- * - * @param first {@link IArrayIterator Random-access iterator} to the initial position of the sequence. - * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence. The range used is - * [first, last), which contains all the elements between first and last, - * including the element pointed by first but not the element pointed by last. - * {@link IArrayIterator RandomAccessIterator} shall point to a type for which {@link Iterator.swap swap} - * is properly defined. - * - * @return true if the range [first, last) is a heap (as if constructed with - * {@link make_heap}), false otherwise. If the range [first, last) contains less - * than two elements, the function always returns true. - */ - function is_heap>(first: RandomAccessIterator, last: RandomAccessIterator): boolean; - /** - *

Test if range is heap.

- * - *

Returns true if the range [first, last) forms a heap, as if constructed with {@link make_heap}. - *

- * - *

The elements are compared using compare.

- * - * @param first {@link IArrayIterator Random-access iterator} to the initial position of the sequence. - * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence. The range used is - * [first, last), which contains all the elements between first and last, - * including the element pointed by first but not the element pointed by last. - * {@link IArrayIterator RandomAccessIterator} shall point to a type for which {@link Iterator.swap swap} - * is properly defined. - * @param compare Binary function that accepts two elements in the range as arguments, and returns a value - * convertible to boolean. The value returned indicates whether the element passed as - * first argument is considered to go before the second in the specific strict weak ordering it defines. - * The function shall not modify any of its arguments. This can either be a function pointer or a - * function object. - * - * @return true if the range [first, last) is a heap (as if constructed with - * {@link make_heap}), false otherwise. If the range [first, last) contains less - * than two elements, the function always returns true. - */ - function is_heap>(first: RandomAccessIterator, last: RandomAccessIterator, compare: (x: T, y: T) => boolean): boolean; - /** - *

Find first element not in heap order.

- * - *

Returns an iterator to the first element in the range [first, last) which is not in a valid - * position if the range is considered a heap (as if constructed with {@link make_heap}).

- * - *

The range between first and the iterator returned is a heap.

- * - *

If the entire range is a valid heap, the function returns last.

- * - *

The elements are compared using {@link less}.

- * - * @param first {@link IArrayIterator Random-access iterator} to the initial position of the sequence. - * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence. The range used is - * [first, last), which contains all the elements between first and last, - * including the element pointed by first but not the element pointed by last. - * {@link IArrayIterator RandomAccessIterator} shall point to a type for which {@link Iterator.swap swap} - * is properly defined. - */ - function is_heap_until>(first: RandomAccessIterator, last: RandomAccessIterator): RandomAccessIterator; - /** - *

Find first element not in heap order.

- * - *

Returns an iterator to the first element in the range [first, last) which is not in a valid - * position if the range is considered a heap (as if constructed with {@link make_heap}).

- * - *

The range between first and the iterator returned is a heap.

- * - *

If the entire range is a valid heap, the function returns last.

- * - *

The elements are compared using {@link less}.

- * - * @param first {@link IArrayIterator Random-access iterator} to the initial position of the sequence. - * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence. The range used is - * [first, last), which contains all the elements between first and last, - * including the element pointed by first but not the element pointed by last. - * {@link IArrayIterator RandomAccessIterator} shall point to a type for which {@link Iterator.swap swap} - * is properly defined. - * @param compare Binary function that accepts two elements in the range as arguments, and returns a value - * convertible to boolean. The value returned indicates whether the element passed as - * first argument is considered to go before the second in the specific strict weak ordering it defines. - * The function shall not modify any of its arguments. This can either be a function pointer or a - * function object. - */ - function is_heap_until>(first: RandomAccessIterator, last: RandomAccessIterator, compare: (x: T, y: T) => boolean): RandomAccessIterator; - /** - *

Sort elements of heap.

- * - *

Sorts the elements in the heap range [first, last) into ascending order.

- * - *

The elements are compared using {@link less}, which shall be the same as used to construct the heap.

- * - *

The range loses its properties as a heap.

- * - * @param first {@link IArrayIterator Random-access iterator} to the initial position of the sequence to be sorted. - * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence to be sorted. - * The range used is [first, last), which contains all the elements between first and - * last, including the element pointed by first but not the element pointed by last. - * {@link IArrayIterator RandomAccessIterator} shall point to a type for which {@link Iterator.swap swap} - * is properly defined. - */ - function sort_heap>(first: RandomAccessIterator, last: RandomAccessIterator): void; - /** - *

Sort elements of heap.

- * - *

Sorts the elements in the heap range [first, last) into ascending order.

- * - *

The elements are compared using compare, which shall be the same as used to construct the heap.

- * - *

The range loses its properties as a heap.

- * - * @param first {@link IArrayIterator Random-access iterator} to the initial position of the sequence to be sorted. - * @param last {@link IArrayIterator Random-access iterator} to the final position of the sequence to be sorted. - * The range used is [first, last), which contains all the elements between first and - * last, including the element pointed by first but not the element pointed by last. - * {@link IArrayIterator RandomAccessIterator} shall point to a type for which {@link Iterator.swap swap} - * is properly defined. - * @param compare Binary function that accepts two elements in the range as arguments, and returns a value - * convertible to boolean. The value returned indicates whether the element passed as - * first argument is considered to go before the second in the specific strict weak ordering it defines. - * The function shall not modify any of its arguments. This can either be a function pointer or a - * function object. - */ - function sort_heap>(first: RandomAccessIterator, last: RandomAccessIterator, compare: (x: T, y: T) => boolean): void; -} -declare namespace std { - /** - *

Return iterator to lower bound.

- * - *

Returns an iterator pointing to the first element in the range [first, last) which does not - * compare less than val.

- * - *

The elements are compared using {@link less}. The elements in the range shall already be {@link is_sorted sorted} - * according to this same criterion ({@link less}), or at least {@link is_partitioned partitioned} with respect to - * val.

- * - *

The function optimizes the number of comparisons performed by comparing non-consecutive elements of the sorted - * range, which is specially efficient for {@link IArrayIterator random-access iterators}.

- * - *

Unlike {@link upper_bound}, the value pointed by the iterator returned by this function may also be equivalent - * to val, and not only greater.

- * - * @param first {@link Iterator Forward iterator} to the initial position of a {@link is_sorted sorted} (or properly - * {@link is_partitioned partitioned}) sequence. - * @param last {@link Iterator Forward iterator} to the final position of a {@link is_sorted sorted} (or properly - * {@link is_partitioned partitioned}) sequence. The range used is [first, last), which - * contains all the elements between first and last, including the element pointed by - * first but not the element pointed by last. - * @param val Value of the lower bound to search for in the range. T shall be a type supporting being compared - * with elements of the range [first, last) as the left-hand side operand of {@link less}. - * - * @return An iterator to the lower bound of val in the range. If all the element in the range compare less than - * val, the function returns last. - */ - function lower_bound>(first: ForwardIterator, last: ForwardIterator, val: T): ForwardIterator; - /** - *

Return iterator to lower bound.

- * - *

Returns an iterator pointing to the first element in the range [first, last) which does not - * compare less than val.

- * - *

The elements are compared using compare. The elements in the range shall already be - * {@link is_sorted sorted} according to this same criterion (compare), or at least - * {@link is_partitioned partitioned} with respect to val.

- * - *

The function optimizes the number of comparisons performed by comparing non-consecutive elements of the sorted - * range, which is specially efficient for {@link IArrayIterator random-access iterators}.

- * - *

Unlike {@link upper_bound}, the value pointed by the iterator returned by this function may also be equivalent - * to val, and not only greater.

- * - * @param first {@link Iterator Forward iterator} to the initial position of a {@link is_sorted sorted} (or properly - * {@link is_partitioned partitioned}) sequence. - * @param last {@link Iterator Forward iterator} to the final position of a {@link is_sorted sorted} (or properly - * {@link is_partitioned partitioned}) sequence. The range used is [first, last), which - * contains all the elements between first and last, including the element pointed by - * first but not the element pointed by last. - * @param val Value of the lower bound to search for in the range. - * @param compare Binary function that accepts two arguments (the first of the type pointed by ForwardIterator, - * and the second, always val), and returns a value convertible to bool. The value - * returned indicates whether the first argument is considered to go before the second. The function - * shall not modify any of its arguments. - * - * @return An iterator to the lower bound of val in the range. If all the element in the range compare less than - * val, the function returns last. - */ - function lower_bound>(first: ForwardIterator, last: ForwardIterator, val: T, compare: (x: T, y: T) => boolean): ForwardIterator; - /** - *

Return iterator to upper bound.

- * - *

Returns an iterator pointing to the first element in the range [first, last) which compares - * greater than val.

- * - *

The elements are compared using {@link less}. The elements in the range shall already be {@link is_sorted sorted} - * according to this same criterion ({@link less}), or at least {@link is_partitioned partitioned} with respect to - * val.

- * - *

The function optimizes the number of comparisons performed by comparing non-consecutive elements of the sorted - * range, which is specially efficient for {@link IArrayIterator random-access iterators}.

- * - *

Unlike {@link lower_bound}, the value pointed by the iterator returned by this function cannot be equivalent to - * val, only greater.

- * - * @param first {@link Iterator Forward iterator} to the initial position of a {@link is_sorted sorted} (or properly - * {@link is_partitioned partitioned}) sequence. - * @param last {@link Iterator Forward iterator} to the final position of a {@link is_sorted sorted} (or properly - * {@link is_partitioned partitioned}) sequence. The range used is [first, last), which - * contains all the elements between first and last, including the element pointed by - * first but not the element pointed by last. - * @param val Value of the lower bound to search for in the range. T shall be a type supporting being compared - * with elements of the range [first, last) as the left-hand side operand of {@link less}. - * - * @return An iterator to the upper bound of val in the range. If no element in the range comparse greater than - * val, the function returns last. - */ - function upper_bound>(first: ForwardIterator, last: ForwardIterator, val: T): ForwardIterator; - /** - *

Return iterator to upper bound.

- * - *

Returns an iterator pointing to the first element in the range [first, last) which compares - * greater than val.

- * - *

The elements are compared using compare. The elements in the range shall already be - * {@link is_sorted sorted} according to this same criterion (compare), or at least - * {@link is_partitioned partitioned} with respect to val.

- * - *

The function optimizes the number of comparisons performed by comparing non-consecutive elements of the sorted - * range, which is specially efficient for {@link IArrayIterator random-access iterators}.

- * - *

Unlike {@link lower_bound}, the value pointed by the iterator returned by this function cannot be equivalent to - * val, only greater.

- * - * @param first {@link Iterator Forward iterator} to the initial position of a {@link is_sorted sorted} (or properly - * {@link is_partitioned partitioned}) sequence. - * @param last {@link Iterator Forward iterator} to the final position of a {@link is_sorted sorted} (or properly - * {@link is_partitioned partitioned}) sequence. The range used is [first, last), which - * contains all the elements between first and last, including the element pointed by - * first but not the element pointed by last. - * @param val Value of the lower bound to search for in the range. - * @param compare Binary function that accepts two arguments (the first of the type pointed by ForwardIterator, - * and the second, always val), and returns a value convertible to bool. The value - * returned indicates whether the first argument is considered to go before the second. The function - * shall not modify any of its arguments. - * - * @return An iterator to the upper bound of val in the range. If no element in the range comparse greater than - * val, the function returns last. - */ - function upper_bound>(first: ForwardIterator, last: ForwardIterator, val: T, compare: (x: T, y: T) => boolean): ForwardIterator; - /** - *

Get subrange of equal elements.

- * - *

Returns the bounds of the subrange that includes all the elements of the range [first, last) with - * values equivalent to val.

- * - *

The elements are compared using {@link less}. Two elements, ax/i> and y are considered equivalent - * if (!std.less(x, y) && !std.less(y, x)).

- * - *

The elements in the range shall already be {@link is_sorted sorted} according to this same criterion - * ({@link less}), or at least {@link is_partitioned partitioned} with respect to val.

- * - *

If val is not equivalent to any value in the range, the subrange returned has a length of zero, with both - * iterators pointing to the nearest value greater than val, if any, or to last, if val compares - * greater than all the elements in the range.

- * - * @param first {@link Iterator Forward iterator} to the initial position of a {@link is_sorted sorted} (or properly - * {@link is_partitioned partitioned}) sequence. - * @param last {@link Iterator Forward iterator} to the final position of a {@link is_sorted sorted} (or properly - * {@link is_partitioned partitioned}) sequence. The range used is [first, last), which - * contains all the elements between first and last, including the element pointed by - * first but not the element pointed by last. - * @param val Value of the lower bound to search for in the range. T shall be a type supporting being compared - * with elements of the range [first, last) as the left-hand side operand of {@link less}. - * - * @return A {@link Pair} object, whose member {@link Pair.first} is an iterator to the lower bound of the subrange of - * equivalent values, and {@link Pair.second} its upper bound. The values are the same as those that would be - * returned by functions {@link lower_bound} and {@link upper_bound} respectively. - */ - function equal_range>(first: ForwardIterator, last: ForwardIterator, val: T): Pair; - /** - *

Get subrange of equal elements.

- * - *

Returns the bounds of the subrange that includes all the elements of the range [first, last) with - * values equivalent to val.

- * - *

The elements are compared using compare. Two elements, ax/i> and y are considered equivalent - * if (!compare(x, y) && !compare(y, x)).

- * - *

The elements in the range shall already be {@link is_sorted sorted} according to this same criterion - * (compare), or at least {@link is_partitioned partitioned} with respect to val.

- * - *

If val is not equivalent to any value in the range, the subrange returned has a length of zero, with both - * iterators pointing to the nearest value greater than val, if any, or to last, if val compares - * greater than all the elements in the range.

- * - * @param first {@link Iterator Forward iterator} to the initial position of a {@link is_sorted sorted} (or properly - * {@link is_partitioned partitioned}) sequence. - * @param last {@link Iterator Forward iterator} to the final position of a {@link is_sorted sorted} (or properly - * {@link is_partitioned partitioned}) sequence. The range used is [first, last), which - * contains all the elements between first and last, including the element pointed by - * first but not the element pointed by last. - * @param val Value of the lower bound to search for in the range. - * @param compare Binary function that accepts two arguments of the type pointed by ForwardIterator (and of type - * T), and returns a value convertible to bool. The value returned indicates whether - * the first argument is considered to go before the second. The function shall not modify any of its - * arguments. - * - * @return A {@link Pair} object, whose member {@link Pair.first} is an iterator to the lower bound of the subrange of - * equivalent values, and {@link Pair.second} its upper bound. The values are the same as those that would be - * returned by functions {@link lower_bound} and {@link upper_bound} respectively. - */ - function equal_range>(first: ForwardIterator, last: ForwardIterator, val: T, compare: (x: T, y: T) => boolean): Pair; - /** - *

Get subrange of equal elements.

- * - *

Returns the bounds of the subrange that includes all the elements of the range [first, last) with - * values equivalent to val.

- * - *

The elements are compared using {@link less}. Two elements, x and y are considered equivalent - * if (!std.less(x, y) && !std.less(y, x)).

- * - *

The elements in the range shall already be {@link is_sorted sorted} according to this same criterion - * ({@link less}), or at least {@link is_partitioned partitioned} with respect to val.

- * - *

If val is not equivalent to any value in the range, the subrange returned has a length of zero, with both - * iterators pointing to the nearest value greater than val, if any, or to last, if val compares - * greater than all the elements in the range.

- * - * @param first {@link Iterator Forward iterator} to the initial position of a {@link is_sorted sorted} (or properly - * {@link is_partitioned partitioned}) sequence. - * @param last {@link Iterator Forward iterator} to the final position of a {@link is_sorted sorted} (or properly - * {@link is_partitioned partitioned}) sequence. The range used is [first, last), which - * contains all the elements between first and last, including the element pointed by - * first but not the element pointed by last. - * @param val Value of the lower bound to search for in the range. T shall be a type supporting being compared - * with elements of the range [first, last) as the left-hand side operand of {@link less}. - * - * @return true if an element equivalent to val is found, and false otherwise. - */ - function binary_search>(first: ForwardIterator, last: ForwardIterator, val: T): boolean; - /** - *

Get subrange of equal elements.

- * - *

Returns the bounds of the subrange that includes all the elements of the range [first, last) with - * values equivalent to val.

- * - *

The elements are compared using {compare}. Two elements, x and y are considered equivalent - * if (!compare(x, y) && !compare(y, x)).

- * - *

The elements in the range shall already be {@link is_sorted sorted} according to this same criterion - * (compare), or at least {@link is_partitioned partitioned} with respect to val.

- * - *

If val is not equivalent to any value in the range, the subrange returned has a length of zero, with both - * iterators pointing to the nearest value greater than val, if any, or to last, if val compares - * greater than all the elements in the range.

- * - * @param first {@link Iterator Forward iterator} to the initial position of a {@link is_sorted sorted} (or properly - * {@link is_partitioned partitioned}) sequence. - * @param last {@link Iterator Forward iterator} to the final position of a {@link is_sorted sorted} (or properly - * {@link is_partitioned partitioned}) sequence. The range used is [first, last), which - * contains all the elements between first and last, including the element pointed by - * first but not the element pointed by last. - * @param val Value of the lower bound to search for in the range. - * @param compare Binary function that accepts two arguments of the type pointed by ForwardIterator (and of type - * T), and returns a value convertible to bool. The value returned indicates whether - * the first argument is considered to go before the second. The function shall not modify any of its - * arguments. - * - * @return true if an element equivalent to val is found, and false otherwise. - */ - function binary_search>(first: ForwardIterator, last: ForwardIterator, val: T, compare: (x: T, y: T) => boolean): boolean; -} -declare namespace std { - /** - *

Test whether range is partitioned.

- * - *

Returns true if all the elements in the range [first, last) for which pred - * returns true precede those for which it returns false.

- * - *

If the range is {@link IContainer.empty empty}, the function returns true.

- * - * @param first {@link Iterator Input iterator} to the initial position of the sequence. - * @param last {@link Iterator Input iterator} to the final position of the sequence. The range used is - * [first, last), which contains all the elements between first and last, - * including the element pointed by first but not the element pointed by last. - * @param pred Unary function that accepts an element in the range as argument, and returns a value convertible to - * bool. The value returned indicates whether the element belongs to the first group (if - * true, the element is expected before all the elements for which it returns - * false). The function shall not modify its argument. - * - * @return true if all the elements in the range [first, last) for which pred returns - * true precede those for which it returns false. Otherwise it returns - * false. If the range is {@link IContainer.empty empty}, the function returns true. - */ - function is_partitioned>(first: InputIterator, last: InputIterator, pred: (x: T) => boolean): boolean; - /** - *

Partition range in two.

- * - *

Rearranges the elements from the range [first, last), in such a way that all the elements for - * which pred returns true precede all those for which it returns false. The iterator - * returned points to the first element of the second group.

- * - *

The relative ordering within each group is not necessarily the same as before the call. See - * {@link stable_partition} for a function with a similar behavior but with stable ordering within each group.

- * - * @param first {@link Iterator Forward iterator} to the initial position of the sequence to partition. - * @param last {@link Iterator Forward iterator} to the final position of the sequence to partition. The range used is - * [first, last), which contains all the elements between first and last, - * including the element pointed by first but not the element pointed by last. - * @param pred Unary function that accepts an element in the range as argument, and returns a value convertible to - * bool. The value returned indicates whether the element belongs to the first group (if - * true, the element is expected before all the elements for which it returns - * false). The function shall not modify its argument. - * - * @return An iterator that points to the first element of the second group of elements (those for which pred - * returns false), or last if this group is {@link IContainer.empty empty}. - */ - function partition>(first: BidirectionalIterator, last: BidirectionalIterator, pred: (x: T) => boolean): BidirectionalIterator; - /** - *

Partition range in two - stable ordering.

- * - *

Rearranges the elements in the range [first, last), in such a way that all the elements for which - * pred returns true precede all those for which it returns false, and, unlike - * function {@link partition}, the relative order of elements within each group is preserved.

- * - *

This is generally implemented using an internal temporary buffer.

- * - * @param first {@link Iterator Bidirectional iterator} to the initial position of the sequence to partition. - * @param last {@link Iterator Bidirectional iterator} to the final position of the sequence to partition. The range - * used is [first, last), which contains all the elements between first and - * last, including the element pointed by first but not the element pointed by last. - * @param pred Unary function that accepts an element in the range as argument, and returns a value convertible to - * bool. The value returned indicates whether the element belongs to the first group (if - * true, the element is expected before all the elements for which it returns - * false). The function shall not modify its argument. - * - * @return An iterator that points to the first element of the second group of elements (those for which pred - * returns false), or last if this group is {@link IContainer.empty empty}. - */ - function stable_partition>(first: BidirectionalIterator, last: BidirectionalIterator, pred: (x: T) => boolean): BidirectionalIterator; - /** - *

Partition range into two.

- * - *

Copies the elements in the range [first, last) for which pred returns true - * into the range pointed by result_true, and those for which it does not into the range pointed by - * result_false.

- * - * @param first {@link Iterator Input iterator} to the initial position of the range to be copy-partitioned. - * @param last {@link Iterator Input iterator} to the final position of the range to be copy-partitioned. The range - * used is [first, last), which contains all the elements between first and - * last, including the element pointed by first but not the element pointed by last. - * @param result_true {@link Iterator Output iterator} to the initial position of the range where the elements for - * which pred returns true are stored. - * @param result_false {@link Iterator Output iterator} to the initial position of the range where the elements for - * which pred returns false are stored. - * @param pred Unary function that accepts an element pointed by InputIterator as argument, and returns a value - * convertible to bool. The value returned indicates on which result range the element is - * copied. The function shall not modify its argument. - * - * @return A {@link Pair} of iterators with the end of the generated sequences pointed by result_true and - * result_false, respectivelly. Its member {@link Pair.first first} points to the element that follows - * the last element copied to the sequence of elements for which pred returned true. Its - * member {@link Pair.second second} points to the element that follows the last element copied to the sequence - * of elements for which pred returned false. - */ - function partition_copy, OutputIterator1 extends base.ILinearIterator, OutputIterator2 extends base.ILinearIterator>(first: InputIterator, last: InputIterator, result_true: OutputIterator1, result_false: OutputIterator2, pred: (val: T) => T): Pair; - /** - *

Get partition point.

- * - *

Returns an iterator to the first element in the partitioned range [first, last) for which - * pred is not true, indicating its partition point.

- * - *

The elements in the range shall already {@link is_partitioned be partitioned}, as if {@link partition} had been - * called with the same arguments.

- * - *

The function optimizes the number of comparisons performed by comparing non-consecutive elements of the sorted - * range, which is specially efficient for {@link Iteartor random-access iterators}.

- * - * @param first {@link Iterator Forward iterator} to the initial position of the partitioned sequence. - * @param last {@link Iterator Forward iterator} to the final position of the partitioned sequence. The range checked - * is [first, last), which contains all the elements between first an last, - * including the element pointed by first but not the element pointed by last. - * @param pred Unary function that accepts an element in the range as argument, and returns a value convertible to - * bool. The value returned indicates whether the element goes before the partition point (if - * true, it goes before; if false goes at or after it). The function shall not - * modify its argument. - * - * @return An iterator to the first element in the partitioned range [first, last) for which pred - * is not true, or last if it is not true for any element. - */ - function partition_point>(first: ForwardIterator, last: ForwardIterator, pred: (x: T) => boolean): ForwardIterator; -} -declare namespace std { - /** - *

Merge sorted ranges.

- * - *

Combines the elements in the sorted ranges [first1, last1) and [first2, last2), into - * a new range beginning at result with all its elements sorted.

- * - *

The elements are compared using {@link less}. The elements in both ranges shall already be ordered according to - * this same criterion ({@link less}). The resulting range is also sorted according to this.

- * - * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. - * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence. The range used is - * [first1, last1), which contains all the elements between first1 and last1, - * including the element pointed by first1 but not the element pointed by last1. - * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. - * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. The range used is - * [first2, last2). - * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting combined - * range is stored. Its size is equal to the sum of both ranges above. - * - * @return An iterator pointing to the past-the-end element in the resulting sequence. - */ - function merge, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator): OutputIterator; - /** - *

Merge sorted ranges.

- * - *

Combines the elements in the sorted ranges [first1, last1) and [first2, last2), into - * a new range beginning at result with all its elements sorted.

- * - *

The elements are compared using {@link less}. The elements in both ranges shall already be ordered according to - * this same criterion (compare). The resulting range is also sorted according to this.

- * - * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. - * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence. The range used is - * [first1, last1), which contains all the elements between first1 and last1, - * including the element pointed by first1 but not the element pointed by last1. - * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. - * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. The range used is - * [first2, last2). - * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting combined - * range is stored. Its size is equal to the sum of both ranges above. - * @param compare Binary function that accepts two arguments of the types pointed by the iterators, and returns a value - * convertible to bool. The value returned indicates whether the first argument is - * considered to go before the second in the specific strict weak ordering it defines. The - * function shall not modify any of its arguments. - * - * @return An iterator pointing to the past-the-end element in the resulting sequence. - */ - function merge, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator, compare: (x: T, y: T) => boolean): OutputIterator; - /** - *

Merge consecutive sorted ranges.

- * - *

Merges two consecutive sorted ranges: [first, middle) and [middle, last), putting - * the result into the combined sorted range [first, last).

- * - *

The elements are compared using {@link less}. The elements in both ranges shall already be ordered according to - * this same criterion ({@link less}). The resulting range is also sorted according to this.

- * - *

The function preserves the relative order of elements with equivalent values, with the elements in the first - * range preceding those equivalent in the second.

- * - * @param first {@link Iterator Bidirectional iterator} to the initial position in the first sorted sequence to merge. - * This is also the initial position where the resulting merged range is stored. - * @param middle {@link Iterator Bidirectional iterator} to the initial position of the second sorted sequence, which - * because both sequences must be consecutive, matches the past-the-end position of the first - * sequence. - * @param last {@link Iterator Bidirectional iterator} to the past-the-end position of the second sorted - * sequence. This is also the past-the-end position of the range where the resulting merged range is - * stored. - */ - function inplace_merge>(first: BidirectionalIterator, middle: BidirectionalIterator, last: BidirectionalIterator): void; - /** - *

Merge consecutive sorted ranges.

- * - *

Merges two consecutive sorted ranges: [first, middle) and [middle, last), putting - * the result into the combined sorted range [first, last).

- * - *

The elements are compared using compare. The elements in both ranges shall already be ordered according - * to this same criterion (compare). The resulting range is also sorted according to this.

- * - *

The function preserves the relative order of elements with equivalent values, with the elements in the first - * range preceding those equivalent in the second.

- * - * @param first {@link Iterator Bidirectional iterator} to the initial position in the first sorted sequence to merge. - * This is also the initial position where the resulting merged range is stored. - * @param middle {@link Iterator Bidirectional iterator} to the initial position of the second sorted sequence, which - * because both sequences must be consecutive, matches the past-the-end position of the first - * sequence. - * @param last {@link Iterator Bidirectional iterator} to the past-the-end position of the second sorted - * sequence. This is also the past-the-end position of the range where the resulting merged range is - * stored. - * @param compare Binary function that accepts two arguments of the types pointed by the iterators, and returns a value - * convertible to bool. The value returned indicates whether the first argument is - * considered to go before the second in the specific strict weak ordering it defines. The - * function shall not modify any of its arguments. - */ - function inplace_merge>(first: BidirectionalIterator, middle: BidirectionalIterator, last: BidirectionalIterator, compare: (x: T, y: T) => boolean): void; - /** - *

Test whether sorted range includes another sorted range.

- * - *

Returns true if the sorted range [first1, last1) contains all the elements in the - * sorted range [first2, last2).

- * - *

The elements are compared using {@link less}. Two elements, x and y are considered equivalent - * if (!std.less(x, y) && !std.less(y, x)).

- * - *

The elements in the range shall already be ordered according to this same criterion ({@link less}).

- * - * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. - * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence (which is tested on - * whether it contains the second sequence). The range used is [first1, last1), which - * contains all the elements between first1 and last1, including the element pointed by - * first1 but not the element pointed by last1. - * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. - * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. (which is tested - * on whether it is contained in the first sequence). The range used is [first2, last2). - * - * @return true if every element in the range [first2, last2) is contained in the range - * [first1, last1), false otherwise. If [first2, last2) is an empty - * range, the function returns true. - */ - function includes, InputIterator2 extends Iterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2): boolean; - /** - *

Test whether sorted range includes another sorted range.

- * - *

Returns true if the sorted range [first1, last1) contains all the elements in the - * sorted range [first2, last2).

- * - *

The elements are compared using compare. Two elements, x and y are considered equivalent - * if (!compare(x, y) && !compare(y, x)).

- * - *

The elements in the range shall already be ordered according to this same criterion (compare).

- * - * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. - * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence (which is tested on - * whether it contains the second sequence). The range used is [first1, last1), which - * contains all the elements between first1 and last1, including the element pointed by - * first1 but not the element pointed by last1. - * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. - * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. (which is tested - * on whether it is contained in the first sequence). The range used is [first2, last2). - * @param compare Binary function that accepts two elements as arguments (one from each of the two sequences, in the - * same order), and returns a value convertible to bool. The value returned indicates - * whether the element passed as first argument is considered to go before the second in the specific - * strict weak ordering it defines. The function shall not modify any of its arguments. - * - * @return true if every element in the range [first2, last2) is contained in the range - * [first1, last1), false otherwise. If [first2, last2) is an empty - * range, the function returns true. - */ - function includes, InputIterator2 extends Iterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, compare: (x: T, y: T) => boolean): boolean; - /** - *

Union of two sorted ranges.

- * - *

Constructs a sorted range beginning in the location pointed by result with the set union of the - * two sorted ranges [first1, last1) and [first2, last2).

- * - *

The union of two sets is formed by the elements that are present in either one of the sets, or in both. - * Elements from the second range that have an equivalent element in the first range are not copied to the resulting - * range.

- * - *

The elements are compared using {@link less}. Two elements, x and y are considered equivalent - * if (!std.less(x, y) && !std.less(y, x)).

- * - *

The elements in the ranges shall already be ordered according to this same criterion ({@link less}). The - * resulting range is also sorted according to this.

- * - * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. - * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence. The range used is - * [first1, last1), which contains all the elements between first1 and last1, - * including the element pointed by first1 but not the element pointed by last1. - * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. - * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. The range used is - * [first2, last2). - * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is - * stored. The pointed type shall support being assigned the value of an element from the other ranges. - * - * @return An iterator to the end of the constructed range. - */ - function set_union, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator): OutputIterator; - /** - *

Union of two sorted ranges.

- * - *

Constructs a sorted range beginning in the location pointed by result with the set union of the - * two sorted ranges [first1, last1) and [first2, last2).

- * - *

The union of two sets is formed by the elements that are present in either one of the sets, or in both. - * Elements from the second range that have an equivalent element in the first range are not copied to the resulting - * range.

- * - *

The elements are compared using compare. Two elements, x and y are considered equivalent - * if (!compare(x, y) && !compare(y, x)).

- * - *

The elements in the ranges shall already be ordered according to this same criterion (compare). The - * resulting range is also sorted according to this.

- * - * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. - * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence. The range used is - * [first1, last1), which contains all the elements between first1 and last1, - * including the element pointed by first1 but not the element pointed by last1. - * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. - * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. The range used is - * [first2, last2). - * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is - * stored. The pointed type shall support being assigned the value of an element from the other ranges. - * @param compare Binary function that accepts two arguments of the types pointed by the input iterators, and returns a - * value convertible to bool. The value returned indicates whether the first argument is - * considered to go before the second in the specific strict weak ordering it defines. The - * function shall not modify any of its arguments. - * - * @return An iterator to the end of the constructed range. - */ - function set_union, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator, compare: (x: T, y: T) => boolean): OutputIterator; - /** - *

Intersection of two sorted ranges.

- * - *

Constructs a sorted range beginning in the location pointed by result with the set intersection of - * the two sorted ranges [first1, last1) and [first2, last2).

- * - *

The intersection of two sets is formed only by the elements that are present in both sets. The elements - * copied by the function come always from the first range, in the same order.

- * - *

The elements are compared using {@link less}. Two elements, x and y are considered equivalent - * if (!std.less(x, y) && !std.less(y, x)).

- * - *

The elements in the ranges shall already be ordered according to this same criterion ({@link less}). The - * resulting range is also sorted according to this.

- * - * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. - * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence. The range used is - * [first1, last1), which contains all the elements between first1 and last1, - * including the element pointed by first1 but not the element pointed by last1. - * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. - * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. The range used is - * [first2, last2). - * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is - * stored. The pointed type shall support being assigned the value of an element from the first range. - * - * @return An iterator to the end of the constructed range. - */ - function set_intersection, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator): OutputIterator; - /** - *

Intersection of two sorted ranges.

- * - *

Constructs a sorted range beginning in the location pointed by result with the set intersection of - * the two sorted ranges [first1, last1) and [first2, last2).

- * - *

The intersection of two sets is formed only by the elements that are present in both sets. The elements - * copied by the function come always from the first range, in the same order.

- * - *

The elements are compared using compare. Two elements, x and y are considered equivalent - * if (!compare(x, y) && !compare(y, x)).

- * - *

The elements in the ranges shall already be ordered according to this same criterion (compare). The - * resulting range is also sorted according to this.

- * - * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. - * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence. The range used is - * [first1, last1), which contains all the elements between first1 and last1, - * including the element pointed by first1 but not the element pointed by last1. - * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. - * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. The range used is - * [first2, last2). - * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is - * stored. The pointed type shall support being assigned the value of an element from the first range. - * @param compare Binary function that accepts two arguments of the types pointed by the input iterators, and returns a - * value convertible to bool. The value returned indicates whether the first argument is - * considered to go before the second in the specific strict weak ordering it defines. The - * function shall not modify any of its arguments. - * - * @return An iterator to the end of the constructed range. - */ - function set_intersection, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator, compare: (x: T, y: T) => boolean): OutputIterator; - /** - *

Difference of two sorted ranges.

- * - *

Constructs a sorted range beginning in the location pointed by result with the set difference of - * the sorted range [first1, last1) with respect to the sorted range [first2, last2).

- * - *

The difference of two sets is formed by the elements that are present in the first set, but not in the - * second one. The elements copied by the function come always from the first range, in the same order.

- * - *

For containers supporting multiple occurrences of a value, the difference includes as many occurrences of - * a given value as in the first range, minus the amount of matching elements in the second, preserving order.

- * - *

Notice that this is a directional operation - for a symmetrical equivalent, see {@link set_symmetric_difference}. - *

- * - *

The elements are compared using {@link less}. Two elements, x and y are considered equivalent - * if (!std.less(x, y) && !std.less(y, x)).

- * - *

The elements in the ranges shall already be ordered according to this same criterion ({@link less}). The - * resulting range is also sorted according to this.

- * - * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. - * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence. The range used is - * [first1, last1), which contains all the elements between first1 and last1, - * including the element pointed by first1 but not the element pointed by last1. - * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. - * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. The range used is - * [first2, last2). - * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is - * stored. The pointed type shall support being assigned the value of an element from the first range. - * - * @return An iterator to the end of the constructed range. - */ - function set_difference, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator): OutputIterator; - /** - *

Difference of two sorted ranges.

- * - *

Constructs a sorted range beginning in the location pointed by result with the set difference of - * the sorted range [first1, last1) with respect to the sorted range [first2, last2).

- * - *

The difference of two sets is formed by the elements that are present in the first set, but not in the - * second one. The elements copied by the function come always from the first range, in the same order.

- * - *

For containers supporting multiple occurrences of a value, the difference includes as many occurrences of - * a given value as in the first range, minus the amount of matching elements in the second, preserving order.

- * - *

Notice that this is a directional operation - for a symmetrical equivalent, see {@link set_symmetric_difference}. - *

- * - *

The elements are compared using compare. Two elements, x and y are considered equivalent - * if (!compare(x, y) && !compare(y, x)).

- * - *

The elements in the ranges shall already be ordered according to this same criterion (compare). The - * resulting range is also sorted according to this.

- * - * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. - * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence. The range used is - * [first1, last1), which contains all the elements between first1 and last1, - * including the element pointed by first1 but not the element pointed by last1. - * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. - * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. The range used is - * [first2, last2). - * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is - * stored. The pointed type shall support being assigned the value of an element from the first range. - * @param compare Binary function that accepts two arguments of the types pointed by the input iterators, and returns a - * value convertible to bool. The value returned indicates whether the first argument is - * considered to go before the second in the specific strict weak ordering it defines. The - * function shall not modify any of its arguments. - * - * @return An iterator to the end of the constructed range. - */ - function set_difference, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator, compare: (x: T, y: T) => boolean): OutputIterator; - /** - *

Symmetric difference of two sorted ranges.

- * - *

Constructs a sorted range beginning in the location pointed by0 result with the set - * symmetric difference of the two sorted ranges [first1, last1) and [first2, last2). - *

- * - *

The symmetric difference of two sets is formed by the elements that are present in one of the sets, but - * not in the other. Among the equivalent elements in each range, those discarded are those that appear before in the - * existent order before the call. The existing order is also preserved for the copied elements.

- * - *

The elements are compared using {@link less}. Two elements, x and y are considered equivalent - * if (!std.less(x, y) && !std.less(y, x)).

- * - *

The elements in the ranges shall already be ordered according to this same criterion ({@link std.less}). The - * resulting range is also sorted according to this.

- * - * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. - * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence. The range used is - * [first1, last1), which contains all the elements between first1 and last1, - * including the element pointed by first1 but not the element pointed by last1. - * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. - * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. The range used is - * [first2, last2). - * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is - * stored. The pointed type shall support being assigned the value of an element from the other ranges. - * @param compare Binary function that accepts two arguments of the types pointed by the input iterators, and returns a - * value convertible to bool. The value returned indicates whether the first argument is - * considered to go before the second in the specific strict weak ordering it defines. The - * function shall not modify any of its arguments. - * - * @return An iterator to the end of the constructed range. - */ - function set_symmetric_difference, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator): OutputIterator; - /** - *

Symmetric difference of two sorted ranges.

- * - *

Constructs a sorted range beginning in the location pointed by0 result with the set - * symmetric difference of the two sorted ranges [first1, last1) and [first2, last2). - *

- * - *

The symmetric difference of two sets is formed by the elements that are present in one of the sets, but - * not in the other. Among the equivalent elements in each range, those discarded are those that appear before in the - * existent order before the call. The existing order is also preserved for the copied elements.

- * - *

The elements are compared using compare. Two elements, x and y are considered equivalent - * if (!compare(x, y) && !compare(y, x)).

- * - *

The elements in the ranges shall already be ordered according to this same criterion (compare). The - * resulting range is also sorted according to this.

- * - * @param first1 {@link Iterator Input iterator} to the initial position of the first sorted sequence. - * @param last1 {@link Iterator Input iterator} to the final position of the first sorted sequence. The range used is - * [first1, last1), which contains all the elements between first1 and last1, - * including the element pointed by first1 but not the element pointed by last1. - * @param first2 {@link Iterator Input iterator} to the initial position of the second sorted sequence. - * @param last2 {@link Iterator Input iterator} to the final position of the second sorted sequence. The range used is - * [first2, last2). - * @param result {@link Iterator Output iterator} to the initial position of the range where the resulting sequence is - * stored. The pointed type shall support being assigned the value of an element from the other ranges. - * @param compare Binary function that accepts two arguments of the types pointed by the input iterators, and returns a - * value convertible to bool. The value returned indicates whether the first argument is - * considered to go before the second in the specific strict weak ordering it defines. The - * function shall not modify any of its arguments. - * - * @return An iterator to the end of the constructed range. - */ - function set_symmetric_difference, InputIterator2 extends Iterator, OutputIterator extends base.ILinearIterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator, compare: (x: T, y: T) => boolean): OutputIterator; -} -declare namespace std { - /** - *

Return the smallest.

- * - *

Returns the smallest of all the elements in the args.

- * - * @param args Values to compare. - * - * @return The lesser of the values passed as arguments. - */ - function min(...args: T[]): T; - /** - *

Return the largest.

- * - *

Returns the largest of all the elements in the args.

- * - * @param args Values to compare. - * - * @return The largest of the values passed as arguments. - */ - function max(...args: T[]): T; - /** - *

Return smallest and largest elements.

- * - *

Returns a {@link Pair} with the smallest of all the elements in the args as first element (the first of - * them, if there are more than one), and the largest as second (the last of them, if there are more than one).

- * - * @param args Values to compare. - * - * @return The lesser and greatest of the values passed as arguments. - */ - function minmax(...args: T[]): Pair; - /** - *

Return smallest element in range.

- * - *

Returns an iterator pointing to the element with the smallest value in the range [first, last). - *

- * - *

The comparisons are performed using either {@link less}; An element is the smallest if no other element - * compares less than it. If more than one element fulfills this condition, the iterator returned points to the first - * of such elements.

- * - * @param first {@link Iteartor Input iterator} to the initial final position of the sequence to compare. - * @param last {@link Iteartor Input iterator} to the final final position of the sequence to compare. The range used - * is [first, last), which contains all the elements between first and last, - * including the element pointed by first but not the element pointed by last. - * - * @return An iterator to smallest value in the range, or last if the range is empty. - */ - function min_element>(first: ForwardIterator, last: ForwardIterator): ForwardIterator; - /** - *

Return smallest element in range.

- * - *

Returns an iterator pointing to the element with the smallest value in the range [first, last). - *

- * - *

The comparisons are performed using either compare; An element is the smallest if no other element - * compares less than it. If more than one element fulfills this condition, the iterator returned points to the first - * of such elements.

- * - * @param first {@link Iteartor Input iterator} to the initial final position of the sequence to compare. - * @param last {@link Iteartor Input iterator} to the final final position of the sequence to compare. The range used - * is [first, last), which contains all the elements between first and last, - * including the element pointed by first but not the element pointed by last. - * @param compare Binary function that accepts two elements in the range as arguments, and returns a value convertible - * to bool. The value returned indicates whether the element passed as first argument is - * considered less than the second. The function shall not modify any of its arguments. - * - * @return An iterator to smallest value in the range, or last if the range is empty. - */ - function min_element>(first: ForwardIterator, last: ForwardIterator, compare: (x: T, y: T) => boolean): ForwardIterator; - /** - *

Return largest element in range.

- * - *

Returns an iterator pointing to the element with the largest value in the range [first, last). - *

- * - *

The comparisons are performed using either {@link greater}; An element is the largest if no other element - * compares less than it. If more than one element fulfills this condition, the iterator returned points to the first - * of such elements.

- * - * @param first {@link Iteartor Input iterator} to the initial final position of the sequence to compare. - * @param last {@link Iteartor Input iterator} to the final final position of the sequence to compare. The range used - * is [first, last), which contains all the elements between first and last, - * including the element pointed by first but not the element pointed by last. - * - * @return An iterator to largest value in the range, or last if the range is empty. - */ - function max_element>(first: ForwardIterator, last: ForwardIterator): ForwardIterator; - /** - *

Return largest element in range.

- * - *

Returns an iterator pointing to the element with the largest value in the range [first, last). - *

- * - *

The comparisons are performed using either compare; An element is the largest if no other element - * compares less than it. If more than one element fulfills this condition, the iterator returned points to the first - * of such elements.

- * - * @param first {@link Iteartor Input iterator} to the initial final position of the sequence to compare. - * @param last {@link Iteartor Input iterator} to the final final position of the sequence to compare. The range used - * is [first, last), which contains all the elements between first and last, - * including the element pointed by first but not the element pointed by last. - * @param compare Binary function that accepts two elements in the range as arguments, and returns a value convertible - * to bool. The value returned indicates whether the element passed as first argument is - * considered less than the second. The function shall not modify any of its arguments. - * - * @return An iterator to largest value in the range, or last if the range is empty. - */ - function max_element>(first: ForwardIterator, last: ForwardIterator, compare: (x: T, y: T) => boolean): ForwardIterator; - /** - *

Return smallest and largest elements in range.

- * - *

Returns a {@link Pair} with an iterator pointing to the element with the smallest value in the range - * [first, last) as first element, and the largest as second.

- * - *

The comparisons are performed using either {@link less} and {@link greater}.

- * - *

If more than one equivalent element has the smallest value, the first iterator points to the first of such - * elements.

- * - *

If more than one equivalent element has the largest value, the second iterator points to the last of such - * elements.

- * - * @param first {@link Iteartor Input iterator} to the initial final position of the sequence to compare. - * @param last {@link Iteartor Input iterator} to the final final position of the sequence to compare. The range used - * is [first, last), which contains all the elements between first and last, - * including the element pointed by first but not the element pointed by last. - * @param compare Binary function that accepts two elements in the range as arguments, and returns a value convertible - * to bool. The value returned indicates whether the element passed as first argument is - * considered less than the second. The function shall not modify any of its arguments. - * - * @return A {@link Pair} with an iterator pointing to the element with the smallest value in the range - * [first, last) as first element, and the largest as second. - */ - function minmax_element>(first: ForwardIterator, last: ForwardIterator): Pair; - /** - *

Return smallest and largest elements in range.

- * - *

Returns a {@link Pair} with an iterator pointing to the element with the smallest value in the range - * [first, last) as first element, and the largest as second.

- * - *

The comparisons are performed using either compare.

- * - *

If more than one equivalent element has the smallest value, the first iterator points to the first of such - * elements.

- * - *

If more than one equivalent element has the largest value, the second iterator points to the last of such - * elements.

- * - * @param first {@link Iteartor Input iterator} to the initial final position of the sequence to compare. - * @param last {@link Iteartor Input iterator} to the final final position of the sequence to compare. The range used - * is [first, last), which contains all the elements between first and last, - * including the element pointed by first but not the element pointed by last. - * @param compare Binary function that accepts two elements in the range as arguments, and returns a value convertible - * to bool. The value returned indicates whether the element passed as first argument is - * considered less than the second. The function shall not modify any of its arguments. - * - * @return A {@link Pair} with an iterator pointing to the element with the smallest value in the range - * [first, last) as first element, and the largest as second. - */ - function minmax_element>(first: ForwardIterator, last: ForwardIterator, compare: (x: T, y: T) => boolean): Pair; - /** - *

Test whether range is permutation of another.

- * - *

Compares the elements in the range [first1, last1) with those in the range beginning at - * first2, and returns true if all of the elements in both ranges match, even in a different - * order.

- * - * @param first1 An {@link Iterator} to the initial position of the first sequence. - * @param last1 An {@link Iterator} to the final position in a sequence. The range used is - * [first1, last1), including the element pointed by first1, but not the element - * pointed by last1. - * @param first2 An {@link Iterator} to the initial position of the second sequence. The comparison includes up to - * as many elements of this sequence as those in the range [first1, last1). - * - * @return true if all the elements in the range [first1, last1) compare equal to those - * of the range starting at first2 in any order, and false otherwise. - */ - function is_permutation, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2): boolean; - /** - *

Test whether range is permutation of another.

- * - *

Compares the elements in the range [first1, last1) with those in the range beginning at - * first2, and returns true if all of the elements in both ranges match, even in a different - * order.

- * - * @param first1 An {@link Iterator} to the initial position of the first sequence. - * @param last1 An {@link Iterator} to the final position in a sequence. The range used is - * [first1, last1), including the element pointed by first1, but not the element - * pointed by last1. - * @param first2 An {@link Iterator} to the initial position of the second sequence. The comparison includes up to - * as many elements of this sequence as those in the range [first1, last1). - * @param pred Binary function that accepts two elements as argument (one of each of the two sequences, in the same - * order), and returns a value convertible to bool. The value returned indicates whether - * the elements are considered to match in the context of this function. - * - * @return true if all the elements in the range [first1, last1) compare equal to those - * of the range starting at first2 in any order, and false otherwise. - */ - function is_permutation, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, pred: (x: T, y: T) => boolean): boolean; - /** - * Transform range to previous permutation. - * - * Rearranges the elements in the range [*first*, *last*) into the previous *lexicographically-ordered* permutation. - * - * A *permutation* is each one of the N! possible arrangements the elements can take (where *N* is the number of - * elements in the range). Different permutations can be ordered according to how they compare - * {@link lexicographicaly lexicographical_compare} to each other; The first such-sorted possible permutation (the one - * that would compare *lexicographically smaller* to all other permutations) is the one which has all its elements - * sorted in ascending order, and the largest has all its elements sorted in descending order. - * - * The comparisons of individual elements are performed using the {@link std.less std.less()} function. - * - * If the function can determine the previous permutation, it rearranges the elements as such and returns true. If - * that was not possible (because it is already at the lowest possible permutation), it rearranges the elements - * according to the last permutation (sorted in descending order) and returns false. - * - * @param first Bidirectional iterators to the initial positions of the sequence - * @param last Bidirectional iterators to the final positions of the sequence. The range used is [*first*, *last*), - * which contains all the elements between *first* and *last*, including the element pointed by *first* - * but not the element pointed by *last*. - * - * @return true if the function could rearrange the object as a lexicographicaly smaller permutation. Otherwise, the - * function returns false to indicate that the arrangement is not less than the previous, but the largest - * possible (sorted in descending order). - */ - function prev_permutation>(first: BidirectionalIterator, last: BidirectionalIterator): boolean; - /** - * Transform range to previous permutation. - * - * Rearranges the elements in the range [*first*, *last*) into the previous *lexicographically-ordered* permutation. - * - * A *permutation* is each one of the N! possible arrangements the elements can take (where *N* is the number of - * elements in the range). Different permutations can be ordered according to how they compare - * {@link lexicographicaly lexicographical_compare} to each other; The first such-sorted possible permutation (the one - * that would compare *lexicographically smaller* to all other permutations) is the one which has all its elements - * sorted in ascending order, and the largest has all its elements sorted in descending order. - * - * The comparisons of individual elements are performed using the *compare*. - * - * If the function can determine the previous permutation, it rearranges the elements as such and returns true. If - * that was not possible (because it is already at the lowest possible permutation), it rearranges the elements - * according to the last permutation (sorted in descending order) and returns false. - * - * @param first Bidirectional iterators to the initial positions of the sequence - * @param last Bidirectional iterators to the final positions of the sequence. The range used is [*first*, *last*), - * which contains all the elements between *first* and *last*, including the element pointed by *first* - * but not the element pointed by *last*. - * @param compare Binary function that accepts two arguments of the type pointed by BidirectionalIterator, and returns - * a value convertible to bool. The value returned indicates whether the first argument is considered - * to go before the second in the specific strict weak ordering it defines. - * - * @return true if the function could rearrange the object as a lexicographicaly smaller permutation. Otherwise, the - * function returns false to indicate that the arrangement is not less than the previous, but the largest - * possible (sorted in descending order). - */ - function prev_permutation>(first: BidirectionalIterator, last: BidirectionalIterator, compare: (x: T, y: T) => boolean): boolean; - /** - * Transform range to next permutation. - * - * Rearranges the elements in the range [*first*, *last*) into the next *lexicographically greater* permutation. - * - * A permutation is each one of the *N!* possible arrangements the elements can take (where *N* is the number of - * elements in the range). Different permutations can be ordered according to how they compare - * {@link lexicographicaly lexicographical_compare} to each other; The first such-sorted possible permutation (the one - * that would compare *lexicographically smaller* to all other permutations) is the one which has all its elements - * sorted in ascending order, and the largest has all its elements sorted in descending order. - * - * The comparisons of individual elements are performed using the {@link std.less} function. - * - * If the function can determine the next higher permutation, it rearranges the elements as such and returns true. If - * that was not possible (because it is already at the largest possible permutation), it rearranges the elements - * according to the first permutation (sorted in ascending order) and returns false. - * - * @param first Bidirectional iterators to the initial positions of the sequence - * @param last Bidirectional iterators to the final positions of the sequence. The range used is [*first*, *last*), - * which contains all the elements between *first* and *last*, including the element pointed by *first* - * but not the element pointed by *last*. - * - * @return true if the function could rearrange the object as a lexicographicaly greater permutation. Otherwise, the - * function returns false to indicate that the arrangement is not greater than the previous, but the lowest - * possible (sorted in ascending order). - */ - function next_permutation>(first: BidirectionalIterator, last: BidirectionalIterator): boolean; - /** - * Transform range to next permutation. - * - * Rearranges the elements in the range [*first*, *last*) into the next *lexicographically greater* permutation. - * - * A permutation is each one of the *N!* possible arrangements the elements can take (where *N* is the number of - * elements in the range). Different permutations can be ordered according to how they compare - * {@link lexicographicaly lexicographical_compare} to each other; The first such-sorted possible permutation (the one - * that would compare *lexicographically smaller* to all other permutations) is the one which has all its elements - * sorted in ascending order, and the largest has all its elements sorted in descending order. - * - * The comparisons of individual elements are performed using the *compare*. - * - * If the function can determine the next higher permutation, it rearranges the elements as such and returns true. If - * that was not possible (because it is already at the largest possible permutation), it rearranges the elements - * according to the first permutation (sorted in ascending order) and returns false. - * - * @param first Bidirectional iterators to the initial positions of the sequence - * @param last Bidirectional iterators to the final positions of the sequence. The range used is [*first*, *last*), - * which contains all the elements between *first* and *last*, including the element pointed by *first* - * but not the element pointed by *last*. - * @param compare Binary function that accepts two arguments of the type pointed by BidirectionalIterator, and returns - * a value convertible to bool. The value returned indicates whether the first argument is considered - * to go before the second in the specific strict weak ordering it defines. - * - * @return true if the function could rearrange the object as a lexicographicaly greater permutation. Otherwise, the - * function returns false to indicate that the arrangement is not greater than the previous, but the lowest - * possible (sorted in ascending order). - */ - function next_permutation>(first: BidirectionalIterator, last: BidirectionalIterator, compare: (x: T, y: T) => boolean): boolean; -} -declare namespace std.base { - /** - *

Static class holding enumeration codes of color of Red-black tree.

- * - *

Color codes imposed to nodes of RB-Tree are following those rules:

- * - *
    - *
  1. A node is either red or black.
  2. - *
  3. The root is black. This rule is sometimes omitted. Since the root can - * always be changed from red to black, but not - * necessarily vice versa, this rule has little effect on analysis.
  4. - *
  5. All leaves (NIL; null) are black.
  6. - *
  7. If a node is red, then both its children are - * black.
  8. - *
  9. Every path from a given node to any of its descendant NIL nodes contains the same number of - * black nodes. Some definitions: the number of - * black nodes from the root to a node is the node's - * black depth; the uniform number of black - * nodes in all paths from root to the leaves is called the black-height of - * the red-black tree.
  10. - *
- * - * @author Migrated by Jeongho Nam - */ - enum Color { - /** - *

Code of color black.

- * - *
    - *
  • Those are clearly black: root, leaf nodes or children nodes of red.
  • - *
  • Every path from a given nodes containes the same number of black nodes exclude NIL(s).
  • - *
- */ - BLACK = 0, - /** - *

Code of color red.

- */ - RED = 1, - } -} -declare namespace std.base { - /** - *

An abstract container.

- * - *

- * - *

- * - *

Container properties

- *
- *
Sequence
- *
Elements in sequence containers are ordered in a strict linear sequence. Individual elements are - * accessed by their position in this sequence.
- * - *
Doubly-linked list
- *
Each element keeps information on how to locate the next and the previous elements, allowing - * constant time insert and erase operations before or after a specific element (even of entire ranges), - * but no direct random access.
- *
- * - * @param Type of elements. - * - * @author Jeongho Nam - */ - abstract class Container implements IContainer { - /** - * Default Constructor. - */ - protected constructor(); - /** - * @inheritdoc - */ - abstract assign>(begin: InputIterator, end: InputIterator): void; - /** - * @inheritdoc - */ - clear(): void; - /** - * @inheritdoc - */ - abstract begin(): Iterator; - /** - * @inheritdoc - */ - abstract end(): Iterator; - /** - * @inheritdoc - */ - abstract rbegin(): base.IReverseIterator; - /** - * @inheritdoc - */ - abstract rend(): base.IReverseIterator; - /** - * @inheritdoc - */ - abstract size(): number; - /** - * @inheritdoc - */ - empty(): boolean; - /** - * @inheritdoc - */ - abstract push(...items: T[]): number; - /** - * @inheritdoc - */ - abstract insert(position: Iterator, val: T): Iterator; - /** - * @inheritdoc - */ - abstract erase(position: Iterator): Iterator; - /** - * @inheritdoc - */ - abstract erase(begin: Iterator, end: Iterator): Iterator; - /** - * @inheritdoc - */ - swap(obj: IContainer): void; - } -} -declare namespace std.base { - /** - *

An abstract error instance.

- * - *

{@link ErrorInstance} is an abstract class of {@link ErrorCode} and {@link ErrorCondition} - * holding an error instance's identifier {@link value}, associated with a {@link category}.

- * - *

The operating system and other low-level applications and libraries generate numerical error codes to - * represent possible results. These numerical values may carry essential information for a specific platform, - * but be non-portable from one platform to another.

- * - *

Objects of this class associate such numerical codes to {@link ErrorCategory error categories}, - * so that they can be interpreted when needed as more abstract (and portable) - * {@link ErrorCondition error conditions}.

- * - *

- *

- * - * @author Jeongho Nam - */ - abstract class ErrorInstance { - /** - * @hidden - */ - protected category_: ErrorCategory; - /** - * @hidden - */ - protected value_: number; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from a numeric value and error category. - * - * @param val A numerical value identifying an error instance. - * @param category A reference to an {@link ErrorCategory} object. - */ - constructor(val: number, category: ErrorCategory); - /** - *

Assign error instance.

- * - *

Assigns the {@link ErrorCode} object a value of val associated with the {@link ErrorCategory}.

- * - * @param val A numerical value identifying an error instance. - * @param category A reference to an {@link ErrorCategory} object. - */ - assign(val: number, category: ErrorCategory): void; - /** - *

Clear error instance.

- * - *

Clears the value in the {@link ErrorCode} object so that it is set to a value of 0 of the - * {@link ErrorCategory.systemCategory ErrorCategory.systemCategory()} (indicating no error).

- */ - clear(): void; - /** - *

Get category.

- * - *

Returns a reference to the {@link ErrorCategory} associated with the {@link ErrorCode} object.

- * - * @return A reference to a non-copyable object of a type derived from {@link ErrorCategory}. - */ - category(): ErrorCategory; - /** - *

Error value.

- * - *

Returns the error value associated with the {@link ErrorCode} object.

- * - * @return The error value. - */ - value(): number; - /** - *

Get message.

- * - *

Returns the message associated with the error instance.

- * - *

Error messages are defined by the {@link category} the error instance belongs to.

- * - *

This function returns the same as if the following member was called:

- * - *

category().message(value())

- * - * @return A string object with the message associated with the {@link ErrorCode}. - */ - message(): string; - /** - *

Default error condition.

- * - *

Returns the default {@link ErrorCondition}object associated with the {@link ErrorCode} object.

- * - *

This function returns the same as if the following member was called:

- * - *

category().default_error_condition(value())

- * - *

{@link ErrorCategory.default_error_condition ErrorCategory.default_error_condition()} - * is a virtual member function, that can operate differently for each category.

- * - * @return An {@link ErrorCondition}object that corresponds to the {@link ErrorCode} object. - */ - default_error_condition(): ErrorCondition; - /** - *

Convert to bool.

- * - *

Returns whether the error instance has a numerical {@link value} other than 0.

- * - *

If it is zero (which is generally used to represent no error), the function returns false, otherwise it returns true.

- * - * @return true if the error's numerical value is not zero. - * false otherwise. - */ - to_bool(): boolean; - } -} -declare namespace std.base { - enum Hash { - MIN_SIZE = 10, - RATIO = 1, - MAX_RATIO = 2, - } - /** - *

Hask buckets.

- * - * @author Jeongho Nam - */ - abstract class HashBuckets { - /** - * @hidden - */ - private buckets_; - /** - * @hidden - */ - private item_size_; - /** - * Default Constructor. - */ - protected constructor(); - /** - *

Reconstruction of hash table.

- * - *

All the elements in the hash buckets are rearranged according to their hash value into the new set of - * buckets. This may alter the order of iteration of elements within the container.

- * - *

Notice that {@link rehash rehashes} are automatically performed whenever its number of elements is going - * to greater than its own {@link capacity}.

- * - * @param size Number of bucket size to rehash. - */ - rehash(size: number): void; - clear(): void; - size(): number; - item_size(): number; - capacity(): number; - at(index: number): Vector; - hash_index(val: T): number; - insert(val: T): void; - erase(val: T): void; - } -} -declare namespace std.base { - /** - *

Common interface for hash map.

- * - *

{@link IHashMap}s are associative containers that store elements formed by the combination of - * a key value and a mapped value.

- * - *

In an {@link IHashMap}, the key value is generally used to uniquely identify the - * element, while the mapped value is an object with the content associated to this key. - * Types of key and mapped value may differ.

- * - *

Internally, the elements in the {@link IHashMap} are not sorted in any particular order with - * respect to either their key or mapped values, but organized into buckets depending on - * their hash values to allow for fast access to individual elements directly by their key values - * (with a constant average time complexity on average).

- * - *

Elements with equivalent keys are grouped together in the same bucket and in such a way that - * an iterator can iterate through all of them. Iterators in the container are doubly linked iterators.

- * - *

- * - *

- * - *

Container properties

- *
- *
Associative
- *
Elements in associative containers are referenced by their key and not by their absolute - * position in the container.
- * - *
Hashed
- *
Hashed containers organize their elements using hash tables that allow for fast access to elements - * by their key.
- * - *
Map
- *
Each element associates a key to a mapped value: - * Keys are meant to identify the elements whose main content is the mapped value.
- *
- * - * @param Type of the key values. - * Each element in an {@link IHashMap} is identified by a key value. - * @param Type of the mapped value. - * Each element in an {@link IHashMap} is used to store some data as its mapped value. - * - * @reference http://www.cplusplus.com/reference/unordered_map - * @author Jeongho Nam - */ - interface IHashMap { - /** - *

Return iterator to beginning.

- * - *

Returns an iterator pointing to the first element in the {@link IHashMap}.

- * - *

Notice that an {@link IHashMap} object makes no guarantees on which specific element is considered its - * first element. But, in any case, the range that goes from its begin to its end covers all the elements in the - * container, until invalidated.

- * - * @return An iterator to the first element in the container. - */ - begin(): MapIterator; - /** - *

Return iterator to beginning.

- * - *

Returns an iterator pointing to the first element in one of buckets in the {@link IHashMap}.

- * - *

Notice that an {@link IHashMap} object makes no guarantees on which specific element is considered its - * first element. But, in any case, the range that goes from its begin to its end covers all the elements in the - * bucket, until invalidated.

- * - * @param index Bucket number. This shall be lower than {@link bucket_count}. - * - * @return An iterator to the first element in the bucket. - */ - begin(index: number): MapIterator; - /** - *

Return iterator to end.

- * - *

Returns an iterator pointing to the past-the-end element in the {@link HaspMap} container.

- * - *

The iterator returned by end does not point to any element, but to the position that follows the last - * element in the {@link HaspMap} container (its past-the-end position). Thus, the value returned shall - * not be dereferenced - it is generally used to describe the open-end of a range, such as - * [begin, end).

- * - *

Notice that an {@link IHashMap} object makes no guarantees on which order its elements follow. But, in any - * case, the range that goes from its begin to its end covers all the elements in the container (or the bucket), - * until invalidated.

- * - * @return An iterator to the element past the end of the container. - */ - end(): MapIterator; - /** - *

Return iterator to end.

- * - *

Returns an iterator pointing to the past-the-end element in the {@link HaspMap} container.

- * - *

The iterator returned by end does not point to any element, but to the position that follows the last - * element in the {@link HaspMap} container (its past-the-end position). Thus, the value returned shall - * not be dereferenced - it is generally used to describe the open-end of a range, such as - * [begin, end).

- * - *

Notice that an {@link IHashMap} object makes no guarantees on which order its elements follow. But, in any - * case, the range that goes from its begin to its end covers all the elements in the container (or the bucket), - * until invalidated.

- * - * @param index Bucket number. This shall be lower than {@link bucket_count}. - * - * @return An iterator to the element past the end of the bucket. - */ - end(index: number): MapIterator; - /** - *

Return {@link MapReverseIterator reverse iterator} to reverse beginning.

- * - *

Returns a {@link MapReverseIterator reverse iterator} pointing to the last element in the {@link IHashMap} - * (i.e., its reverse beginning).

- * - * {@link MapReverseIterator Reverse iterators} iterate backwards: increasing them moves them towards the - * beginning of the container.

- * - *

{@link rbegin} points to the element preceding the one that would be pointed to by member {@link end}.

- * - *

Notice that an {@link IHashMap} object makes no guarantees on which specific element is considered its - * first element. But, in any case, the range that goes from its begin to its end covers all the elements in the - * bucket, until invalidated.

- * - * @return A {@link MapReverseIterator reverse iterator} to the reverse beginning of the sequence - */ - rbegin(): MapReverseIterator; - /** - *

Return {@link MapReverseIterator reverse iterator} to reverse beginning.

- * - *

Returns a {@link MapReverseIterator reverse iterator} pointing to the last element in one of buckets in the - * {@link IHashMap} (i.e., its reverse beginning).

- * - * {@link MapReverseIterator Reverse iterators} iterate backwards: increasing them moves them towards the - * beginning of the container.

- * - *

{@link rbegin} points to the element preceding the one that would be pointed to by member {@link end}.

- * - *

Notice that an {@link IHashMap} object makes no guarantees on which specific element is considered its - * first element. But, in any case, the range that goes from its begin to its end covers all the elements in the - * bucket, until invalidated.

- * - * @param index Bucket number. This shall be lower than {@link bucket_count}. - * - * @return A {@link MapReverseIterator reverse iterator} to the reverse beginning of the sequence - */ - rbegin(index: number): MapReverseIterator; - /** - *

Return {@link MapReverseIterator reverse iterator} to reverse end.

- * - *

Returns a {@link MapReverseIterator reverse iterator} pointing to the theoretical element right before - * the first element in the {@link IHashMap hash map container} (which is considered its reverse end).

- * - *

The range between {@link IHashMap}.{@link rbegin} and {@link IHashMap}.{@link rend} contains all the - * elements of the container (in reverse order).

- * - *

Notice that an {@link IHashMap} object makes no guarantees on which order its elements follow. But, in any - * case, the range that goes from its begin to its end covers all the elements in the container (or the bucket), - * until invalidated.

- * - * @return A {@link MapReverseIterator reverse iterator} to the reverse end of the sequence. - */ - rend(): MapReverseIterator; - /** - *

Return {@link MapReverseIterator reverse iterator} to reverse end.

- * - *

Returns a {@link MapReverseIterator reverse iterator} pointing to the theoretical element right before - * the first element in one of buckets in the {@link IHashMap hash map container} (which is considered its - * reverse end).

- * - *

The range between {@link IHashMap}.{@link rbegin} and {@link IHashMap}.{@link rend} contains all the - * elements of the container (in reverse order).

- * - *

Notice that an {@link IHashMap} object makes no guarantees on which order its elements follow. But, in any - * case, the range that goes from its begin to its end covers all the elements in the container (or the bucket), - * until invalidated.

- * - * @param index Bucket number. This shall be lower than {@link bucket_count}. - * - * @return A {@link MapReverseIterator reverse iterator} to the reverse end of the sequence. - */ - rend(index: number): MapReverseIterator; - /** - *

Return number of buckets.

- * - *

Returns the number of buckets in the {@link IHashMap} container.

- * - *

A bucket is a slot in the container's internal hash table to which elements are assigned based on the - * hash value of their key.

- * - *

The number of buckets influences directly the {@link load_factor load factor} of the container's hash - * table (and thus the probability of collision). The container automatically increases the number of buckets to - * keep the load factor below a specific threshold (its {@link max_load_factor}), causing a {@link rehash} each - * time the number of buckets needs to be increased.

- * - * @return The current amount of buckets. - */ - bucket_count(): number; - /** - *

Return bucket size.

- * - *

Returns the number of elements in bucket n.

- * - *

A bucket is a slot in the container's internal hash table to which elements are assigned based on the hash - * value of their key.

- * - *

The number of elements in a bucket influences the time it takes to access a particular element in the - * bucket. The container automatically increases the number of buckets to keep the {@link load_cator load factor} - * (which is the average bucket size) below its {@link max_load_factor}.

- * - * @param n Bucket number. This shall be lower than {@link bucket_count}. - * - * @return The number of elements in bucket n. - */ - bucket_size(n: number): number; - /** - *

Get maximum load factor.

- * - *

Returns the current maximum load factor for the {@link HashMultiMap} container.

- * - *

The load factor is the ratio between the number of elements in the container (its {@link size}) and the - * number of buckets ({@link bucket_count}).

- * - *

By default, {@link HashMultiMap} containers have a {@link max_load_factor} of 1.0.

- * - *

The load factor influences the probability of collision in the hash table (i.e., the probability of two - * elements being located in the same bucket). The container uses the value of max_load_factor as the threshold - * that forces an increase in the number of buckets (and thus causing a {@link rehash}).

- * - *

Note though, that implementations may impose an upper limit on the number of buckets (see - * {@link max_bucket_count}), which may force the container to ignore the {@link max_load_factor}.

- * - * @return The current load factor. - */ - max_load_factor(): number; - /** - *

Set maximum load factor.

- * - *

Sets z as the cnew maximum load factor for the {@link HashMultiMap} container.

- * - *

The load factor is the ratio between the number of elements in the container (its {@link size}) and the - * number of buckets ({@link bucket_count}).

- * - *

By default, {@link HashMultiMap} containers have a {@link max_load_factor} of 1.0.

- * - *

The load factor influences the probability of collision in the hash table (i.e., the probability of two - * elements being located in the same bucket). The container uses the value of max_load_factor as the threshold - * that forces an increase in the number of buckets (and thus causing a {@link rehash}).

- * - *

Note though, that implementations may impose an upper limit on the number of buckets (see - * {@link max_bucket_count}), which may force the container to ignore the {@link max_load_factor}.

- * - * @param z The new maximum load factor. - */ - max_load_factor(z: number): void; - /** - *

Locate element's bucket.

- * - *

Returns the bucket number where the element with key is located.

- * - *

A bucket is a slot in the container's internal hash table to which elements are assigned based on the - * hash value of their key. Buckets are numbered from 0 to ({@link bucket_count} - 1).

- * - *

Individual elements in a bucket can be accessed by means of the range iterators returned by - * {@link begin} and {@link end}.

- * - * @param key Key whose bucket is to be located. - */ - bucket(key: Key): number; - /** - *

Request a capacity change.

- * - *

Sets the number of buckets in the container ({@link bucket_count}) to the most appropriate to contain at - * least n elements.

- * - *

If n is greater than the current {@link bucket_count} multiplied by the {@link max_load_factor}, - * the container's {@link bucket_count} is increased and a {@link rehash} is forced.

- * - *

If n is lower than that, the function may have no effect.

- * - * @param n The number of elements requested as minimum capacity. - */ - reserve(n: number): void; - /** - *

Set number of buckets.

- * - *

Sets the number of buckets in the container to n or more.

- * - *

If n is greater than the current number of buckets in the container ({@link bucket_count}), a - * {@link HashBuckets.rehash rehash} is forced. The new {@link bucket_count bucket count} can either be equal or - * greater than n.

- * - *

If n is lower than the current number of buckets in the container ({@link bucket_count}), the - * function may have no effect on the {@link bucket_count bucket count} and may not force a - * {@link HashBuckets.rehash rehash}.

- * - *

A {@link HashBuckets.rehash rehash} is the reconstruction of the hash table: All the elements in the - * container are rearranged according to their hash value into the new set of buckets. This may alter the order - * of iteration of elements within the container.

- * - *

{@link HashBuckets.rehash Rehashes} are automatically performed by the container whenever its - * {@link load_factor load factor} is going to surpass its {@link max_load_factor} in an operation.

- * - *

Notice that this function expects the number of buckets as argument. A similar function exists, - * {@link reserve}, that expects the number of elements in the container as argument.

- * - * @param n The minimum number of buckets for the container hash table. - */ - rehash(n: number): void; - } -} -declare namespace std.base { - /** - *

Hash buckets storing {@link MapIterator MapIterators}.

- * - *

- * - *

- * - * @author Jeongho Nam - */ - class MapHashBuckets extends HashBuckets> { - private map; - constructor(map: MapContainer); - find(key: K): MapIterator; - } -} -declare namespace std.base { - /** - *

A common interface for hash set.

- * - *

{@link IHashSet}s are containers that store unique elements in no particular order, and which - * allow for fast retrieval of individual elements based on their value.

- * - *

In an {@link IHashSet}, the value of an element is at the same time its key, that - * identifies it uniquely. Keys are immutable, therefore, the elements in an {@link IHashSet} cannot be - * modified once in the container - they can be inserted and removed, though.

- * - *

Internally, the elements in the {@link IHashSet} are not sorted in any particular order, but - * organized into buckets depending on their hash values to allow for fast access to individual elements - * directly by their values (with a constant average time complexity on average).

- * - *

{@link IHashSet} containers are faster than {@link TreeSet} containers to access individual - * elements by their key, although they are generally less efficient for range iteration through a - * subset of their elements.

- * - *

- * - *

- * - *

Container properties

- *
- *
Associative
- *
Elements in associative containers are referenced by their key and not by their absolute - * position in the container.
- * - *
Hashed
- *
Hashed containers organize their elements using hash tables that allow for fast access to elements - * by their key.
- * - *
Set
- *
The value of an element is also the key used to identify it.
- *
- * - * @param Type of the elements. - * Each element in an {@link IHashSet} is also uniquely identified by this value. - * - * @reference http://www.cplusplus.com/reference/unordered_set/unordered_set - * @author Jeongho Nam - */ - interface IHashSet { - /** - *

Return iterator to beginning.

- * - *

Returns an iterator pointing to the first element in the {@link IHashSet}.

- * - *

Notice that an {@link IHashSet} object makes no guarantees on which specific element is considered its - * first element. But, in any case, the range that goes from its begin to its end covers all the elements in the - * container, until invalidated.

- * - * @return An iterator to the first element in the container. - */ - begin(): SetIterator; - /** - *

Return iterator to beginning.

- * - *

Returns an iterator pointing to the first element in one of buckets in the {@link IHashSet}.

- * - *

Notice that an {@link IHashSet} object makes no guarantees on which specific element is considered its - * first element. But, in any case, the range that goes from its begin to its end covers all the elements in the - * bucket, until invalidated.

- * - * @param index Bucket number. This shall be lower than {@link bucket_count}. - * - * @return An iterator to the first element in the bucket. - */ - begin(index: number): SetIterator; - /** - *

Return iterator to end.

- * - *

Returns an iterator pointing to the past-the-end element in the {@link HaspMap} container.

- * - *

The iterator returned by end does not point to any element, but to the position that follows the last - * element in the {@link HaspMap} container (its past-the-end position). Thus, the value returned shall - * not be dereferenced - it is generally used to describe the open-end of a range, such as - * [begin, end).

- * - *

Notice that an {@link IHashSet} object makes no guarantees on which order its elements follow. But, in any - * case, the range that goes from its begin to its end covers all the elements in the container (or the bucket), - * until invalidated.

- * - * @return An iterator to the element past the end of the container. - */ - end(): SetIterator; - /** - *

Return iterator to end.

- * - *

Returns an iterator pointing to the past-the-end element in the {@link HaspMap} container.

- * - *

The iterator returned by end does not point to any element, but to the position that follows the last - * element in the {@link HaspMap} container (its past-the-end position). Thus, the value returned shall - * not be dereferenced - it is generally used to describe the open-end of a range, such as - * [begin, end).

- * - *

Notice that an {@link IHashSet} object makes no guarantees on which order its elements follow. But, in any - * case, the range that goes from its begin to its end covers all the elements in the container (or the bucket), - * until invalidated.

- * - * @param index Bucket number. This shall be lower than {@link bucket_count}. - * - * @return An iterator to the element past the end of the bucket. - */ - end(index: number): SetIterator; - rbegin(): SetReverseIterator; - rbegin(index: number): SetReverseIterator; - rend(): SetReverseIterator; - rend(index: number): SetReverseIterator; - /** - *

Return number of buckets.

- * - *

Returns the number of buckets in the {@link IHashSet} container.

- * - *

A bucket is a slot in the container's internal hash table to which elements are assigned based on the - * hash value of their key.

- * - *

The number of buckets influences directly the {@link load_factor load factor} of the container's hash - * table (and thus the probability of collision). The container automatically increases the number of buckets to - * keep the load factor below a specific threshold (its {@link max_load_factor}), causing a {@link rehash} each - * time the number of buckets needs to be increased.

- * - * @return The current amount of buckets. - */ - bucket_count(): number; - /** - *

Return bucket size.

- * - *

Returns the number of elements in bucket n.

- * - *

A bucket is a slot in the container's internal hash table to which elements are assigned based on the hash - * value of their key.

- * - *

The number of elements in a bucket influences the time it takes to access a particular element in the - * bucket. The container automatically increases the number of buckets to keep the {@link load_cator load factor} - * (which is the average bucket size) below its {@link max_load_factor}.

- * - * @param n Bucket number. This shall be lower than {@link bucket_count}. - * - * @return The number of elements in bucket n. - */ - bucket_size(n: number): number; - /** - *

Get maximum load factor.

- * - *

Returns the current maximum load factor for the {@link HashMultiMap} container.

- * - *

The load factor is the ratio between the number of elements in the container (its {@link size}) and the - * number of buckets ({@link bucket_count}).

- * - *

By default, {@link HashMultiMap} containers have a {@link max_load_factor} of 1.0.

- * - *

The load factor influences the probability of collision in the hash table (i.e., the probability of two - * elements being located in the same bucket). The container uses the value of max_load_factor as the threshold - * that forces an increase in the number of buckets (and thus causing a {@link rehash}).

- * - *

Note though, that implementations may impose an upper limit on the number of buckets (see - * {@link max_bucket_count}), which may force the container to ignore the {@link max_load_factor}.

- * - * @return The current load factor. - */ - max_load_factor(): number; - /** - *

Set maximum load factor.

- * - *

Sets z as the cnew maximum load factor for the {@link HashMultiMap} container.

- * - *

The load factor is the ratio between the number of elements in the container (its {@link size}) and the - * number of buckets ({@link bucket_count}).

- * - *

By default, {@link HashMultiMap} containers have a {@link max_load_factor} of 1.0.

- * - *

The load factor influences the probability of collision in the hash table (i.e., the probability of two - * elements being located in the same bucket). The container uses the value of max_load_factor as the threshold - * that forces an increase in the number of buckets (and thus causing a {@link rehash}).

- * - *

Note though, that implementations may impose an upper limit on the number of buckets (see - * {@link max_bucket_count}), which may force the container to ignore the {@link max_load_factor}.

- * - * @param z The new maximum load factor. - */ - max_load_factor(z: number): void; - /** - *

Locate element's bucket.

- * - *

Returns the bucket number where the element with key is located.

- * - *

A bucket is a slot in the container's internal hash table to which elements are assigned based on the - * hash value of their key. Buckets are numbered from 0 to ({@link bucket_count} - 1).

- * - *

Individual elements in a bucket can be accessed by means of the range iterators returned by - * {@link begin} and {@link end}.

- * - * @param key Key whose bucket is to be located. - */ - bucket(key: T): number; - /** - *

Request a capacity change.

- * - *

Sets the number of buckets in the container ({@link bucket_count}) to the most appropriate to contain at - * least n elements.

- * - *

If n is greater than the current {@link bucket_count} multiplied by the {@link max_load_factor}, - * the container's {@link bucket_count} is increased and a {@link rehash} is forced.

- * - *

If n is lower than that, the function may have no effect.

- * - * @param n The number of elements requested as minimum capacity. - */ - reserve(n: number): void; - /** - *

Set number of buckets.

- * - *

Sets the number of buckets in the container to n or more.

- * - *

If n is greater than the current number of buckets in the container ({@link bucket_count}), a - * {@link HashBuckets.rehash rehash} is forced. The new {@link bucket_count bucket count} can either be equal or - * greater than n.

- * - *

If n is lower than the current number of buckets in the container ({@link bucket_count}), the - * function may have no effect on the {@link bucket_count bucket count} and may not force a - * {@link HashBuckets.rehash rehash}.

- * - *

A {@link HashBuckets.rehash rehash} is the reconstruction of the hash table: All the elements in the - * container are rearranged according to their hash value into the new set of buckets. This may alter the order - * of iteration of elements within the container.

- * - *

{@link HashBuckets.rehash Rehashes} are automatically performed by the container whenever its - * {@link load_factor load factor} is going to surpass its {@link max_load_factor} in an operation.

- * - *

Notice that this function expects the number of buckets as argument. A similar function exists, - * {@link reserve}, that expects the number of elements in the container as argument.

- * - * @param n The minimum number of buckets for the container hash table. - */ - rehash(n: number): void; - } -} -declare namespace std.base { - /** - *

Hash buckets storing {@link SetIterator SetIterators}.

- * - *

- * - *

- * - * @author Jeongho Nam - */ - class SetHashBuckets extends HashBuckets> { - private set; - constructor(set: SetContainer); - find(val: T): SetIterator; - } -} -declare namespace std.base { - /** - *

Array

- * - *

{@link IArray} is an interface for sequence containers representing arrays that can change in - * {@link size}. However, compared to arrays, {@link IArray} objectss consume more memory in exchange for - * the ability to manage storage and grow dynamically in an efficient way.

- * - *

Both {@link Vector Vectors} and {@link Deque Deques} who implemented {@link IArray} provide a very - * similar interface and can be used for similar purposes, but internally both work in quite different ways: - * While {@link Vector Vectors} use a single array that needs to be occasionally reallocated for growth, the - * elements of a {@link Deque} can be scattered in different chunks of storage, with the container keeping the - * necessary information internally to provide direct access to any of its elements in constant time and with a - * uniform sequential interface (through iterators). Therefore, {@link Deque Deques} are a little more complex - * internally than {@link Vector Vectors}, but this allows them to grow more efficiently under certain - * circumstances, especially with very long sequences, where reallocations become more expensive.

- * - *

Both {@link Vector Vectors} and {@link Deque Deques} provide a very similar interface and can be used for - * similar purposes, but internally both work in quite different ways: While {@link Vector Vectors} use a single - * array that needs to be occasionally reallocated for growth, the elements of a {@link Deque} can be scattered - * in different chunks of storage, with the container keeping the necessary information internally to provide - * direct access to any of its elements in constant time and with a uniform sequential interface (through - * iterators). Therefore, {@link Deque Deques} are a little more complex internally than {@link Vector Vectors}, - * but this allows them to grow more efficiently under certain circumstances, especially with very long - * sequences, where reallocations become more expensive.

- * - *

For operations that involve frequent insertion or removals of elements at positions other than the - * beginning or the end, {@link IArray} objects perform worse and have less consistent iterators and references - * than {@link List Lists}

. - * - *

- * - *

- * - *

Container properties

- *
- *
Sequence
- *
- * Elements in sequence containers are ordered in a strict linear sequence. Individual elements are - * accessed by their position in this sequence. - *
- * - *
Dynamic array
- *
- * Allows direct access to any element in the sequence, even through pointer arithmetics, and provides - * relatively fast addition/removal of elements at the end of the sequence. - *
- *
- * - * @param Type of the elements. - * - * @author Jeongho Nam - */ - interface IArrayContainer extends ILinearContainer { - /** - *

Request a change in capacity.

- * - *

Requests that the {@link IArray container} {@link capacity} be at least enough to contain - * n elements.

- * - *

If n is greater than the current {@link IArray container} {@link capacity}, the - * function causes the {@link IArray container} to reallocate its storage increasing its - * {@link capacity} to n (or greater).

- * - *

In all other cases, the function call does not cause a reallocation and the - * {@link IArray container} {@link capacity} is not affected.

- * - *

This function has no effect on the {@link IArray container} {@link size} and cannot alter - * its elements.

- * - * @param n Minimum {@link capacity} for the {@link IArray container}. - * Note that the resulting {@link capacity} may be equal or greater than n. - */ - reserve(n: number): void; - /** - *

Return size of allocated storage capacity.

- * - *

Returns the size of the storage space currently allocated for the {@link IArray container}, - * expressed in terms of elements.

- * - *

This {@link capacity} is not necessarily equal to the {@link IArray container} {@link size}. - * It can be equal or greater, with the extra space allowing to accommodate for growth without the - * need to reallocate on each insertion.

- * - *

Notice that this {@link capacity} does not suppose a limit on the {@link size} of the - * {@link IArray container}. When this {@link capacity} is exhausted and more is needed, it is - * automatically expanded by the {@link IArray container} (reallocating it storage space). - * The theoretical limit on the {@link size} of a {@link IArray container} is given by member - * {@link max_size}.

- * - *

The {@link capacity} of a {@link IArray container} can be explicitly altered by calling member - * {@link IArray.reserve}.

- * - * @return The size of the currently allocated storage capacity in the {@link IArray container}, - * measured in terms of the number elements it can hold. - */ - capacity(): number; - /** - *

Access element.

- *

Returns a value to the element at position index in the {@link IArray container}.

- * - *

The function automatically checks whether index is within the bounds of valid elements - * in the {@link IArray container}, throwing an {@link OutOfRange} exception if it is not (i.e., - * if index is greater or equal than its {@link size}).

- * - * @param index Position of an element in the - * If this is greater than or equal to the {@link IArray container} {@link size}, an - * exception of type {@link OutOfRange} is thrown. Notice that the first - * element has a position of 0 (not 1). - * - * @return The element at the specified position in the - */ - at(index: number): T; - /** - *

Modify element.

- *

Replaces an element at the specified position (index) in this {@link IArray container} - * with the specified element (val).

- * - *

The function automatically checks whether index is within the bounds of valid elements - * in the {@link IArray container}, throwing an {@link OutOfRange} exception if it is not (i.e., if - * index is greater or equal than its {@link size}).

- * - * @.param index A specified position of the value to replace. - * @param val A value to be stored at the specified position. - * - * @return The previous element had stored at the specified position. - */ - set(index: number, val: T): void; - } - /** - *

Random-access iterator.

- * - *

{@link IArrayIterator Random-access iterators} are iterators that can be used to access elements at an - * arbitrary offset position relative to the element they point to, offering the same functionality as pointers. - *

- * - *

{@link IArrayIterator Random-access iterators} are the most complete iterators in terms of functionality. - * All pointer types are also valid {@link IArrayIterator random-access iterators}.

- * - *

There is not a single type of {@link IArrayIterator random-access iterator}: Each container may define its - * own specific iterator type able to iterate through it and access its elements.

- * - *

- * - *

- * - * @reference http://www.cplusplus.com/reference/iterator/RandomAccessIterator - * @author Jeongho Nam - */ - interface IArrayIterator extends ILinearIterator { - /** - * Get index, sequence number of the iterator in the source {@link IArray array}. - * - * @return Sequence number of the iterator in the source {@link IArray array}. - */ - index: number; - /** - * @inheritdoc - */ - prev(): IArrayIterator; - /** - * @inheritdoc - */ - next(): IArrayIterator; - } -} -declare namespace std.base { - /** - *

An interface of containers.

- * - *

{@link IContainer} is an interface designed for sequence containers. Sequence containers of STL - * (Standard Template Library) are based on the {@link IContainer}.

- * - *

- * - *

- * - *

Container properties

- *
- *
Sequence
- *
Elements in sequence containers are ordered in a strict linear sequence. Individual elements are - * accessed by their position in this sequence.
- * - *
Doubly-linked list
- *
Each element keeps information on how to locate the next and the previous elements, allowing - * constant time insert and erase operations before or after a specific element (even of entire ranges), - * but no direct random access.
- *
- * - * @param Type of elements. - * - * @author Jeongho Nam - */ - interface IContainer { - /** - *

Assign new content to content.

- * - *

Assigns new contents to the container, replacing its current contents, and modifying its - * {@link size} accordingly.

- * - * @param begin Input interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - */ - assign>(begin: InputIterator, end: InputIterator): void; - /** - *

Clear content.

- * - *

Removes all elements from the Container, leaving the container with a size of 0.

- */ - clear(): void; - /** - *

Return iterator to beginning.

- * - *

Returns an iterator referring the first element in the

- * - *

Note

- *

If the container is {@link empty}, the returned iterator is same with {@link end end()}.

- * - * @return An iterator to the first element in the The iterator containes the first element's value. - */ - begin(): Iterator; - /** - *

Return iterator to end.

- *

Returns an iterator referring to the past-the-end element in the

- * - *

The past-the-end element is the theoretical element that would follow the last element in the - * It does not point to any element, and thus shall not be dereferenced.

- * - *

Because the ranges used by functions of the Container do not include the element reference by their - * closing iterator, this function is often used in combination with {@link IContainer}.{@link begin} to - * specify a range including all the elements in the container.

- * - *

Note

- *

Returned iterator from {@link IContainer}.{@link end} does not refer any element. Trying to accessing - * element by the iterator will cause throwing exception ({@link OutOfRange}).

- * - *

If the container is {@link empty}, this function returns the same as {@link Container}.{@link begin}. - *

- * - * @return An iterator to the end element in the - */ - end(): Iterator; - /** - *

Return {@link ReverseIterator reverse iterator} to reverse beginning.

- * - *

Returns a {@link ReverseIterator reverse iterator} pointing to the last element in the container (i.e., - * its reverse beginning).

- * - *

{@link ReverseIterator reverse iterators} iterate backwards: increasing them moves them towards the - * beginning of the

- * - *

{@link rbegin} points to the element right before the one that would be pointed to by member {@link end}. - *

- * - * @return A {@link ReverseIterator reverse iterator} to the reverse beginning of the sequence - */ - rbegin(): base.IReverseIterator; - /** - *

Return {@link ReverseIterator reverse iterator} to reverse end.

- * - *

Returns a {@link ReverseIterator reverse iterator} pointing to the theoretical element preceding the - * first element in the container (which is considered its reverse end).

- * - *

The range between {@link IContainer}.{@link rbegin} and {@link IContainer}.{@link rend} contains all - * the elements of the container (in reverse order). - * - * @return A {@link ReverseIterator reverse iterator} to the reverse end of the sequence - */ - rend(): base.IReverseIterator; - /** - * Return the number of elements in the Container. - * - * @return The number of elements in the - */ - size(): number; - /** - *

Test whether the container is empty.

- *

Returns whether the container is empty (i.e. whether its size is 0).

- * - *

This function does not modify the container in any way. To clear the content of the container, - * see {@link clear clear()}.

- * - * @return true if the container size is 0, false otherwise. - */ - empty(): boolean; - /** - *

Insert elements.

- * - *

Appends new elements to the container, and returns the new size of the

- * - * @param items New elements to insert. - * - * @return New size of the Container. - */ - push(...items: T[]): number; - /** - *

Insert an element.

- * - *

The container is extended by inserting a new element before the element at the specified - * position. This effectively increases the {@link IContainer.size container size} by the amount of - * elements inserted.

- * - * @param position Position in the {@link IContainer} where the new element is inserted. - * {@link iterator} is a member type, defined as a {@link Iterator random access iterator} - * type that points to elements. - * @param val Value to be copied to the inserted element. - * - * @return An iterator that points to the newly inserted element. - */ - insert(position: Iterator, val: T): Iterator; - /** - *

Erase an element.

- * - *

Removes from the container a single element.

- * - *

This effectively reduces the container size by the number of element removed.

- * - * @param position Iterator pointing to a single element to be removed from the Container. - * - * @return An iterator pointing to the element that followed the last element erased by the function - * call. This is the {@link end Container.end} if the operation erased the last element in the - * sequence. - */ - erase(position: Iterator): Iterator; - /** - *

Erase elements.

- * - *

Removes from the container a range of elements.

- * - *

This effectively reduces the container size by the number of elements removed.

- * - * @param begin An iterator specifying a range of beginning to erase. - * @param end An iterator specifying a range of end to erase. - * - * @return An iterator pointing to the element that followed the last element erased by the function - * call. This is the {@link end Container.end} if the operation erased the last element in - * the sequence. - */ - erase(begin: Iterator, end: Iterator): Iterator; - /** - *

Swap content.

- * - *

Exchanges the content of the container by the content of obj, which is another - * {@link IContainer container} object with same type of elements. Sizes and container type may differ.

- * - *

After the call to this member function, the elements in this container are those which were in obj - * before the call, and the elements of obj are those which were in this. All iterators, references and - * pointers remain valid for the swapped objects.

- * - *

Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that - * algorithm with an optimization that behaves like this member function.

- * - * @param obj Another {@link IContainer container} of the same type of elements (i.e., instantiated - * with the same template parameter, T) whose content is swapped with that of this - * {@link container IContainer}. - */ - swap(obj: IContainer): void; - } - interface IReverseIterator extends ReverseIterator, IReverseIterator> { - } -} -declare namespace std.base { - /** - *

An interface for deque

- * - *

- * - *

- * - * @author Jeongho Nam - */ - interface IDequeContainer extends ILinearContainer { - /** - *

Insert element at beginning.

- * - *

Inserts a new element at the beginning of the {@link IDeque container}, right before its - * current first element. This effectively increases the {@link IDeque container} {@link size} by - * one.

- * - * @param val Value to be inserted as an element. - */ - push_front(val: T): void; - /** - *

Delete first element.

- * - *

Removes the first element in the {@link IDeque container}, effectively reducing its - * {@link size} by one.

- */ - pop_front(): void; - } -} -declare namespace std.base { - /** - *

An interface for linear containers.

- * - *

- * - *

- * - * @author Jeonngho Nam - */ - interface ILinearContainer extends IContainer { - /** - * @inheritdoc - */ - assign>(begin: InputIterator, end: InputIterator): void; - /** - *

Assign container content.

- * - *

Assigns new contents to the {@link IList container}, replacing its current contents, - * and modifying its {@link size} accordingly.

- * - * @param n New size for the - * @param val Value to fill the container with. Each of the n elements in the container will - * be initialized to a copy of this value. - */ - assign(n: number, val: T): void; - /** - *

Access first element.

- *

Returns a value of the first element in the {@link IList container}.

- * - *

Unlike member {@link end end()}, which returns an iterator just past this element, - * this function returns a direct value.

- * - *

Calling this function on an {@link empty} {@link IList container} causes undefined behavior.

- * - * @return A value of the first element of the {@link IList container}. - */ - front(): T; - /** - *

Access last element.

- *

Returns a value of the last element in the {@link IList container}.

- * - *

Unlike member {@link end end()}, which returns an iterator just past this element, - * this function returns a direct value.

- * - *

Calling this function on an {@link empty} {@link IList container} causes undefined behavior.

- * - * @return A value of the last element of the {@link IList container}. - */ - back(): T; - /** - *

Add element at the end.

- * - *

Adds a new element at the end of the {@link IList container}, after its current last element. - * This effectively increases the {@link IList container} {@link size} by one.

- * - * @param val Value to be copied to the new element. - */ - push_back(val: T): void; - /** - *

Delete last element.

- * - *

Removes the last element in the {@link IList container}, effectively reducing the - * {@link IList container} {@link size} by one.

- */ - pop_back(): void; - /** - *

Insert an element.

- * - *

The {@link IList conatiner} is extended by inserting new element before the element at the - * specified position, effectively increasing the {@link IList container} {@link size} by - * one.

- * - * @param position Position in the {@link IList container} where the new elements are inserted. - * {@link iterator} is a member type, defined as a {@link iterator random access iterator} - * type that points to elements. - * @param val Value to be copied to the inserted element. - * - * @return An iterator that points to the newly inserted element. - */ - insert(position: Iterator, val: T): Iterator; - /** - *

Insert elements by range iterators.

- * - *

The {@link IList container} is extended by inserting new elements before the element at the - * specified position, effectively increasing the {@link IList container} {@link size} by - * the number of repeating elements n.

- * - * @param position Position in the {@link IList container} where the new elements are inserted. - * {@link iterator} is a member type, defined as a {@link iterator random access iterator} - * type that points to elements. - * @param n Number of elements to insert. Each element is initialized to a copy of val. - * @param val Value to be copied (or moved) to the inserted elements. - * - * @return An iterator that points to the first of the newly inserted elements. - */ - insert(position: Iterator, n: number, val: T): Iterator; - /** - *

Insert elements by range iterators.

- * - *

The {@link IList container} is extended by inserting new elements before the element at the - * specified position, effectively increasing the {@link IList container} {@link size} by - * the number of elements inserted by range iterators.

- * - * @param position Position in the {@link IList container} where the new elements are inserted. - * {@link iterator} is a member type, defined as a {@link iterator random access iterator} - * type that points to elements. - * @param begin Input interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - * - * @return An iterator that points to the first of the newly inserted elements. - */ - insert>(position: Iterator, begin: InputIterator, end: InputIterator): Iterator; - } - /** - * An interface for iterators from linear containers. - * - * {@link ILieanerIterator} is an bi-directional iterator which is created from the related - * {@link ILinearContainer linear containers}. Not only accessing to {@link value} of the pointed element from - * this {@link ILieanerIterator}, but also modifying the {@link value} is possible. - * - * @author Jeongho Nam - */ - interface ILinearIterator extends Iterator { - /** - * @inheritdoc - */ - value: T; - /** - * @inheritdoc - */ - prev(): ILinearIterator; - /** - * @inheritdoc - */ - next(): ILinearIterator; - } -} -declare namespace std { - /** - *

Bi-directional iterator.

- * - *

{@link Iterator Bidirectional iterators} are iterators that can be used to access the sequence of elements - * in a range in both directions (towards the end and towards the beginning).

- * - *

All {@link IArrayIterator random-access iterators} are also valid {@link Iterrator bidirectional iterators}. - *

- * - *

There is not a single type of {@link Iterator bidirectional iterator}: {@link IContainer Each container} - * may define its own specific iterator type able to iterate through it and access its elements.

- * - *

- * - *

- * - * @reference http://www.cplusplus.com/reference/iterator/BidirectionalIterator - * @author Jeongho Nam - */ - abstract class Iterator { - /** - * Source container of the iterator is directing for. - */ - protected source_: base.IContainer; - /** - * Construct from the source {@link IContainer container}. - * - * @param source The source container. - */ - protected constructor(source: base.IContainer); - /** - *

Get iterator to previous element.

- *

If current iterator is the first item(equal with {@link IContainer.begin IContainer.begin()}), - * returns {@link IContainer.end IContainer.end()}.

- * - * @return An iterator of the previous item. - */ - abstract prev(): Iterator; - /** - *

Get iterator to next element.

- *

If current iterator is the last item, returns {@link IContainer.end IContainer.end()}.

- * - * @return An iterator of the next item. - */ - abstract next(): Iterator; - /** - * Advances the {@link Iterator} by n element positions. - * - * @param n Number of element positions to advance. - * @return An advanced iterator. - */ - advance(n: number): Iterator; - /** - * Get source - */ - get_source(): base.IContainer; - /** - *

Whether an iterator is equal with the iterator.

- * - *

Compare two iterators and returns whether they are equal or not.

- * - *

Note

- *

Iterator's {@link equals equals()} only compare souce container and index number.

- * - *

Although elements in a pair, key and value are {@link std.equal_to equal_to}, if the source map or - * index number is different, then the {@link equals equals()} will return false. If you want to - * compare the elements of a pair, compare them directly by yourself.

- * - * @param obj An iterator to compare - * @return Indicates whether equal or not. - */ - equals(obj: Iterator): boolean; - /** - *

Get value of the iterator is pointing.

- * - * @return A value of the iterator. - */ - readonly abstract value: T; - abstract swap(obj: Iterator): void; - } -} -declare namespace std { - /** - *

This class reverses the direction in which a bidirectional or random-access iterator iterates through a range. - *

- * - *

A copy of the original iterator (the {@link Iterator base iterator}) is kept internally and used to reflect - * the operations performed on the {@link ReverseIterator}: whenever the {@link ReverseIterator} is incremented, its - * {@link Iterator base iterator} is decreased, and vice versa. A copy of the {@link Iterator base iterator} with the - * current state can be obtained at any time by calling member {@link base}.

- * - *

Notice however that when an iterator is reversed, the reversed version does not point to the same element in - * the range, but to the one preceding it. This is so, in order to arrange for the past-the-end element of a - * range: An iterator pointing to a past-the-end element in a range, when reversed, is pointing to the last element - * (not past it) of the range (this would be the first element of the reversed range). And if an iterator to the - * first element in a range is reversed, the reversed iterator points to the element before the first element (this - * would be the past-the-end element of the reversed range).

- * - *

- * - *

- * - * @reference http://www.cplusplus.com/reference/iterator/reverse_iterator - * @author Jeongho Nam - */ - abstract class ReverseIterator, This extends ReverseIterator> extends Iterator { - /** - * @hidden - */ - protected base_: Base; - /** - * Construct from base iterator. - * - * @param base A reference of the base iterator, which iterates in the opposite direction. - */ - protected constructor(base: Base); - /** - *

Return base iterator.

- * - *

Return a reference of the base iteraotr.

- * - *

The base iterator is an iterator of the same type as the one used to construct the {@link ReverseIterator}, - * but pointing to the element next to the one the {@link ReverseIterator} is currently pointing to - * (a {@link ReverseIterator} has always an offset of -1 with respect to its base iterator). - * - * @return A reference of the base iterator, which iterates in the opposite direction. - */ - base(): Base; - /** - * @hidden - */ - protected abstract _Create_neighbor(base: Base): This; - /** - *

Get value of the iterator is pointing.

- * - * @return A value of the reverse iterator. - */ - readonly value: T; - /** - * @inheritdoc - */ - prev(): This; - /** - * @inheritdoc - */ - next(): This; - /** - * @inheritdoc - */ - advance(n: number): This; - /** - * @inheritdoc - */ - equals(obj: This): boolean; - /** - * @inheritdoc - */ - swap(obj: This): void; - } - /** - *

Return distance between {@link Iterator iterators}.

- * - *

Calculates the number of elements between first and last.

- * - *

If it is a {@link IArrayIterator random-access iterator}, the function uses operator- to calculate this. - * Otherwise, the function uses the increase operator {@link Iterator.next next()} repeatedly.

- * - * @param first Iterator pointing to the initial element. - * @param last Iterator pointing to the final element. This must be reachable from first. - * - * @return The number of elements between first and last. - */ - function distance>(first: InputIterator, last: InputIterator): number; - /** - *

Advance iterator.

- * - *

Advances the iterator it by n elements positions.

- * - * @param it Iterator to be advanced. - * @param n Number of element positions to advance. - * - * @return An iterator to the element n positions before it. - */ - function advance>(it: InputIterator, n: number): InputIterator; - /** - *

Get iterator to previous element.

- * - *

Returns an iterator pointing to the element that it would be pointing to if advanced -n positions.

- * - * @param it Iterator to base position. - * @param n Number of element positions offset (1 by default). - * - * @return An iterator to the element n positions before it. - */ - function prev>(it: BidirectionalIterator, n?: number): BidirectionalIterator; - /** - *

Get iterator to next element.

- * - *

Returns an iterator pointing to the element that it would be pointing to if advanced n positions.

- * - * @param it Iterator to base position. - * @param n Number of element positions offset (1 by default). - * - * @return An iterator to the element n positions away from it. - */ - function next>(it: ForwardIterator, n?: number): ForwardIterator; - /** - *

Iterator to beginning.

- * - *

Returns an iterator pointing to the first element in the sequence.

- * - *

If the sequence is empty, the returned value shall not be dereferenced.

- * - * @param container A container object of a class type for which member {@link IContainer.begin begin} is defined. - * - * @return The same as returned by {@link IContainer.begin container.begin()}. - */ - function begin(container: Vector): VectorIterator; - /** - *

Iterator to beginning.

- * - *

Returns an iterator pointing to the first element in the sequence.

- * - *

If the sequence is empty, the returned value shall not be dereferenced.

- * - * @param container A container object of a class type for which member {@link IContainer.begin begin} is defined. - * - * @return The same as returned by {@link IContainer.begin container.begin()}. - */ - function begin(container: List): ListIterator; - /** - *

Iterator to beginning.

- * - *

Returns an iterator pointing to the first element in the sequence.

- * - *

If the sequence is empty, the returned value shall not be dereferenced.

- * - * @param container A container object of a class type for which member {@link IContainer.begin begin} is defined. - * - * @return The same as returned by {@link IContainer.begin container.begin()}. - */ - function begin(container: Deque): DequeIterator; - /** - *

Iterator to beginning.

- * - *

Returns an iterator pointing to the first element in the sequence.

- * - *

If the sequence is empty, the returned value shall not be dereferenced.

- * - * @param container A container object of a class type for which member {@link IContainer.begin begin} is defined. - * - * @return The same as returned by {@link IContainer.begin container.begin()}. - */ - function begin(container: base.SetContainer): SetIterator; - /** - *

Iterator to beginning.

- * - *

Returns an iterator pointing to the first element in the sequence.

- * - *

If the sequence is empty, the returned value shall not be dereferenced.

- * - * @param container A container object of a class type for which member {@link IContainer.begin begin} is defined. - * - * @return The same as returned by {@link IContainer.begin container.begin()}. - */ - function begin(container: base.MapContainer): MapIterator; - /** - *

Iterator to end.

- * - *

Returns an iterator pointing to the past-the-end element in the sequence.

- * - *

If the sequence is {@link IContainer.empty empty}, the returned value compares equal to the one returned by {@link begin} with the same argument.

- * - * @param container A container of a class type for which member {@link IContainer.end end} is defined. - * - * @return The same as returned by {@link IContainer.end container.end()}. - */ - function end(container: Vector): VectorIterator; - /** - *

Iterator to end.

- * - *

Returns an iterator pointing to the past-the-end element in the sequence.

- * - *

If the sequence is {@link IContainer.empty empty}, the returned value compares equal to the one returned by {@link begin} with the same argument.

- * - * @param container A container of a class type for which member {@link IContainer.end end} is defined. - * - * @return The same as returned by {@link IContainer.end container.end()}. - */ - function end(container: List): ListIterator; - /** - *

Iterator to end.

- * - *

Returns an iterator pointing to the past-the-end element in the sequence.

- * - *

If the sequence is {@link IContainer.empty empty}, the returned value compares equal to the one returned by {@link begin} with the same argument.

- * - * @param container A container of a class type for which member {@link IContainer.end end} is defined. - * - * @return The same as returned by {@link IContainer.end container.end()}. - */ - function end(container: Deque): DequeIterator; - /** - *

Iterator to end.

- * - *

Returns an iterator pointing to the past-the-end element in the sequence.

- * - *

If the sequence is {@link IContainer.empty empty}, the returned value compares equal to the one returned by {@link begin} with the same argument.

- * - * @param container A container of a class type for which member {@link IContainer.end end} is defined. - * - * @return The same as returned by {@link IContainer.end container.end()}. - */ - function end(container: base.SetContainer): SetIterator; - /** - *

Iterator to end.

- * - *

Returns an iterator pointing to the past-the-end element in the sequence.

- * - *

If the sequence is {@link IContainer.empty empty}, the returned value compares equal to the one returned by {@link begin} with the same argument.

- * - * @param container A container of a class type for which member {@link IContainer.end end} is defined. - * - * @return The same as returned by {@link IContainer.end container.end()}. - */ - function end(container: base.MapContainer): MapIterator; -} -declare namespace std.base { - /** - * An abstract list. - * - *

{@link ListContainer}s are sequence containers that allow constant time insert and erase operations anywhere - * within the sequence, and iteration in both directions.

- * - *

List containers are implemented as doubly-linked lists; Doubly linked lists can store each of the elements they - * contain in different and unrelated storage locations. The ordering is kept internally by the association to each - * element of a link to the element preceding it and a link to the element following it.

- * - *

Compared to other base standard sequence containers (array, vector and deque), lists perform generally better - * in inserting, extracting and moving elements in any position within the container for which an iterator has already - * been obtained, and therefore also in algorithms that make intensive use of these, like sorting algorithms.

- * - *

The main drawback of lists and forward_lists compared to these other sequence containers is that they lack - * direct access to the elements by their position; For example, to access the sixth element in a list, one has to - * iterate from a known position (like the beginning or the end) to that position, which takes linear time in the - * distance between these. They also consume some extra memory to keep the linking information associated to each - * element (which may be an important factor for large lists of small-sized elements).

- * - *

Container properties

- *
- *
Sequence
- *
Elements in sequence containers are ordered in a strict linear sequence. Individual elements are accessed by - * their position in this sequence.
- * - *
Doubly-linked list
- *
Each element keeps information on how to locate the next and the previous elements, allowing constant time - * insert and erase operations before or after a specific element (even of entire ranges), but no direct random - * access.
- *
- * - * @param Type of the elements. - * - * @reference http://www.cplusplus.com/reference/list/list/ - * - * @author Jeongho Nam - */ - abstract class ListContainer> extends Container implements IDequeContainer { - /** - * @hidden - */ - private begin_; - /** - * @hidden - */ - private end_; - /** - * @hidden - */ - private size_; - /** - * Default Constructor. - */ - protected constructor(); - /** - * @hidden - */ - protected abstract _Create_iterator(prev: BidirectionalIterator, next: BidirectionalIterator, val: T): BidirectionalIterator; - /** - * @hidden - */ - protected _Set_begin(it: BidirectionalIterator): void; - /** - * @inheritdoc - */ - assign>(first: InputIterator, last: InputIterator): void; - /** - * @inheritdoc - */ - clear(): void; - /** - * @inheritdoc - */ - begin(): BidirectionalIterator; - /** - * @inheritdoc - */ - end(): BidirectionalIterator; - /** - * @inheritdoc - */ - size(): number; - /** - * @inheritdoc - */ - front(): T; - /** - * @inheritdoc - */ - back(): T; - /** - * @inheritdoc - */ - push_front(val: T): void; - /** - * @inheritdoc - */ - push_back(val: T): void; - /** - * @inheritdoc - */ - pop_front(): void; - /** - * @inheritdoc - */ - pop_back(): void; - /** - * @inheritdoc - */ - push(...items: T[]): number; - /** - *

Insert an element.

- * - *

The container is extended by inserting a new element before the element at the specified - * position. This effectively increases the {@link List.size List size} by the amount of elements - * inserted.

- * - *

Unlike other standard sequence containers, {@link List} is specifically designed to be efficient - * inserting and removing elements in any position, even in the middle of the sequence.

- * - * @param position Position in the container where the new element is inserted. - * {@link iterator}> is a member type, defined as a - * {@link ListIterator bidirectional iterator} type that points to elements. - * @param val Value to be inserted as an element. - * - * @return An iterator that points to the newly inserted element; val. - */ - insert(position: BidirectionalIterator, val: T): BidirectionalIterator; - /** - *

Insert elements by repeated filling.

- * - *

The container is extended by inserting a new element before the element at the specified - * position. This effectively increases the {@link List.size List size} by the amount of elements - * inserted.

- * - *

Unlike other standard sequence containers, {@link List} is specifically designed to be efficient - * inserting and removing elements in any position, even in the middle of the sequence.

- * - * @param position Position in the container where the new elements are inserted. The {@link iterator} is a - * member type, defined as a {@link ListIterator bidirectional iterator} type that points to - * elements. - * @param size Number of elements to insert. - * @param val Value to be inserted as an element. - * - * @return An iterator that points to the first of the newly inserted elements. - */ - insert(position: BidirectionalIterator, size: number, val: T): BidirectionalIterator; - /** - *

Insert elements by range iterators.

- * - *

The container is extended by inserting a new element before the element at the specified - * position. This effectively increases the {@link List.size List size} by the amount of elements - * inserted.

- * - *

Unlike other standard sequence containers, {@link List} is specifically designed to be efficient - * inserting and removing elements in any position, even in the middle of the sequence.

- * - * @param position Position in the container where the new elements are inserted. The {@link iterator} is a - * member type, defined as a {@link ListIterator bidirectional iterator} type that points to - * elements. - * @param begin An iterator specifying range of the begining element. - * @param end An iterator specifying range of the ending element. - * - * @return An iterator that points to the first of the newly inserted elements. - */ - insert>(position: BidirectionalIterator, begin: InputIterator, end: InputIterator): BidirectionalIterator; - /** - * @hidden - */ - private insert_by_val(position, val); - /** - * @hidden - */ - protected _Insert_by_repeating_val(position: BidirectionalIterator, size: number, val: T): BidirectionalIterator; - /** - * @hidden - */ - protected _Insert_by_range>(position: BidirectionalIterator, begin: InputIterator, end: InputIterator): BidirectionalIterator; - /** - *

Erase an element.

- * - *

Removes from the {@link List} either a single element; position.

- * - *

This effectively reduces the container size by the number of element removed.

- * - *

Unlike other standard sequence containers, {@link List} objects are specifically designed to be - * efficient inserting and removing elements in any position, even in the middle of the sequence.

- * - * @param position Iterator pointing to a single element to be removed from the {@link List}. - * - * @return An iterator pointing to the element that followed the last element erased by the function call. - * This is the {@link end end()} if the operation erased the last element in the sequence. - */ - erase(position: BidirectionalIterator): BidirectionalIterator; - /** - *

Erase elements.

- * - *

Removes from the {@link List} container a range of elements.

- * - *

This effectively reduces the container {@link size} by the number of elements removed.

- * - *

Unlike other standard sequence containers, {@link List} objects are specifically designed to be - * efficient inserting and removing elements in any position, even in the middle of the sequence.

- * - * @param begin An iterator specifying a range of beginning to erase. - * @param end An iterator specifying a range of end to erase. - * - * @return An iterator pointing to the element that followed the last element erased by the function call. - * This is the {@link end end()} if the operation erased the last element in the sequence. - */ - erase(begin: BidirectionalIterator, end: BidirectionalIterator): BidirectionalIterator; - /** - * @hidden - */ - protected _Erase_by_range(first: BidirectionalIterator, last: BidirectionalIterator): BidirectionalIterator; - /** - *

Swap content.

- * - *

Exchanges the content of the container by the content of obj, which is another - * {@link List container} object with same type of elements. Sizes and container type may differ.

- * - *

After the call to this member function, the elements in this container are those which were in obj - * before the call, and the elements of obj are those which were in this. All iterators, references and - * pointers remain valid for the swapped objects.

- * - *

Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that - * algorithm with an optimization that behaves like this member function.

- * - * @param obj Another {@link List container} of the same type of elements (i.e., instantiated - * with the same template parameter, T) whose content is swapped with that of this - * {@link container List}. - */ - swap(obj: ListContainer): void; - /** - * @inheritdoc - */ - swap(obj: base.IContainer): void; - } -} -declare namespace std.base { - /** - * An iterator, node of a List-based container. - * - * - * - * - * - * @author Jeongho Nam - */ - abstract class ListIteratorBase extends Iterator { - /** - * @hidden - */ - private prev_; - /** - * @hidden - */ - private next_; - /** - * @hidden - */ - protected value_: T; - /** - * Initializer Constructor. - * - * @param source The source {@link Container} to reference. - * @param prev A refenrece of previous node ({@link ListIterator iterator}). - * @param next A refenrece of next node ({@link ListIterator iterator}). - * @param value Value to be stored in the node (iterator). - */ - protected constructor(source: Container, prev: ListIteratorBase, next: ListIteratorBase, value: T); - /** - * @inheritdoc - */ - prev(): ListIteratorBase; - /** - * @inheritdoc - */ - next(): ListIteratorBase; - /** - * @inheritdoc - */ - advance(step: number): ListIteratorBase; - /** - * @inheritdoc - */ - readonly value: T; - /** - * @inheritdoc - */ - equals(obj: ListIteratorBase): boolean; - /** - * @inheritdoc - */ - swap(obj: ListIteratorBase): void; - } -} -declare namespace std.base { - /** - *

An abstract map.

- * - *

{@link MapContainer MapContainers} are associative containers that store elements formed by a combination - * of a key value (Key) and a mapped value (T), and which allows for fast retrieval - * of individual elements based on their keys.

- * - *

In a {@link MapContainer}, the key values are generally used to identify the elements, while the - * mapped values store the content associated to this key. The types of key and - * mapped value may differ, and are grouped together in member type value_type, which is a - * {@link Pair} type combining both:

- * - *

typedef pair value_type;

- * - *

{@link MapContainer} stores elements, keeps sequence and enables indexing by inserting elements into a - * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index - * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

- * - *

- *

- * - *

Container properties

- *
- *
Associative
- *
- * Elements in associative containers are referenced by their key and not by their absolute position - * in the container. - *
- * - *
Map
- *
- * Each element associates a key to a mapped value: - * Keys are meant to identify the elements whose main content is the mapped value. - *
- *
- * - * @param Type of the keys. Each element in a map is identified by its key value. - * @param Type of the mapped value. Each element in a map stores some data as its mapped value. - * - * @author Jeongho Nam - */ - abstract class MapContainer extends Container> { - /** - *

{@link List} storing elements.

- * - *

Storing elements and keeping those sequence of the {@link MapContainer} are implemented by - * {@link data_ this list container}. Implementing index-table is also related with {@link data_ this list} - * by storing {@link ListIterator iterators} ({@link MapIterator} references {@link ListIterator}) who are - * created from {@link data_ here}.

- */ - private data_; - /** - * Default Constructor. - */ - protected constructor(); - /** - * @inheritdoc - */ - assign>>(first: InputIterator, last: InputIterator): void; - /** - * @inheritdoc - */ - clear(): void; - /** - *

Get iterator to element.

- * - *

Searches the container for an element with a identifier equivalent to key and returns an - * iterator to it if found, otherwise it returns an iterator to {@link end end()}.

- * - *

Two keys are considered equivalent if the container's comparison object returns false reflexively - * (i.e., no matter the order in which the elements are passed as arguments).

- * - *

Another member functions, {@link has has()} and {@link count count()}, can be used to just check - * whether a particular key exists.

- * - * @param key Key to be searched for - * @return An iterator to the element, if an element with specified key is found, or - * {@link end end()} otherwise. - */ - abstract find(key: Key): MapIterator; - /** - *

Return iterator to beginning.

- * - *

Returns an iterator referring the first element in the

- * - *

Note

- *

If the container is {@link empty}, the returned iterator is same with {@link end end()}.

- * - * @return An iterator to the first element in the The iterator containes the first element's value. - */ - begin(): MapIterator; - /** - *

Return iterator to end.

- *

Returns an iterator referring to the past-the-end element in the

- * - *

The past-the-end element is the theoretical element that would follow the last element in the - * It does not point to any element, and thus shall not be dereferenced.

- * - *

Because the ranges used by functions of the container do not include the element reference by their - * closing iterator, this function is often used in combination with {@link MapContainer}.{@link begin} to - * specify a range including all the elements in the

- * - *

Note

- *

Returned iterator from {@link MapContainer}.{@link end} does not refer any element. Trying to accessing - * element by the iterator will cause throwing exception ({@link OutOfRange}).

- * - *

If the container is {@link empty}, this function returns the same as {@link begin}.

- * - * @return An iterator to the end element in the - */ - end(): MapIterator; - /** - *

Return {@link MapReverseIterator reverse iterator} to reverse beginning.

- * - *

Returns a {@link MapReverseIterator reverse iterator} pointing to the last element in the container - * (i.e., its reverse beginning).

- * - * {@link MapReverseIterator Reverse iterators} iterate backwards: increasing them moves them towards the - * beginning of the container.

- * - *

{@link rbegin} points to the element preceding the one that would be pointed to by member {@link end}. - *

7 - * - * @return A {@link MapReverseIterator reverse iterator} to the reverse beginning of the sequence - * - */ - rbegin(): MapReverseIterator; - /** - *

Return {@link MapReverseIterator reverse iterator} to reverse end.

- * - *

Returns a {@link MapReverseIterator reverse iterator} pointing to the theoretical element right before - * the first element in the {@link MapContainer map container} (which is considered its reverse end). - *

- * - *

The range between {@link MapContainer}.{@link rbegin} and {@link MapContainer}.{@link rend} contains - * all the elements of the container (in reverse order).

- * - * @return A {@link MapReverseIterator reverse iterator} to the reverse end of the sequence - */ - rend(): MapReverseIterator; - /** - *

Whether have the item or not.

- * - *

Indicates whether a map has an item having the specified identifier.

- * - * @param key Key value of the element whose mapped value is accessed. - * - * @return Whether the map has an item having the specified identifier. - */ - has(key: Key): boolean; - /** - *

Count elements with a specific key.

- * - *

Searches the container for elements whose key is key and returns the number of elements found.

- * - * @param key Key value to be searched for. - * - * @return The number of elements in the container with a key. - */ - abstract count(key: Key): number; - /** - * Return the number of elements in the map. - */ - size(): number; - /** - * @inheritdoc - */ - push(...args: Pair[]): number; - /** - * @inheritdoc - */ - push(...args: [Key, T][]): number; - /** - * Construct and insert element with hint - * - * Inserts a new element in the {@link MapContainer map container}. This new element is constructed in - * place using *args* as the arguments for the element's constructor. *hint* points to a location in the - * container suggested as a hint on where to start the search for its insertion point (the container may or - * may not use this suggestion to optimize the insertion operation). - * - * A similar member function exists, {@link insert}, which either copies or moves an existing object into - * the container, and may also take a position *hint*. - * - * @param hint Hint for the position where the element can be inserted. - * @param key The key used both to look up and to insert if not found. - * @param value Value, the item. - * - * @return An iterator pointing to either the newly inserted element or to the element that already had an - * equivalent key in the {@link MapContainer}. - */ - emplace_hint(hint: MapIterator, key: Key, val: T): MapIterator; - /** - * Construct and insert element with hint - * - * Inserts a new element in the {@link MapContainer map container}. This new element is constructed in - * place using *args* as the arguments for the element's constructor. *hint* points to a location in the - * container suggested as a hint on where to start the search for its insertion point (the container may or - * may not use this suggestion to optimize the insertion operation). - * - * A similar member function exists, {@link insert}, which either copies or moves an existing object into - * the container, and may also take a position *hint*. - * - * @param hint Hint for the position where the element can be inserted. - * @param key The key used both to look up and to insert if not found. - * @param value Value, the item. - * - * @return An {@link MapIterator iterator} pointing to either the newly inserted element or to the element - * that already had an equivalent key in the {@link MapContainer}. - */ - emplace_hint(hint: MapReverseIterator, key: Key, val: T): MapReverseIterator; - /** - * Construct and insert element with hint - * - * Inserts a new element in the {@link MapContainer map container}. This new element is constructed in - * place using *args* as the arguments for the element's constructor. *hint* points to a location in the - * container suggested as a hint on where to start the search for its insertion point (the container may or - * may not use this suggestion to optimize the insertion operation). - * - * A similar member function exists, {@link insert}, which either copies or moves an existing object into - * the container, and may also take a position *hint*. - * - * @param hint Hint for the position where the element can be inserted. - * @param pair A single argument of a {@link Pair} type with a value for the *key* as - * {@link Pair.first first} member, and a *value* for the mapped value as - * {@link Pair.second second}. - * - * @return An iterator pointing to either the newly inserted element or to the element that already had an - * equivalent key in the {@link MapContainer}. - */ - emplace_hint(hint: MapIterator, pair: Pair): MapIterator; - /** - * Construct and insert element with hint - * - * Inserts a new element in the {@link MapContainer map container}. This new element is constructed in - * place using *args* as the arguments for the element's constructor. *hint* points to a location in the - * container suggested as a hint on where to start the search for its insertion point (the container may or - * may not use this suggestion to optimize the insertion operation). - * - * A similar member function exists, {@link insert}, which either copies or moves an existing object into - * the container, and may also take a position *hint*. - * - * @param hint Hint for the position where the element can be inserted. - * @param pair A single argument of a {@link Pair} type with a value for the *key* as - * {@link Pair.first first} member, and a *value* for the mapped value as - * {@link Pair.second second}. - * - * @return An {@link MapIterator iterator} pointing to either the newly inserted element or to the element - * that already had an equivalent key in the {@link MapContainer}. - */ - emplace_hint(hint: MapReverseIterator, pair: Pair): MapReverseIterator; - /** - *

Insert an element.

- * - *

Extends the container by inserting a new element, effectively increasing the container {@link size} - * by the number of element inserted (zero or one).

- * - * @param hint Hint for the position where the element can be inserted. - * @param pair A single argument of a {@link Pair} type with a value for the *key* as - * {@link Pair.first first} member, and a *value* for the mapped value as - * {@link Pair.second second}. - * - * @return An iterator pointing to either the newly inserted element or to the element that already had an - * equivalent key in the {@link MapContainer}. - */ - insert(hint: MapIterator, pair: Pair): MapIterator; - /** - *

Insert an element.

- * - *

Extends the container by inserting a new element, effectively increasing the container {@link size} - * by the number of element inserted (zero or one).

- * - * @param hint Hint for the position where the element can be inserted. - * @param pair A single argument of a {@link Pair} type with a value for the *key* as - * {@link Pair.first first} member, and a *value* for the mapped value as - * {@link Pair.second second}. - * - * @return An iterator pointing to either the newly inserted element or to the element that already had an - * equivalent key in the {@link MapContainer}. - */ - insert(hint: MapReverseIterator, pair: Pair): MapReverseIterator; - /** - *

Insert an element.

- * - *

Extends the container by inserting new elements, effectively increasing the container {@link size} - * by the number of elements inserted.

- * - * @param hint Hint for the position where the element can be inserted. - * @param tuple Tuple represensts the {@link Pair} to be inserted as an element. - * - * @return An iterator pointing to either the newly inserted element or to the element that already had an - * equivalent key in the {@link MapContainer}. - */ - insert(hint: MapIterator, tuple: [L, U]): MapIterator; - /** - *

Insert an element.

- * - *

Extends the container by inserting new elements, effectively increasing the container {@link size} - * by the number of elements inserted.

- * - * @param hint Hint for the position where the element can be inserted. - * @param tuple Tuple represensts the {@link Pair} to be inserted as an element. - * - * @return An iterator pointing to either the newly inserted element or to the element that already had an - * equivalent key in the {@link MapContainer}. - */ - insert(hint: MapReverseIterator, tuple: [L, U]): MapReverseIterator; - /** - *

Insert elements from range iterators.

- * - *

Extends the container by inserting new elements, effectively increasing the container {@link size} by - * the number of elements inserted.

- * - * @param begin Input iterator specifying initial position of a range of elements. - * @param end Input iterator specifying final position of a range of elements. - * Notice that the range includes all the elements between begin and end, - * including the element pointed by begin but not the one pointed by end. - */ - insert>>(first: InputIterator, last: InputIterator): void; - /** - * @hidden - */ - protected abstract _Insert_by_pair(pair: Pair): any; - /** - * @hidden - */ - private insert_by_tuple(tuple); - /** - * @hidden - */ - protected abstract _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; - /** - * @hidden - */ - private insert_by_hint_with_tuple(hint, tuple); - /** - * @hidden - */ - protected abstract _Insert_by_range>>(first: InputIterator, last: InputIterator): void; - /** - *

Erase an elemet by key.

- * - *

Removes from the {@link MapContainer map container} a single element.

- * - *

This effectively reduces the container {@link size} by the number of element removed (zero or one), - * which are destroyed.

- * - * @param key Key of the element to be removed from the {@link MapContainer}. - */ - erase(key: Key): number; - /** - *

Erase an elemet by iterator.

- * - *

Removes from the {@link MapContainer map container} a single element.

- * - *

This effectively reduces the container {@link size} by the number of element removed (zero or one), - * which are destroyed.

- * - * @param it Iterator specifying position winthin the {@link MapContainer map contaier} to be removed. - */ - erase(it: MapIterator): MapIterator; - /** - *

Erase elements by range iterators.

- * - *

Removes from the {@link MapContainer map container} a range of elements.

- * - *

This effectively reduces the container {@link size} by the number of elements removed, which are - * destroyed.

- * - * @param begin An iterator specifying initial position of a range within {@link MApContainer map container} - * to be removed. - * @param end An iterator specifying initial position of a range within {@link MApContainer map container} - * to be removed. - * Notice that the range includes all the elements between begin and end, - * including the element pointed by begin but not the one pointed by end. - */ - erase(begin: MapIterator, end: MapIterator): MapIterator; - /** - *

Erase an elemet by iterator.

- * - *

Removes from the {@link MapContainer map container} a single element.

- * - *

This effectively reduces the container {@link size} by the number of element removed (zero or one), - * which are destroyed.

- * - * @param it Iterator specifying position winthin the {@link MapContainer map contaier} to be removed. - */ - erase(it: MapReverseIterator): MapReverseIterator; - /** - *

Erase elements by range iterators.

- * - *

Removes from the {@link MapContainer map container} a range of elements.

- * - *

This effectively reduces the container {@link size} by the number of elements removed, which are - * destroyed.

- * - * @param begin An iterator specifying initial position of a range within {@link MApContainer map container} - * to be removed. - * @param end An iterator specifying initial position of a range within {@link MApContainer map container} - * to be removed. - * Notice that the range includes all the elements between begin and end, - * including the element pointed by begin but not the one pointed by end. - */ - erase(begin: MapReverseIterator, end: MapReverseIterator): MapReverseIterator; - /** - * @hidden - */ - private erase_by_key(key); - /** - * @hidden - */ - private erase_by_iterator(first, last?); - /** - * @hidden - */ - private erase_by_range(first, last); - /** - * @hidden - */ - protected _Swap(obj: MapContainer): void; - /** - * Merge two maps. - * - * Extracts and transfers elements from *source* to this container. - * - * @param source A {@link MapContainer map container} to transfer the elements from. - */ - abstract merge(source: MapContainer): void; - /** - *

Abstract method handling insertions for indexing.

- * - *

This method, {@link _Handle_insert} is designed to register the first to last to somewhere storing - * those {@link MapIterator iterators} for indexing, fast accessment and retrievalance.

- * - *

When {@link insert} is called, new elements will be inserted into the {@link data_ list container} and new - * {@link MapIterator iterators} first to last, pointing the inserted elements, will be created and the - * newly created iterators first to last will be shifted into this method {@link _Handle_insert} after the - * insertions.

- * - *

If the derived one is {@link RBTree tree-based} like {@link TreeSet}, the {@link MapIterator iterators} - * will be registered into the {@link TreeSet.tree_ tree} as a {@link XTreeNode tree node item}. Else if the - * derived one is {@link HashBuckets hash-based} like {@link HashSet}, the first to last will be - * registered into the {@link HashSet.hash_buckets_ hash bucket}.

- * - * @param first An {@link MapIterator} to the initial position in a sequence. - * @param last An {@link MapIterator} to the final position in a sequence. The range used is - * [first, last), which contains all the elements between first and last, - * including the element pointed by first but not the element pointed by last. - */ - protected abstract _Handle_insert(first: MapIterator, last: MapIterator): void; - /** - *

Abstract method handling deletions for indexing.

- * - *

This method, {@link _Handle_erase} is designed to unregister the first to last to somewhere storing - * those {@link MapIterator iterators} for indexing, fast accessment and retrievalance.

- * - *

When {@link erase} is called with first to last, {@link MapIterator iterators} positioning somewhere - * place to be deleted, is memorized and shifted to this method {@link _Handle_erase} after the deletion process is - * terminated.

- * - *

If the derived one is {@link RBTree tree-based} like {@link TreeSet}, the {@link MapIterator iterators} - * will be unregistered from the {@link TreeSet.tree_ tree} as a {@link XTreeNode tree node item}. Else if the - * derived one is {@link HashBuckets hash-based} like {@link HashSet}, the first to last will be - * unregistered from the {@link HashSet.hash_buckets_ hash bucket}.

- * - * @param first An {@link MapIterator} to the initial position in a sequence. - * @param last An {@link MapIterator} to the final position in a sequence. The range used is - * [first, last), which contains all the elements between first and last, - * including the element pointed by first but not the element pointed by last. - */ - protected abstract _Handle_erase(first: MapIterator, last: MapIterator): void; - } - /** - * @hidden - */ - class MapElementList extends ListContainer, MapIterator> { - private associative_; - private rend_; - constructor(associative: MapContainer); - protected _Create_iterator(prev: MapIterator, next: MapIterator, val: Pair): MapIterator; - protected _Set_begin(it: MapIterator): void; - get_associative(): MapContainer; - rbegin(): MapReverseIterator; - rend(): MapReverseIterator; - } -} -declare namespace std { - /** - *

An iterator of {@link MapContainer map container}.

- * - *

- *

- * - * @author Jeongho Nam - */ - class MapIterator extends base.ListIteratorBase> implements IComparable> { - /** - * Construct from the {@link MapContainer source map} and {@link ListIterator list iterator}. - * - * @param source The source {@link MapContainer}. - * @param list_iterator A {@link ListIterator} pointing {@link Pair} of key and value. - */ - constructor(source: base.MapElementList, prev: MapIterator, next: MapIterator, val: Pair); - /** - * Get iterator to previous element. - */ - prev(): MapIterator; - /** - * Get iterator to next element. - */ - next(): MapIterator; - /** - * Advances the Iterator by n element positions. - * - * @param step Number of element positions to advance. - * @return An advanced Iterator. - */ - advance(step: number): MapIterator; - /** - * @hidden - */ - get_source(): base.MapContainer; - /** - * Get first, key element. - */ - readonly first: Key; - /** - * Get second, value element. - */ - /** - * Set second value. - */ - second: T; - /** - * @inheritdoc - */ - less(obj: MapIterator): boolean; - /** - * @inheritdoc - */ - equals(obj: MapIterator): boolean; - /** - * @inheritdoc - */ - hashCode(): number; - /** - * @inheritdoc - */ - swap(obj: MapIterator): void; - } - /** - *

A reverse-iterator of {@link MapContainer map container}.

- * - *

- *

- * - * @author Jeongho Nam - */ - class MapReverseIterator extends ReverseIterator, MapIterator, MapReverseIterator> { - /** - * Construct from base iterator. - * - * @param base A reference of the base iterator, which iterates in the opposite direction. - */ - constructor(base: MapIterator); - /** - * @hidden - */ - protected _Create_neighbor(base: MapIterator): MapReverseIterator; - /** - * Get first, key element. - */ - readonly first: Key; - /** - * Get second, value element. - */ - /** - * Set second value. - */ - second: T; - } -} -declare namespace std.base { - /** - *

An abstract multi-map.

- * - *

{@link MultiMap MultiMaps} are associative containers that store elements formed by a combination of a - * key value (Key) and a mapped value (T), and which allows for fast retrieval of - * individual elements based on their keys.

- * - *

In a {@link MapContainer}, the key values are generally used to identify the elements, while the - * mapped values store the content associated to this key. The types of key and - * mapped value may differ, and are grouped together in member type value_type, which is a - * {@link Pair} type combining both:

- * - *

typedef pair value_type;

- * - *

{@link UniqueMap} stores elements, keeps sequence and enables indexing by inserting elements into a - * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index - * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

- * - *

- *

- * - *

Container properties

- *
- *
Associative
- *
- * Elements in associative containers are referenced by their key and not by their absolute position - * in the container. - *
- * - *
Map
- *
- * Each element associates a key to a mapped value: - * Keys are meant to identify the elements whose main content is the mapped value. - *
- * - *
Multiple equivalent keys
- *
Multiple elements in the container can have equivalent keys.
- *
- * - * @param Type of the keys. Each element in a map is identified by its key value. - * @param Type of the mapped value. Each element in a map stores some data as its mapped value. - * - * @author Jeongho Nam - */ - abstract class MultiMap extends MapContainer { - /** - * Construct and insert element. - * - * Inserts a new element in the {@link MultiMap}. This new element is constructed in place using args - * as the arguments for the element's constructor. - * - * This effectively increases the container {@link size} by one. - * - * A similar member function exists, {@link insert}, which either copies or moves existing objects into the - * container. - * - * @param key The key used both to look up and to insert if not found. - * @param value Value, the item. - * - * @return An {@link MapIterator iterator} to the newly inserted element. - */ - emplace(key: Key, value: T): MapIterator; - /** - * Construct and insert element. - * - * Inserts a new element in the {@link MultiMap}. This new element is constructed in place using args - * as the arguments for the element's constructor. - * - * This effectively increases the container {@link size} by one. - * - * A similar member function exists, {@link insert}, which either copies or moves existing objects into the - * container. - * - * @param pair A single argument of a {@link Pair} type with a value for the *key* as - * {@link Pair.first first} member, and a *value* for the mapped value as - * {@link Pair.second second}. - * @return An {@link MapIterator iterator} to the newly inserted element. - */ - emplace(pair: Pair): MapIterator; - /** - *

Insert elements.

- * - *

Extends the container by inserting new elements, effectively increasing the container {@link size} by - * the number of elements inserted.

- * - * @param pair A single argument of a {@link Pair} type with a value for the *key* as - * {@link Pair.first first} member, and a *value* for the mapped value as - * {@link Pair.second second}. - * - * @return An iterator pointing to the newly inserted element. - */ - insert(pair: Pair): MapIterator; - /** - *

Insert elements.

- * - *

Extends the container by inserting new elements, effectively increasing the container {@link size} by - * the number of elements inserted.

- * - * @param tuple Tuple represensts the {@link Pair} to be inserted as an element. - * - * @return An iterator pointing to the newly inserted element. - */ - insert(tuple: [L, U]): MapIterator; - /** - * @inheritdoc - */ - insert(hint: MapIterator, pair: Pair): MapIterator; - /** - * @inheritdoc - */ - insert(hint: MapReverseIterator, pair: Pair): MapReverseIterator; - /** - * @inheritdoc - */ - insert(hint: MapIterator, tuple: [L, U]): MapIterator; - /** - * @inheritdoc - */ - insert(hint: MapReverseIterator, tuple: [L, U]): MapReverseIterator; - /** - * @inheritdoc - */ - insert>>(first: InputIterator, last: InputIterator): void; - /** - * @inheritdoc - */ - merge(source: MapContainer): void; - } -} -declare namespace std.base { - /** - *

An abstract set.

- * - *

{@link SetContainer SetContainers} are containers that store elements allowing fast retrieval of - * individual elements based on their value.

- * - *

In an {@link SetContainer}, the value of an element is at the same time its key, used to - * identify it. Keys are immutable, therefore, the elements in an {@link SetContainer} cannot be - * modified once in the container - they can be inserted and removed, though.

- * - *

{@link SetContainer} stores elements, keeps sequence and enables indexing by inserting elements into a - * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index - * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

- * - *

- *

- * - *

Container properties

- *
- *
Associative
- *
- * Elements in associative containers are referenced by their key and not by their absolute - * position in the container. - *
- * - *
Set
- *
The value of an element is also the key used to identify it.
- *
- * - * @param Type of the elements. Each element in a {@link SetContainer} container is also identified - * by this value (each value is itself also the element's key). - * - * @author Jeongho Nam - */ - abstract class SetContainer extends Container { - /** - *

{@link List} storing elements.

- * - *

Storing elements and keeping those sequence of the {@link SetContainer} are implemented by - * {@link data_ this list container}. Implementing index-table is also related with {@link data_ this list} - * by storing {@link ListIterator iterators} ({@link SetIterator} references {@link ListIterator}) who are - * created from {@link data_ here}.

- */ - private data_; - /** - * Default Constructor. - */ - protected constructor(); - /** - * @inheritdoc - */ - assign>(begin: Iterator, end: Iterator): void; - /** - * @inheritdoc - */ - clear(): void; - /** - *

Get iterator to element.

- * - *

Searches the container for an element with key as value and returns an iterator to it if found, - * otherwise it returns an iterator to {@link end end()} (the element past the end of the container).

- * - *

Another member function, {@link count count()}, can be used to just check whether a particular element - * exists.

- * - * @param key Key to be searched for. - * - * @return An iterator to the element, if the specified value is found, or {@link end end()} if it is not - * found in the - */ - abstract find(val: T): SetIterator; - /** - * @inheritdoc - */ - begin(): SetIterator; - /** - * @inheritdoc - */ - end(): SetIterator; - /** - * @inheritdoc - */ - rbegin(): SetReverseIterator; - /** - * @inheritdoc - */ - rend(): SetReverseIterator; - /** - *

Whether have the item or not.

- * - *

Indicates whether a set has an item having the specified identifier.

- * - * @param key Key value of the element whose mapped value is accessed. - * - * @return Whether the set has an item having the specified identifier. - */ - has(val: T): boolean; - /** - *

Count elements with a specific key.

- * - *

Searches the container for elements with a value of k and returns the number of elements found.

- * - * @param key Value of the elements to be counted. - * - * @return The number of elements in the container with a key. - */ - abstract count(val: T): number; - /** - * @inheritdoc - */ - size(): number; - /** - * @inheritdoc - */ - push(...args: T[]): number; - /** - *

Insert an element with hint.

- * - *

Extends the container by inserting new elements, effectively increasing the container size by the - * number of elements inserted.

- * - * @param hint Hint for the position where the element can be inserted. - * @param val Value to be inserted as an element. - * - * @return An iterator pointing to either the newly inserted element or to the element that already had its - * same value in the {@link SetContainer}. - */ - insert(hint: SetIterator, val: T): SetIterator; - /** - *

Insert an element with hint.

- * - *

Extends the container by inserting new elements, effectively increasing the container size by the - * number of elements inserted.

- * - * @param hint Hint for the position where the element can be inserted. - * @param val Value to be inserted as an element. - * - * @return An iterator pointing to either the newly inserted element or to the element that already had its - * same value in the {@link SetContainer}. - */ - insert(hint: SetReverseIterator, val: T): SetReverseIterator; - /** - *

Insert elements with a range of a

- * - *

Extends the container by inserting new elements, effectively increasing the container size by the - * number of elements inserted.

- * - * @param begin An iterator specifying range of the begining element. - * @param end An iterator specifying range of the ending element. - */ - insert>(begin: InputIterator, end: InputIterator): void; - /** - * @hidden - */ - protected abstract _Insert_by_val(val: T): any; - /** - * @hidden - */ - protected abstract _Insert_by_hint(hint: SetIterator, val: T): SetIterator; - /** - * @hidden - */ - protected abstract _Insert_by_range>(begin: InputIterator, end: InputIterator): void; - /** - *

Erase an element.

- *

Removes from the set container the elements whose value is key.

- * - *

This effectively reduces the container size by the number of elements removed.

- * - * @param key Value of the elements to be erased. - * - * @return Number of elements erased. - */ - erase(val: T): number; - /** - * @inheritdoc - */ - erase(it: SetIterator): SetIterator; - /** - *

Erase elements.

- *

Removes from the set container a range of elements..

- * - *

This effectively reduces the container size by the number of elements removed.

- * - * @param begin An iterator specifying a range of beginning to erase. - * @param end An iterator specifying a range of end to erase. - */ - erase(begin: SetIterator, end: SetIterator): SetIterator; - /** - * @inheritdoc - */ - erase(it: SetReverseIterator): SetReverseIterator; - /** - *

Erase elements.

- *

Removes from the set container a range of elements..

- * - *

This effectively reduces the container size by the number of elements removed.

- * - * @param begin An iterator specifying a range of beginning to erase. - * @param end An iterator specifying a range of end to erase. - */ - erase(begin: SetReverseIterator, end: SetReverseIterator): SetReverseIterator; - /** - * @hidden - */ - private erase_by_iterator(first, last?); - /** - * @hidden - */ - private erase_by_val(val); - /** - * @hidden - */ - private erase_by_range(first, last); - /** - * @hidden - */ - protected _Swap(obj: SetContainer): void; - /** - * Merge two sets. - * - * Extracts and transfers elements from *source* to this container. - * - * @param source A {@link SetContainer set container} to transfer the elements from. - */ - abstract merge(source: SetContainer): void; - /** - *

Abstract method handling insertions for indexing.

- * - *

This method, {@link _Handle_insert} is designed to register the first to last to somewhere storing - * those {@link SetIterator iterators} for indexing, fast accessment and retrievalance.

- * - *

When {@link insert} is called, new elements will be inserted into the {@link data_ list container} and new - * {@link SetIterator iterators} first to last, pointing the inserted elements, will be created and the - * newly created iterators first to last will be shifted into this method {@link _Handle_insert} after the - * insertions.

- * - *

If the derived one is {@link RBTree tree-based} like {@link TreeSet}, the {@link SetIterator iterators} - * will be registered into the {@link TreeSet.tree_ tree} as a {@link XTreeNode tree node item}. Else if the - * derived one is {@link HashBuckets hash-based} like {@link HashSet}, the first to last will be - * registered into the {@link HashSet.hash_buckets_ hash bucket}.

- * - * @param first An {@link SetIterator} to the initial position in a sequence. - * @param last An {@link SetIterator} to the final position in a sequence. The range used is - * [first, last), which contains all the elements between first and last, - * including the element pointed by first but not the element pointed by last. - */ - protected abstract _Handle_insert(first: SetIterator, last: SetIterator): void; - /** - *

Abstract method handling deletions for indexing.

- * - *

This method, {@link _Handle_erase} is designed to unregister the first to last to somewhere storing - * those {@link SetIterator iterators} for indexing, fast accessment and retrievalance.

- * - *

When {@link erase} is called with first to last, {@link SetIterator iterators} positioning somewhere - * place to be deleted, is memorized and shifted to this method {@link _Handle_erase} after the deletion process is - * terminated.

- * - *

If the derived one is {@link RBTree tree-based} like {@link TreeSet}, the {@link SetIterator iterators} - * will be unregistered from the {@link TreeSet.tree_ tree} as a {@link XTreeNode tree node item}. Else if the - * derived one is {@link HashBuckets hash-based} like {@link HashSet}, the first to last will be - * unregistered from the {@link HashSet.hash_buckets_ hash bucket}.

- * - * @param first An {@link SetIterator} to the initial position in a sequence. - * @param last An {@link SetIterator} to the final position in a sequence. The range used is - * [first, last), which contains all the elements between first and last, - * including the element pointed by first but not the element pointed by last. - */ - protected abstract _Handle_erase(first: SetIterator, last: SetIterator): void; - } - /** - * @hidden - */ - class SetElementList extends ListContainer> { - private associative_; - private rend_; - constructor(associative: SetContainer); - protected _Create_iterator(prev: SetIterator, next: SetIterator, val: T): SetIterator; - protected _Set_begin(it: SetIterator): void; - get_associative(): SetContainer; - rbegin(): SetReverseIterator; - rend(): SetReverseIterator; - } -} -declare namespace std { - /** - *

An iterator of a Set.

- * - *

- *

- * - * @author Jeongho Nam - */ - class SetIterator extends base.ListIteratorBase implements IComparable> { - /** - *

Construct from source and index number.

- * - *

Note

- *

Do not create iterator directly.

- *

Use begin(), find() or end() in Map instead.

- * - * @param map The source Set to reference. - * @param index Sequence number of the element in the source Set. - */ - constructor(source: base.SetElementList, prev: SetIterator, next: SetIterator, val: T); - /** - * @inheritdoc - */ - get_source(): base.SetContainer; - /** - * @inheritdoc - */ - prev(): SetIterator; - /** - * @inheritdoc - */ - next(): SetIterator; - /** - * @inheritdoc - */ - advance(size: number): SetIterator; - /** - * @inheritdoc - */ - less(obj: SetIterator): boolean; - /** - * @inheritdoc - */ - equals(obj: SetIterator): boolean; - /** - * @inheritdoc - */ - hashCode(): number; - /** - * @inheritdoc - */ - swap(obj: SetIterator): void; - } - /** - *

A reverse-iterator of Set.

- * - *

- *

- * - * @param Type of the elements. - * - * @author Jeongho Nam - */ - class SetReverseIterator extends ReverseIterator, SetReverseIterator> { - /** - * Construct from base iterator. - * - * @param base A reference of the base iterator, which iterates in the opposite direction. - */ - constructor(base: SetIterator); - /** - * @hidden - */ - protected _Create_neighbor(base: SetIterator): SetReverseIterator; - } -} -declare namespace std.base { - /** - *

An abstract set.

- * - *

{@link SetContainer SetContainers} are containers that store elements allowing fast retrieval of - * individual elements based on their value.

- * - *

In an {@link SetContainer}, the value of an element is at the same time its key, used to - * identify it. Keys are immutable, therefore, the elements in an {@link SetContainer} cannot be - * modified once in the container - they can be inserted and removed, though.

- * - *

{@link SetContainer} stores elements, keeps sequence and enables indexing by inserting elements into a - * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index - * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

- * - *

- *

- * - *

Container properties

- *
- *
Associative
- *
- * Elements in associative containers are referenced by their key and not by their absolute - * position in the container. - *
- * - *
Set
- *
The value of an element is also the key used to identify it.
- * - *
Multiple equivalent keys
- *
Multiple elements in the container can have equivalent keys.
- *
- * - * @param Type of the elements. Each element in a {@link SetContainer} container is also identified - * by this value (each value is itself also the element's key). - * - * @author Jeongho Nam - */ - abstract class MultiSet extends SetContainer { - /** - *

Insert an element.

- * - *

Extends the container by inserting new elements, effectively increasing the container {@link size} by - * the number of elements inserted.

- * - * @param key Value to be inserted as an element. - * - * @return An iterator to the newly inserted element. - */ - insert(val: T): SetIterator; - /** - * @inheritdoc - */ - insert(hint: SetIterator, val: T): SetIterator; - /** - * @inheritdoc - */ - insert(hint: SetReverseIterator, val: T): SetReverseIterator; - /** - * @inheritdoc - */ - insert>(begin: InputIterator, end: InputIterator): void; - /** - * @inheritdoc - */ - merge(source: SetContainer): void; - } -} -declare namespace std.base { - /** - *

Red-black Tree.

- * - *

A red-black tree is a kind of self-balancing - * binary search tree. Each node of the binary tree has an extra bit, and that bit is often interpreted as the - * color (red or black) of the node. These color bits - * are used to ensure the tree remains approximately balanced during insertions and deletions.

- * - *

Balance is preserved by painting each node of the tree with one of two colors (typically called - * 'red' and 'black') in a way that satisfies certain - * properties, which collectively constrain how unbalanced the tree can become in the worst case. When the tree - * is modified, the new tree is subsequently rearranged and repainted to restore the coloring properties. The - * properties are designed in such a way that this rearranging and recoloring can be performed efficiently.

- * - *

The balancing of the tree is not perfect but it is good enough to allow it to guarantee searching in - * O(log n) time, where n is the total number of elements in the tree. The insertion and deletion operations, - * along with the tree rearrangement and recoloring, are also performed in O(log n) time.

- * - *

Tracking the color of each node requires only 1 bit of information per node because there are only two - * colors. The tree does not contain any other data specific to its being a - * red-black tree so its memory footprint is almost - * identical to a classic (uncolored) binary search tree. In many cases the additional bit of information can - * be stored at no additional memory cost.

- * - *

Properties

- *

In addition to the requirements imposed on a binary search tree the following must be satisfied by a - * red-black tree:

- * - *
    - *
  1. A node is either red or black.
  2. - *
  3. - * The root is black. This rule is sometimes omitted. Since the root can - * always be changed from red to black, but not - * necessarily vice versa, this rule has little effect on analysis. - *
  4. - *
  5. All leaves (NIL; null) are black.
  6. - *
  7. - * If a node is red, then both its children are - * black. - *
  8. - *
  9. - * Every path from a given node to any of its descendant NIL nodes contains the same number of - * black nodes. Some definitions: the number of - * black nodes from the root to a node is the node's - * black depth; the uniform number of black - * nodes in all paths from root to the leaves is called the black-height of - * the red-black tree. - *
  10. - *
- * - *

- * - *

These constraints enforce a critical property of red-black trees: the path from the root to the farthest - * leaf is no more than twice as long as the path from the root to the nearest leaf. The result is that the tree - * is roughly height-balanced. Since operations such as inserting, deleting, and finding values require - * worst-case time proportional to the height of the tree, this theoretical upper bound on the height allows - * red-black trees to be efficient in the worst case, unlike ordinary binary search trees.

- * - *

To see why this is guaranteed, it suffices to consider the effect of properties 4 and 5 together. For a - * red-black tree T, let B be the number of black nodes in property 5. Let the - * shortest possible path from the root of T to any leaf consist of B black nodes. - * Longer possible paths may be constructed by inserting red nodes. However, property 4 - * makes it impossible to insert more than one consecutive red node. Therefore, - * ignoring any black NIL leaves, the longest possible path consists of 2*B nodes, - * alternating black and red (this is the worst case). - * Counting the black NIL leaves, the longest possible path consists of 2*B-1 - * nodes.

- * - *

The shortest possible path has all black nodes, and the longest possible - * path alternates between red and black nodes. Since all - * maximal paths have the same number of black nodes, by property 5, this shows - * that no path is more than twice as long as any other path.

- * - * @param Type of elements. - * - * @reference https://en.wikipedia.org/w/index.php?title=Red%E2%80%93black_tree - * @inventor Rudolf Bayer - * @author Migrated by Jeongho Nam - */ - abstract class XTree { - /** - * Root node. - */ - protected root_: XTreeNode; - /** - * Default Constructor. - */ - protected constructor(); - /** - * Clear, removes all tree nodes. - */ - clear(): void; - /** - * Find a node from its contained value. - * - * @param val Value to find. - */ - find(val: T): XTreeNode; - /** - * Fetch maximum (the rightes?) node from one. - * - * @param node A node to fetch its maximum node. - * @return The maximum node. - */ - protected fetch_maximum(node: XTreeNode): XTreeNode; - abstract is_less(left: T, right: T): boolean; - abstract is_equal_to(left: T, right: T): boolean; - /** - *

Insert an element with a new node.

- * - *

Insertion begins by adding the node as any binary search tree insertion does and by coloring it - * red. Whereas in the binary search tree, we always add a leaf, in the red-black - * tree, leaves contain no information, so instead we add a red interior node, with - * two black leaves, in place of an existing - * black leaf.

- * - *

What happens next depends on the color of other nearby nodes. The term uncle node will be used to - * refer to the sibling of a node's parent, as in human family trees. Note that:

- * - *
    - *
  • property 3 (all leaves are black) always holds.
  • - *
  • - * property 4 (both children of every red node are - * black) is threatened only by adding a red - * node, repainting a black node red, or a - * rotation. - *
  • - *
  • - * property 5 (all paths from any given node to its leaf nodes contain the same number of - * black nodes) is threatened only by adding a - * black node, repainting a red node - * black (or vice versa), or a rotation. - *
  • - *
- * - *

Notes

- *
    - *
  1. - * The label N will be used to denote the current node (colored - * red). In the diagrams N carries a blue contour. At the - * beginning, this is the new node being inserted, but the entire procedure may also be applied - * recursively to other nodes (see case 3). {@link XTreeNode.parent P} will denote - * N's parent node, {@link XTreeNode.grand_parent G} will denote N's - * grandparent, and {@link XTreeNode.uncle U} will denote N's uncle. In between - * some cases, the roles and labels of the nodes are exchanged, but in each case, every label continues - * to represent the same node it represented at the beginning of the case. - *
  2. - *
  3. - * If a node in the right (target) half of a diagram carries a blue contour it will become the current - * node in the next iteration and there the other nodes will be newly assigned relative to it. Any - * color shown in the diagram is either assumed in its case or implied by those assumptions. - *
  4. - *
  5. - * A numbered triangle represents a subtree of unspecified depth. A black - * circle atop a triangle means that black-height of subtree is greater - * by one compared to subtree without this circle.
  6. - *
- * - *

There are several cases of red-black tree insertion to handle:

- * - *
    - *
  • N is the root node, i.e., first node of red-black tree.
  • - *
  • - * N's parent ({@link XTreeNode.parent P}) is black. - *
  • - *
  • - * N's parent ({@link XTreeNode.parent P}) and uncle - * ({@link XTreeNode.uncle U}) are red. - *
  • - *
  • - * N is added to right of left child of grandparent, or N is added to left - * of right child of grandparent ({@link XTreeNode.parent P} is red and - * {@link XTreeNode.uncle U} is black). - *
  • - *
  • - * N is added to left of left child of grandparent, or N is added to right - * of right child of grandparent ({@link XTreeNode.parent P} is red and - * {@link XTreeNode.uncle U} is black). - *
  • - *
- * - *

Note

- *

Note that inserting is actually in-place, since all the calls above use tail recursion.

- * - *

In the algorithm above, all cases are chained in order, except in insert case 3 where it can recurse - * to case 1 back to the grandparent node: this is the only case where an iterative implementation will - * effectively loop. Because the problem of repair is escalated to the next higher level but one, it takes - * maximally h⁄2 iterations to repair the tree (where h is the height of the tree). Because the probability - * for escalation decreases exponentially with each iteration the average insertion cost is constant.

- * - * @param val An element to insert. - */ - insert(val: T): void; - /** - *

N is the root node, i.e., first node of red-black tree.

- * - *

The current node N is at the {@link root_ root} of the tree.

- * - *

In this case, it is repainted black to satisfy property 2 (the root is - * black). Since this adds one black node to - * every path at once, property 5 (all paths from any given node to its leaf nodes contain the same number - * of black nodes) is not violated.

- * - * @param N A node to be inserted or swapped. - */ - private insert_case1(N); - /** - *

N's parent ({@link XTreeNode.parent P}) is black.

- * - *

The current node's parent {@link XTreeNode.parent P} is black, - * so property 4 (both children of every red node are - * black) is not invalidated.

- * - *

In this case, the tree is still valid. Property 5 (all paths from any given node to its leaf nodes - * contain the same number of black nodes) is not threatened, because the - * current node N has two black leaf children, but because - * N is red, the paths through each of its children have the same - * number of black nodes as the path through the leaf it replaced, which was - * black, and so this property remains satisfied.

- * - * @param N A node to be inserted or swapped. - */ - private insert_case2(N); - /** - *

N's parent ({@link XTreeNode.parent P}) and uncle - * ({@link XTreeNode.uncle U}) are red.

- * - *

If both the parent {@link XTreeNode.parent P} and the uncle {@link XTreeNode.uncle U} - * are red, then both of them can be repainted black - * and the grandparent {@link XTreeNode.grand_parent G} becomes red (to - * maintain property 5 (all paths from any given node to its leaf nodes contain the same number of - * black nodes)).

- * - *

Now, the current red node N has a - * black parent. Since any path through the parent or uncle must pass through - * the grandparent, the number of black nodes on these paths has not changed. - * - *

However, the grandparent {@link XTreeNode.grand_parent G} may now violate properties 2 (The - * root is black) or 4 (Both children of every red - * node are black) (property 4 possibly being violated since - * {@link XTreeNode.grand_parent G} may have a red parent).

- * - *

To fix this, the entire procedure is recursively performed on {@link XTreeNode.grand_parent G} - * from case 1. Note that this is a tail-recursive call, so it could be rewritten as a loop; since this is - * the only loop, and any rotations occur after this loop, this proves that a constant number of rotations - * occur.

- * - *

- * - * @param N A node to be inserted or swapped. - */ - private insert_case3(N); - /** - *

N is added to right of left child of grandparent, or N is added to left - * of right child of grandparent ({@link XTreeNode.parent P} is red and - * {@link XTreeNode.uncle U} is black).

- * - *

The parent {@link XTreeNode.parent P} is red but the uncle - * {@link XTreeNode.uncle U} is black; also, the current node - * N is the right child of {@link XTreeNode.parent P}, and - * {@link XTreeNode.parent P} in turn is the left child of its parent - * {@link XTreeNode.grand_parent G}.

- * - *

In this case, a left rotation on {@link XTreeNode.parent P} that switches the roles of the - * current node N and its parent {@link XTreeNode.parent P} can be performed; then, - * the former parent node {@link XTreeNode.parent P} is dealt with using case 5 - * (relabeling N and {@link XTreeNode.parent P}) because property 4 (both children of - * every red node are black) is still violated.

- * - *

The rotation causes some paths (those in the sub-tree labelled "1") to pass through the node - * N where they did not before. It also causes some paths (those in the sub-tree labelled "3") - * not to pass through the node {@link XTreeNode.parent P} where they did before. However, both of - * these nodes are red, so property 5 (all paths from any given node to its leaf - * nodes contain the same number of black nodes) is not violated by the - * rotation.

- * - *

After this case has been completed, property 4 (both children of every red - * node are black) is still violated, but now we can resolve this by - * continuing to case 5.

- * - *

- * - * @param N A node to be inserted or swapped. - */ - private insert_case4(node); - /** - *

N is added to left of left child of grandparent, or N is added to right - * of right child of grandparent ({@link XTreeNode.parent P} is red and - * {@link XTreeNode.uncle U} is black).

- * - *

The parent {@link XTreeNode.parent P} is red but the uncle - * {@link XTreeNode.uncle U} is black, the current node N - * is the left child of {@link XTreeNode.parent P}, and {@link XTreeNode.parent P} is the left - * child of its parent {@link XTreeNode.grand_parent G}.

- * - *

In this case, a right rotation on {@link XTreeNode.grand_parent G} is performed; the result is a - * tree where the former parent {@link XTreeNode.parent P} is now the parent of both the current node - * N and the former grandparent {@link XTreeNode.grand_parent G}.

- * - *

{@link XTreeNode.grand_parent G} is known to be black, since its - * former child {@link XTreeNode.parent P} could not have been red otherwise - * (without violating property 4). Then, the colors of {@link XTreeNode.parent P} and - * {@link XTreeNode.grand_parent G} are switched, and the resulting tree satisfies property 4 (both - * children of every red node are black). Property 5 - * (all paths from any given node to its leaf nodes contain the same number of - * black nodes) also remains satisfied, since all paths that went through any - * of these three nodes went through {@link XTreeNode.grand_parent G} before, and now they all go - * through {@link XTreeNode.parent P}. In each case, this is the only - * black node of the three.

- * - *

- * - * @param N A node to be inserted or swapped. - */ - private insert_case5(node); - /** - *

Erase an element with its node.

- * - *

In a regular binary search tree when deleting a node with two non-leaf children, we find either the - * maximum element in its left subtree (which is the in-order predecessor) or the minimum element in its - * right subtree (which is the in-order successor) and move its value into the node being deleted (as shown - * here). We then delete the node we copied the value from, which must have fewer than two non-leaf children. - * (Non-leaf children, rather than all children, are specified here because unlike normal binary search - * trees, red-black trees can have leaf nodes anywhere, so that all nodes are either internal nodes with - * two children or leaf nodes with, by definition, zero children. In effect, internal nodes having two leaf - * children in a red-black tree are like the leaf nodes in a regular binary search tree.) Because merely - * copying a value does not violate any red-black properties, this reduces to the problem of deleting a node - * with at most one non-leaf child. Once we have solved that problem, the solution applies equally to the - * case where the node we originally want to delete has at most one non-leaf child as to the case just - * considered where it has two non-leaf children.

- * - *

Therefore, for the remainder of this discussion we address the deletion of a node with at most one - * non-leaf child. We use the label M to denote the node to be deleted; C will denote a - * selected child of M, which we will also call "its child". If M does have a non-leaf child, - * call that its child, C; otherwise, choose either leaf as its child, C.

- * - *

If M is a red node, we simply replace it with its child C, - * which must be black by property 4. (This can only occur when M has - * two leaf children, because if the red node M had a - * black non-leaf child on one side but just a leaf child on the other side, - * then the count of black nodes on both sides would be different, thus the - * tree would violate property 5.) All paths through the deleted node will simply pass through one fewer - * red node, and both the deleted node's parent and child must be - * black, so property 3 (all leaves are black) - * and property 4 (both children of every red node are - * black) still hold.

- * - *

Another simple case is when M is black and C is - * red. Simply removing a black node could break - * Properties 4 (“Both children of every red node are - * black”) and 5 (“All paths from any given node to its leaf nodes contain the - * same number of black nodes”), but if we repaint C - * black, both of these properties are preserved.

- * - *

The complex case is when both M and C are black. (This - * can only occur when deleting a black node which has two leaf children, - * because if the black node M had a black - * non-leaf child on one side but just a leaf child on the other side, then the count of - * black nodes on both sides would be different, thus the tree would have been - * an invalid red-black tree by violation of property 5.) We begin by replacing M with its child - * C. We will relabel this child C (in its new position) N, and its sibling (its - * new parent's other child) {@link XTreeNode.sibling S}. ({@link XTreeNode.sibling S} was - * previously the sibling of M.)

- * - *

In the diagrams below, we will also use {@link XTreeNode.parent P} for N's new - * parent (M's old parent), SL for {@link XTreeNode.sibling S}'s left child, and - * SR for {@link XTreeNode.sibling S}'s right child ({@link XTreeNode.sibling S} cannot - * be a leaf because if M and C were black, then - * {@link XTreeNode.parent P}'s one subtree which included M counted two - * black-height and thus {@link XTreeNode.parent P}'s other subtree - * which includes {@link XTreeNode.sibling S} must also count two - * black-height, which cannot be the case if {@link XTreeNode.sibling S} - * is a leaf node).

- * - *

Notes

- *
    - *
  1. - * The label N will be used to denote the current node (colored - * black). In the diagrams N carries a blue contour. At the - * beginning, this is the replacement node and a leaf, but the entire procedure may also be applied - * recursively to other nodes (see case 3). In between some cases, the roles and labels of the nodes - * are exchanged, but in each case, every label continues to represent the same node it represented at - * the beginning of the case. - *
  2. - *
  3. - * If a node in the right (target) half of a diagram carries a blue contour it will become the current - * node in the next iteration and there the other nodes will be newly assigned relative to it. Any - * color shown in the diagram is either assumed in its case or implied by those assumptions. - * White represents an arbitrary color (either red or - * black), but the same in both halves of the diagram. - *
  4. - *
  5. - * A numbered triangle represents a subtree of unspecified depth. A black - * circle atop a triangle means that black-height of subtree is greater - * by one compared to subtree without this circle. - *
  6. - *
- * - *

If both N and its original parent are black, then - * deleting this original parent causes paths which proceed through N to have one fewer - * black node than paths that do not. As this violates property 5 (all paths - * from any given node to its leaf nodes contain the same number of black - * nodes), the tree must be rebalanced. There are several cases to consider:

- * - *
    - *
  1. N is the new root.
  2. - *
  3. {@link XTreeNode.sibling S} is red.
  4. - *
  5. - * {@link XTreeNode.parent P}, {@link XTreeNode.sibling S}, and - * {@link XTreeNode.sibling S}'s children are black.
  6. - *
  7. - * {@link XTreeNode.sibling S} and {@link XTreeNode.sibling S}'s children are - * black, but {@link XTreeNode.parent P} is - * red. - *
  8. - *
  9. - * {@link XTreeNode.sibling S} is black, - * {@link XTreeNode.sibling S}'s left child is red, - * {@link XTreeNode.sibling S}'s right child is black, and - * N is the left child of its parent. - *
  10. - *
  11. - * {@link XTreeNode.sibling S} is black, - * {@link XTreeNode.sibling S}'s right child is red, and - * N is the left child of its parent {@link XTreeNode.parent P}. - *
  12. - *
- * - *

Again, the function calls all use tail recursion, so the algorithm is in-place.

- * - *

In the algorithm above, all cases are chained in order, except in delete case 3 where it can recurse - * to case 1 back to the parent node: this is the only case where an iterative implementation will - * effectively loop. No more than h loops back to case 1 will occur (where h is the height of the tree). - * And because the probability for escalation decreases exponentially with each iteration the average - * removal cost is constant.

- * - *

Additionally, no tail recursion ever occurs on a child node, so the tail recursion loop can only - * move from a child back to its successive ancestors. If a rotation occurs in case 2 (which is the only - * possibility of rotation within the loop of cases 1–3), then the parent of the node N - * becomes red after the rotation and we will exit the loop. Therefore, at most one - * rotation will occur within this loop. Since no more than two additional rotations will occur after - * exiting the loop, at most three rotations occur in total.

- * - * @param val An element to erase. - */ - erase(val: T): void; - /** - *

N is the new root.

- * - *

In this case, we are done. We removed one black node from every path, - * and the new root is black, so the properties are preserved.

- * - *

Note

- *

In cases 2, 5, and 6, we assume N is the left child of its parent - * {@link XTreeNode.parent P}. If it is the right child, left and right should be reversed throughout - * these three cases. Again, the code examples take both cases into account.

- * - * @param N A node to be erased or swapped. - */ - private erase_case1(N); - /** - *

{@link XTreeNode.sibling S} is red.

- * - *

- * - *

In this case we reverse the colors of {@link XTreeNode.parent P} and - * {@link XTreeNode.sibling S}, and then rotate left at {@link XTreeNode.parent P}, turning - * {@link XTreeNode.sibling S} into N's grandparent.

- * - *

Note that {@link XTreeNode.parent P} has to be black as it had a - * red child. The resulting subtree has a path short one - * black node so we are not done. Now N has a - * black sibling and a red parent, so we can proceed - * to step 4, 5, or 6. (Its new sibling is black because it was once the child - * of the red {@link XTreeNode.sibling S}.) In later cases, we will re-label - * N's new sibling as {@link XTreeNode.sibling S}.

- * - * @param N A node to be erased or swapped. - */ - private erase_case2(N); - /** - *

{@link XTreeNode.parent P}, {@link XTreeNode.sibling S}, and {@link XTreeNode.sibling - * S}'s children are black.

- * - *

- * - *

In this case, we simply repaint {@link XTreeNode.sibling S} red. The - * result is that all paths passing through {@link XTreeNode.sibling S}, which are precisely those - * paths not passing through N, have one less black node. - * Because deleting N's original parent made all paths passing through N have - * one less black node, this evens things up.

- * - *

However, all paths through {@link XTreeNode.parent P} now have one fewer - * black node than paths that do not pass through - * {@link XTreeNode.parent P}, so property 5 (all paths from any given node to its leaf nodes contain - * the same number of black nodes) is still violated.

- * - *

To correct this, we perform the rebalancing procedure on {@link XTreeNode.parent P}, starting - * at case 1.

- * - * @param N A node to be erased or swapped. - */ - private erase_case3(N); - /** - *

{@link XTreeNode.sibling S} and {@link XTreeNode.sibling S}'s children are - * black, but {@link XTreeNode.parent P} is red.

- * - *

- * - *

In this case, we simply exchange the colors of {@link XTreeNode.sibling S} and - * {@link XTreeNode.parent P}. This does not affect the number of black - * nodes on paths going through {@link XTreeNode.sibling S}, but it does add one to the number of - * black nodes on paths going through N, making up for the - * deleted black node on those paths.

- * - * @param N A node to be erased or swapped. - */ - private erase_case4(N); - /** - *

{@link XTreeNode.sibling S} is black, {@link XTreeNode.sibling S}'s - * left child is red, {@link XTreeNode.sibling S}'s right child is - * black, and N is the left child of its parent.

- * - *

- * - *

In this case we rotate right at {@link XTreeNode.sibling S}, so that - * {@link XTreeNode.sibling S}'s left child becomes {@link XTreeNode.sibling S}'s parent and - * N's new sibling. We then exchange the colors of {@link XTreeNode.sibling S} and its - * new parent.

- * - *

All paths still have the same number of black nodes, but now - * N has a black sibling whose right child is - * red, so we fall into case 6. Neither N nor its parent are affected - * by this transformation. (Again, for case 6, we relabel N's new sibling as - * {@link XTreeNode.sibling S}.)

- * - * @param N A node to be erased or swapped. - */ - private erase_case5(N); - /** - *

{@link XTreeNode.sibling S} is black, - * {@link XTreeNode.sibling S}'s right child is red, and N is - * the left child of its parent {@link XTreeNode.parent P}.

- * - *

In this case we rotate left at {@link XTreeNode.parent P}, so that - * {@link XTreeNode.sibling S} becomes the parent of {@link XTreeNode.parent P} and - * {@link XTreeNode.sibling S}'s right child. We then exchange the colors of - * {@link XTreeNode.parent P} and {@link XTreeNode.sibling S}, and make - * {@link XTreeNode.sibling S}'s right child black.

- * - *

The subtree still has the same color at its root, so Properties 4 (Both children of every - * red node are black) and 5 (All paths from any - * given node to its leaf nodes contain the same number of black nodes) are - * not violated. However, N now has one additional black - * ancestor: either {@link XTreeNode.parent P} has become black, or it - * was black and {@link XTreeNode.sibling S} was added as a - * black grandparent.

- * - *

Thus, the paths passing through N pass through one additional - * black node.

- * - *

- * - *

Meanwhile, if a path does not go through N, then there are two possibilities:

- *
    - *
  1. - * It goes through N's new sibling SL, a node with arbitrary color and the root of - * the subtree labeled 3 (s. diagram). Then, it must go through {@link XTreeNode.sibling S} and - * {@link XTreeNode.parent P}, both formerly and currently, as they have only exchanged colors - * and places. Thus the path contains the same number of black nodes. - *
  2. - *
  3. - * It goes through N's new uncle, {@link XTreeNode.sibling S}'s right child. Then, - * it formerly went through {@link XTreeNode.sibling S}, {@link XTreeNode.sibling S}'s - * parent, and {@link XTreeNode.sibling S}'s right child SR (which was - * red), but now only goes through {@link XTreeNode.sibling S}, which - * has assumed the color of its former parent, and {@link XTreeNode.sibling S}'s right child, - * which has changed from red to black (assuming - * {@link XTreeNode.sibling S}'s color: black). The net effect is - * that this path goes through the same number of black nodes. - *
  4. - *
- * - *

Either way, the number of black nodes on these paths does not change. - * Thus, we have restored Properties 4 (Both children of every red node are - * black) and 5 (All paths from any given node to its leaf nodes contain the - * same number of black nodes). The white node in the diagram can be either - * red or black, but must refer to the same color - * both before and after the transformation.

- * - * @param N A node to be erased or swapped. - */ - private erase_case6(node); - /** - * Rotate a node left. - * - * @param node Node to rotate left. - */ - protected rotate_left(node: XTreeNode): void; - /** - * Rotate a node to right. - * - * @param node A node to rotate right. - */ - protected rotate_right(node: XTreeNode): void; - /** - * Replace a node. - * - * @param oldNode Ordinary node to be replaced. - * @param newNode Target node to replace. - */ - protected replace_node(oldNode: XTreeNode, newNode: XTreeNode): void; - /** - * Fetch color from a node. - * - * @param node A node to fetch color. - * @retur color. - */ - private fetch_color(node); - } -} -declare namespace std.base { - /** - *

Common interface for tree-structured map.

- * - *

{@link ITreeMap ITreeMaps} are associative containers that store elements formed by a combination of - * a key value and a mapped value, following a specific order.

- * - *

In a {@link ITreeMap}, the key values are generally used to sort and uniquely identify - * the elements, while the mapped values store the content associated to this key. The types of - * key and mapped value may differ, and are grouped together in member type - * value_type, which is a {@link Pair} type combining both:

- * - *

typedef Pair value_type;

- * - *

Internally, the elements in a {@link ITreeMap}are always sorted by its key following a - * strict weak ordering criterion indicated by its internal comparison method (of {@link less}).

- * - *

{@link ITreeMap}containers are generally slower than {@link IHashMap} containers - * to access individual elements by their key, but they allow the direct iteration on subsets based - * on their order.

- * - *

{@link ITreeMap TreeMultiMaps} are typically implemented as binary search trees.

- * - *

- *

- * - *

Container properties

- *
- *
Associative
- *
Elements in associative containers are referenced by their key and not by their absolute - * position in the container.
- * - *
Ordered
- *
The elements in the container follow a strict order at all times. All inserted elements are - * given a position in this order.
- * - *
Map
- *
Each element associates a key to a mapped value: - * Keys are meant to identify the elements whose main content is the mapped value.
- *
- * - * @param Type of the keys. Each element in a map is uniquely identified by its key value. - * @param Type of the mapped value. Each element in a map stores some data as its mapped value. - * - * @reference http://www.cplusplus.com/reference/map - * @author Jeongho Nam - */ - interface ITreeMap { - /** - *

Return key comparison function.

- * - *

Returns a references of the comparison function used by the container to compare keys.

- * - *

The comparison object of a {@link ITreeMap tree-map object} is set on - * {@link TreeMap.constructor construction}. Its type (Key) is the last parameter of the - * {@link ITreeMap.constructor constructors}. By default, this is a {@link less} function, which returns the same - * as operator<.

- * - *

This function determines the order of the elements in the container: it is a function pointer that takes - * two arguments of the same type as the element keys, and returns true if the first argument - * is considered to go before the second in the strict weak ordering it defines, and false otherwise. - *

- * - *

Two keys are considered equivalent if {@link key_comp} returns false reflexively (i.e., no - * matter the order in which the keys are passed as arguments).

- * - * @return The comparison function. - */ - key_comp(): (x: Key, y: Key) => boolean; - /** - *

Return value comparison function.

- * - *

Returns a comparison function that can be used to compare two elements to get whether the key of the first - * one goes before the second.

- * - *

The arguments taken by this function object are of member type std.Pair (defined in - * {@link ITreeMap}), but the mapped type (T) part of the value is not taken into consideration in this - * comparison.

- * - *

This comparison class returns true if the {@link Pair.first key} of the first argument - * is considered to go before that of the second (according to the strict weak ordering specified by the - * container's comparison function, {@link key_comp}), and false otherwise.

- * - * @return The comparison function for element values. - */ - value_comp(): (x: Pair, y: Pair) => boolean; - /** - *

Return iterator to lower bound.

- * - *

Returns an iterator pointing to the first element in the container whose key is not considered to - * go before k (i.e., either it is equivalent or goes after).

- * - *

The function uses its internal comparison object (key_comp) to determine this, returning an - * iterator to the first element for which key_comp(k, element_key) would return false.

- * - *

If the {@link ITreeMap} class is instantiated with the default comparison type ({@link less}), - * the function returns an iterator to the first element whose key is not less than k

. - * - *

A similar member function, {@link upper_bound}, has the same behavior as {@link lower_bound}, except - * in the case that the {@link ITreeMap} contains an element with a key equivalent to k: In this - * case, {@link lower_bound} returns an iterator pointing to that element, whereas {@link upper_bound} - * returns an iterator pointing to the next element.

- * - * @param k Key to search for. - * - * @return An iterator to the the first element in the container whose key is not considered to go before - * k, or {@link ITreeMap.end} if all keys are considered to go before k. - */ - lower_bound(key: Key): MapIterator; - /** - *

Return iterator to upper bound.

- * - *

Returns an iterator pointing to the first element in the container whose key is considered to - * go after k

. - * - *

The function uses its internal comparison object (key_comp) to determine this, returning an - * iterator to the first element for which key_comp(k, element_key) would return true.

- * - *

If the {@link ITreeMap} class is instantiated with the default comparison type ({@link less}), - * the function returns an iterator to the first element whose key is greater than k

. - * - *

A similar member function, {@link lower_bound}, has the same behavior as {@link upper_bound}, except - * in the case that the map contains an element with a key equivalent to k: In this case - * {@link lower_bound} returns an iterator pointing to that element, whereas {@link upper_bound} returns an - * iterator pointing to the next element.

- * - * @param k Key to search for. - * - * @return An iterator to the the first element in the container whose key is considered to go after - * k, or {@link TreeMap.end end} if no keys are considered to go after k. - */ - upper_bound(key: Key): MapIterator; - /** - *

Get range of equal elements.

- * - *

Returns the bounds of a range that includes all the elements in the container which have a key - * equivalent to k

. - * - *

If no matches are found, the range returned has a length of zero, with both iterators pointing to - * the first element that has a key considered to go after k according to the container's internal - * comparison object (key_comp).

- * - *

Two keys are considered equivalent if the container's comparison object returns false reflexively - * (i.e., no matter the order in which the keys are passed as arguments).

- * - * @param k Key to search for. - * - * @return The function returns a {@link Pair}, whose member {@link Pair.first} is the lower bound of - * the range (the same as {@link lower_bound}), and {@link Pair.second} is the upper bound - * (the same as {@link upper_bound}). - */ - equal_range(key: Key): Pair, MapIterator>; - } -} -declare namespace std.base { - /** - *

A red-black tree storing {@link MapIterator MapIterators}.

- * - *

- *

- * - * @author Jeongho Nam - */ - class PairTree extends XTree> { - /** - * @hidden - */ - private map_; - /** - * @hidden - */ - private compare_; - /** - * Default Constructor. - */ - constructor(map: TreeMap | TreeMultiMap, compare?: (x: Key, y: Key) => boolean); - find(key: Key): XTreeNode>; - find(it: MapIterator): XTreeNode>; - /** - * @hidden - */ - private find_by_key(key); - /** - *

Return iterator to lower bound.

- * - *

Returns an iterator pointing to the first element in the container whose key is not considered to - * go before k (i.e., either it is equivalent or goes after).

- * - *

The function uses its internal comparison object (key_comp) to determine this, returning an - * iterator to the first element for which key_comp(k, element_key) would return false.

- * - *

If the {@link ITreeMap} class is instantiated with the default comparison type ({@link less}), - * the function returns an iterator to the first element whose key is not less than k

. - * - *

A similar member function, {@link upper_bound}, has the same behavior as {@link lower_bound}, except - * in the case that the {@link ITreeMap} contains an element with a key equivalent to k: In this - * case, {@link lower_bound} returns an iterator pointing to that element, whereas {@link upper_bound} - * returns an iterator pointing to the next element.

- * - * @param k Key to search for. - * - * @return An iterator to the the first element in the container whose key is not considered to go before - * k, or {@link ITreeMap.end} if all keys are considered to go before k. - */ - lower_bound(key: Key): MapIterator; - /** - *

Return iterator to upper bound.

- * - *

Returns an iterator pointing to the first element in the container whose key is considered to - * go after k

. - * - *

The function uses its internal comparison object (key_comp) to determine this, returning an - * iterator to the first element for which key_comp(k, element_key) would return true.

- * - *

If the {@link ITreeMap} class is instantiated with the default comparison type ({@link less}), - * the function returns an iterator to the first element whose key is greater than k

. - * - *

A similar member function, {@link lower_bound}, has the same behavior as {@link upper_bound}, except - * in the case that the map contains an element with a key equivalent to k: In this case - * {@link lower_bound} returns an iterator pointing to that element, whereas {@link upper_bound} returns an - * iterator pointing to the next element.

- * - * @param k Key to search for. - * - * @return An iterator to the the first element in the container whose key is considered to go after - * k, or {@link TreeMap.end end} if no keys are considered to go after k. - */ - upper_bound(key: Key): MapIterator; - /** - *

Get range of equal elements.

- * - *

Returns the bounds of a range that includes all the elements in the container which have a key - * equivalent to k

. - * - *

If no matches are found, the range returned has a length of zero, with both iterators pointing to - * the first element that has a key considered to go after k according to the container's internal - * comparison object (key_comp).

- * - *

Two keys are considered equivalent if the container's comparison object returns false reflexively - * (i.e., no matter the order in which the keys are passed as arguments).

- * - * @param k Key to search for. - * - * @return The function returns a {@link Pair}, whose member {@link Pair.first} is the lower bound of - * the range (the same as {@link lower_bound}), and {@link Pair.second} is the upper bound - * (the same as {@link upper_bound}). - */ - equal_range(key: Key): Pair, MapIterator>; - /** - *

Return key comparison function.

- * - *

Returns a references of the comparison function used by the container to compare keys.

- * - *

The comparison object of a {@link ITreeMap tree-map object} is set on - * {@link TreeMap.constructor construction}. Its type (Key) is the last parameter of the - * {@link ITreeMap.constructor constructors}. By default, this is a {@link less} function, which returns the same - * as operator<.

- * - *

This function determines the order of the elements in the container: it is a function pointer that takes - * two arguments of the same type as the element keys, and returns true if the first argument - * is considered to go before the second in the strict weak ordering it defines, and false otherwise. - *

- * - *

Two keys are considered equivalent if {@link key_comp} returns false reflexively (i.e., no - * matter the order in which the keys are passed as arguments).

- * - * @return The comparison function. - */ - key_comp(): (x: Key, y: Key) => boolean; - /** - *

Return value comparison function.

- * - *

Returns a comparison function that can be used to compare two elements to get whether the key of the first - * one goes before the second.

- * - *

The arguments taken by this function object are of member type std.Pair (defined in - * {@link ITreeMap}), but the mapped type (T) part of the value is not taken into consideration in this - * comparison.

- * - *

This comparison class returns true if the {@link Pair.first key} of the first argument - * is considered to go before that of the second (according to the strict weak ordering specified by the - * container's comparison function, {@link key_comp}), and false otherwise.

- * - * @return The comparison function for element values. - */ - value_comp(): (x: Pair, y: Pair) => boolean; - /** - * @inheritdoc - */ - is_equal_to(left: MapIterator, right: MapIterator): boolean; - /** - * @inheritdoc - */ - is_less(left: MapIterator, right: MapIterator): boolean; - } -} -declare namespace std.base { - /** - *

A common interface for tree-structured set.

- * - *

{@link ITreeSet TreeMultiSets} are containers that store elements following a specific order.

- * - *

In a {@link ITreeSet}, the value of an element also identifies it (the value is itself - * the key, of type T). The value of the elements in a {@link ITreeSet} cannot - * be modified once in the container (the elements are always const), but they can be inserted or removed - * from the

- * - *

Internally, the elements in a {@link ITreeSet TreeMultiSets} are always sorted following a strict - * weak ordering criterion indicated by its internal comparison method (of {@link IComparable.less less}).

- * - *

{@link ITreeSet} containers are generally slower than {@link IHashSet} containers - * to access individual elements by their key, but they allow the direct iteration on subsets based on - * their order.

- * - *

{@link ITreeSet TreeMultiSets} are typically implemented as binary search trees.

- * - *

- *

- * - *

Container properties

- *
- *
Associative
- *
- * Elements in associative containers are referenced by their key and not by their absolute - * position in the container. - *
- * - *
Ordered
- *
- * The elements in the container follow a strict order at all times. All inserted elements are - * given a position in this order. - *
- * - *
Set
- *
The value of an element is also the key used to identify it.
- *
- * - * @param Type of the elements. Each element in a {@link ITreeSet} container is also identified - * by this value (each value is itself also the element's key). - * - * @reference http://www.cplusplus.com/reference/set - * @author Jeongho Nam - */ - interface ITreeSet { - /** - *

Return comparison function.

- * - *

Returns a copy of the comparison function used by the container.

- * - *

By default, this is a {@link less} object, which returns the same as operator<.

- * - *

This object determines the order of the elements in the container: it is a function pointer or a function - * object that takes two arguments of the same type as the container elements, and returns true if - * the first argument is considered to go before the second in the strict weak ordering it - * defines, and false otherwise.

- * - *

Two elements of a {@link ITreeSet} are considered equivalent if {@link key_comp} returns false - * reflexively (i.e., no matter the order in which the elements are passed as arguments).

- * - *

In {@link ITreeSet} containers, the keys to sort the elements are the values (T) themselves, - * therefore {@link key_comp} and its sibling member function {@link value_comp} are equivalent.

- * - * @return The comparison function. - */ - key_comp(): (x: T, y: T) => boolean; - /** - *

Return comparison function.

- * - *

Returns a copy of the comparison function used by the container.

- * - *

By default, this is a {@link less} object, which returns the same as operator<.

- * - *

This object determines the order of the elements in the container: it is a function pointer or a function - * object that takes two arguments of the same type as the container elements, and returns true if - * the first argument is considered to go before the second in the strict weak ordering it - * defines, and false otherwise.

- * - *

Two elements of a {@link ITreeSet} are considered equivalent if {@link key_comp} returns false - * reflexively (i.e., no matter the order in which the elements are passed as arguments).

- * - *

In {@link ITreeSet} containers, the keys to sort the elements are the values (T) themselves, - * therefore {@link key_comp} and its sibling member function {@link value_comp} are equivalent.

- * - * @return The comparison function. - */ - value_comp(): (x: T, y: T) => boolean; - /** - *

Return iterator to lower bound.

- * - *

Returns an iterator pointing to the first element in the container which is not considered to - * go before val (i.e., either it is equivalent or goes after).

- * - *

The function uses its internal comparison object (key_comp) to determine this, returning an - * iterator to the first element for which key_comp(element,val) would return false.

- * - *

If the {@link ITreeSet} class is instantiated with the default comparison type ({@link less}), - * the function returns an iterator to the first element that is not less than val.

- - *

A similar member function, {@link upper_bound}, has the same behavior as {@link lower_bound}, except - * in the case that the {@link ITreeSet} contains elements equivalent to val: In this case - * {@link lower_bound} returns an iterator pointing to the first of such elements, whereas - * {@link upper_bound} returns an iterator pointing to the element following the last.

- * - * @param val Value to compare. - * - * @return An iterator to the the first element in the container which is not considered to go before - * val, or {@link ITreeSet.end} if all elements are considered to go before val. - */ - lower_bound(val: T): SetIterator; - /** - *

Return iterator to upper bound.

- * - *

Returns an iterator pointing to the first element in the container which is considered to go after - * val.

- - *

The function uses its internal comparison object (key_comp) to determine this, returning an - * iterator to the first element for which key_comp(val,element) would return true.

- - *

If the {@code ITreeSet} class is instantiated with the default comparison type (less), the - * function returns an iterator to the first element that is greater than val.

- * - *

A similar member function, {@link lower_bound}, has the same behavior as {@link upper_bound}, except - * in the case that the {@ITreeSet} contains elements equivalent to val: In this case - * {@link lower_bound} returns an iterator pointing to the first of such elements, whereas - * {@link upper_bound} returns an iterator pointing to the element following the last.

- * - * @param val Value to compare. - * - * @return An iterator to the the first element in the container which is considered to go after - * val, or {@link TreeSet.end end} if no elements are considered to go after val. - */ - upper_bound(val: T): SetIterator; - /** - *

Get range of equal elements.

- * - *

Returns the bounds of a range that includes all the elements in the container that are equivalent - * to val.

- * - *

If no matches are found, the range returned has a length of zero, with both iterators pointing to - * the first element that is considered to go after val according to the container's - * internal comparison object (key_comp).

- * - *

Two elements of a multiset are considered equivalent if the container's comparison object returns - * false reflexively (i.e., no matter the order in which the elements are passed as arguments).

- * - * @param key Value to search for. - * - * @return The function returns a {@link Pair}, whose member {@link Pair.first} is the lower bound of - * the range (the same as {@link lower_bound}), and {@link Pair.second} is the upper bound - * (the same as {@link upper_bound}). - */ - equal_range(val: T): Pair, SetIterator>; - } -} -declare namespace std.base { - /** - *

A red-black Tree storing {@link SetIterator SetIterators}.

- * - *

- *

- * - * @author Jeongho Nam - */ - class AtomicTree extends XTree> { - /** - * @hidden - */ - private set_; - /** - * @hidden - */ - private compare_; - /** - * Default Constructor. - */ - constructor(set: TreeSet | TreeMultiSet, compare?: (x: T, y: T) => boolean); - find(val: T): XTreeNode>; - find(it: SetIterator): XTreeNode>; - /** - * @hidden - */ - private find_by_val(val); - /** - *

Return iterator to lower bound.

- * - *

Returns an iterator pointing to the first element in the container which is not considered to - * go before val (i.e., either it is equivalent or goes after).

- * - *

The function uses its internal comparison object (key_comp) to determine this, returning an - * iterator to the first element for which key_comp(element,val) would return false.

- * - *

If the {@link ITreeSet} class is instantiated with the default comparison type ({@link less}), - * the function returns an iterator to the first element that is not less than val.

- - *

A similar member function, {@link upper_bound}, has the same behavior as {@link lower_bound}, except - * in the case that the {@link ITreeSet} contains elements equivalent to val: In this case - * {@link lower_bound} returns an iterator pointing to the first of such elements, whereas - * {@link upper_bound} returns an iterator pointing to the element following the last.

- * - * @param val Value to compare. - * - * @return An iterator to the the first element in the container which is not considered to go before - * val, or {@link ITreeSet.end} if all elements are considered to go before val. - */ - lower_bound(val: T): SetIterator; - /** - *

Return iterator to upper bound.

- * - *

Returns an iterator pointing to the first element in the container which is considered to go after - * val.

- - *

The function uses its internal comparison object (key_comp) to determine this, returning an - * iterator to the first element for which key_comp(val,element) would return true.

- - *

If the {@code ITreeSet} class is instantiated with the default comparison type (less), the - * function returns an iterator to the first element that is greater than val.

- * - *

A similar member function, {@link lower_bound}, has the same behavior as {@link upper_bound}, except - * in the case that the {@ITreeSet} contains elements equivalent to val: In this case - * {@link lower_bound} returns an iterator pointing to the first of such elements, whereas - * {@link upper_bound} returns an iterator pointing to the element following the last.

- * - * @param val Value to compare. - * - * @return An iterator to the the first element in the container which is considered to go after - * val, or {@link TreeSet.end end} if no elements are considered to go after val. - */ - upper_bound(val: T): SetIterator; - /** - *

Get range of equal elements.

- * - *

Returns the bounds of a range that includes all the elements in the container that are equivalent - * to val.

- * - *

If no matches are found, the range returned has a length of zero, with both iterators pointing to - * the first element that is considered to go after val according to the container's - * internal comparison object (key_comp).

- * - *

Two elements of a multiset are considered equivalent if the container's comparison object returns - * false reflexively (i.e., no matter the order in which the elements are passed as arguments).

- * - * @param key Value to search for. - * - * @return The function returns a {@link Pair}, whose member {@link Pair.first} is the lower bound of - * the range (the same as {@link lower_bound}), and {@link Pair.second} is the upper bound - * (the same as {@link upper_bound}). - */ - equal_range(val: T): Pair, SetIterator>; - /** - *

Return comparison function.

- * - *

Returns a copy of the comparison function used by the container.

- * - *

By default, this is a {@link less} object, which returns the same as operator<.

- * - *

This object determines the order of the elements in the container: it is a function pointer or a function - * object that takes two arguments of the same type as the container elements, and returns true if - * the first argument is considered to go before the second in the strict weak ordering it - * defines, and false otherwise.

- * - *

Two elements of a {@link ITreeSet} are considered equivalent if {@link key_comp} returns false - * reflexively (i.e., no matter the order in which the elements are passed as arguments).

- * - *

In {@link ITreeSet} containers, the keys to sort the elements are the values (T) themselves, - * therefore {@link key_comp} and its sibling member function {@link value_comp} are equivalent.

- * - * @return The comparison function. - */ - key_comp(): (x: T, y: T) => boolean; - /** - *

Return comparison function.

- * - *

Returns a copy of the comparison function used by the container.

- * - *

By default, this is a {@link less} object, which returns the same as operator<.

- * - *

This object determines the order of the elements in the container: it is a function pointer or a function - * object that takes two arguments of the same type as the container elements, and returns true if - * the first argument is considered to go before the second in the strict weak ordering it - * defines, and false otherwise.

- * - *

Two elements of a {@link ITreeSet} are considered equivalent if {@link key_comp} returns false - * reflexively (i.e., no matter the order in which the elements are passed as arguments).

- * - *

In {@link ITreeSet} containers, the keys to sort the elements are the values (T) themselves, - * therefore {@link key_comp} and its sibling member function {@link value_comp} are equivalent.

- * - * @return The comparison function. - */ - value_comp(): (x: T, y: T) => boolean; - /** - * @inheritdoc - */ - is_equal_to(left: SetIterator, right: SetIterator): boolean; - /** - * @inheritdoc - */ - is_less(left: SetIterator, right: SetIterator): boolean; - } -} -declare namespace std.base { - /** - *

An abstract unique-map.

- * - *

{@link UniqueMap UniqueMaps} are associative containers that store elements formed by a combination of a - * key value (Key) and a mapped value (T), and which allows for fast retrieval of - * individual elements based on their keys.

- * - *

In a {@link MapContainer}, the key values are generally used to uniquely identify the elements, - * while the mapped values store the content associated to this key. The types of key and - * mapped value may differ, and are grouped together in member type value_type, which is a - * {@link Pair} type combining both:

- * - *

typedef pair value_type;

- * - *

{@link UniqueMap} stores elements, keeps sequence and enables indexing by inserting elements into a - * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index - * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

- * - *

- *

- * - *

Container properties

- *
- *
Associative
- *
- * Elements in associative containers are referenced by their key and not by their absolute position - * in the container. - *
- * - *
Map
- *
- * Each element associates a key to a mapped value: - * Keys are meant to identify the elements whose main content is the mapped value. - *
- * - *
Unique keys
- *
No two elements in the container can have equivalent keys.
- *
- * - * @param Type of the keys. Each element in a map is uniquely identified by its key value. - * @param Type of the mapped value. Each element in a map stores some data as its mapped value. - * - * @author Jeongho Nam - */ - abstract class UniqueMap extends MapContainer { - /** - * @inheritdoc - */ - count(key: Key): number; - /** - *

Get an element

- * - *

Returns a reference to the mapped value of the element identified with key.

- * - * @param key Key value of the element whose mapped value is accessed. - * - * @throw exception out of range - * - * @return A reference object of the mapped value (_Ty) - */ - get(key: Key): T; - /** - *

Set an item as the specified identifier.

- * - *

If the identifier is already in map, change value of the identifier. If not, then insert the object - * with the identifier.

- * - * @param key Key value of the element whose mapped value is accessed. - * @param val Value, the item. - */ - set(key: Key, val: T): void; - /** - * Construct and insert element. - * - * Inserts a new element in the {@link UniqueMap} if its *key* is unique. This new element is constructed in - * place using args as the arguments for the construction of a *value_type* (which is an object of a - * {@link Pair} type). - * - * The insertion only takes place if no other element in the container has a *key equivalent* to the one - * being emplaced (*keys* in a {@link UniqueMap} container are unique). - * - * If inserted, this effectively increases the container {@link size} by one. - * - * A similar member function exists, {@link insert}, which either copies or moves existing objects into the - * container. - * - * @param key The key used both to look up and to insert if not found. - * @param value Value, the item. - * - * @return If the function successfully inserts the element (because no equivalent element existed already in - * the {@link UniqueMap}), the function returns a {@link Pair} of an {@link MapIterator iterator} to - * the newly inserted element and a value of true. Otherwise, it returns an - * {@link MapIterator iterator} to the equivalent element within the container and a value of false. - */ - emplace(key: Key, value: T): Pair, boolean>; - /** - * Construct and insert element. - * - * Inserts a new element in the {@link UniqueMap} if its *key* is unique. This new element is constructed in - * place using args as the arguments for the construction of a *value_type* (which is an object of a - * {@link Pair} type). - * - * The insertion only takes place if no other element in the container has a *key equivalent* to the one - * being emplaced (*keys* in a {@link UniqueMap} container are unique). - * - * If inserted, this effectively increases the container {@link size} by one. - * - * A similar member function exists, {@link insert}, which either copies or moves existing objects into the - * container. - * - * @param pair A single argument of a {@link Pair} type with a value for the *key* as - * {@link Pair.first first} member, and a *value* for the mapped value as - * {@link Pair.second second}. - * - * @return If the function successfully inserts the element (because no equivalent element existed already in - * the {@link UniqueMap}), the function returns a {@link Pair} of an {@link MapIterator iterator} to - * the newly inserted element and a value of true. Otherwise, it returns an - * {@link MapIterator iterator} to the equivalent element within the container and a value of false. - */ - emplace(pair: Pair): Pair, boolean>; - /** - *

Insert an element.

- * - *

Extends the container by inserting new elements, effectively increasing the container {@link size} by - * one.

- * - *

Because element keys in a {@link UniqueMap} are unique, the insertion operation checks whether - * each inserted element has a key equivalent to the one of an element already in the container, and - * if so, the element is not inserted, returning an iterator to this existing element (if the function - * returns a value).

- * - *

For a similar container allowing for duplicate elements, see {@link MultiMap}.

- * - * @param pair A single argument of a {@link Pair} type with a value for the *key* as - * {@link Pair.first first} member, and a *value* for the mapped value as - * {@link Pair.second second}. - * - * @return A {@link Pair}, with its member {@link Pair.first} set to an iterator pointing to either the newly - * inserted element or to the element with an equivalent key in the {@link UniqueMap}. The - * {@link Pair.second} element in the {@link Pair} is set to true if a new element was inserted or - * false if an equivalent key already existed. - */ - insert(pair: Pair): Pair, boolean>; - /** - *

Insert an element.

- * - *

Extends the container by inserting a new element, effectively increasing the container size by the - * number of elements inserted.

- * - *

Because element keys in a {@link UniqueMap} are unique, the insertion operation checks whether - * each inserted element has a key equivalent to the one of an element already in the container, and - * if so, the element is not inserted, returning an iterator to this existing element (if the function - * returns a value).

- * - *

For a similar container allowing for duplicate elements, see {@link MultiMap}.

- * - * @param tuple Tuple represensts the {@link Pair} to be inserted as an element. - * - * @return A {@link Pair}, with its member {@link Pair.first} set to an iterator pointing to either the newly - * inserted element or to the element with an equivalent key in the {@link UniqueMap}. The - * {@link Pair.second} element in the {@link Pair} is set to true if a new element was inserted or - * false if an equivalent key already existed. - */ - insert(tuple: [L, U]): Pair, boolean>; - /** - * @inheritdoc - */ - insert(hint: MapIterator, pair: Pair): MapIterator; - /** - * @inheritdoc - */ - insert(hint: MapReverseIterator, pair: Pair): MapReverseIterator; - /** - * @inheritdoc - */ - insert(hint: MapIterator, tuple: [L, U]): MapIterator; - /** - * @inheritdoc - */ - insert(hint: MapReverseIterator, tuple: [L, U]): MapReverseIterator; - /** - * @inheritdoc - */ - insert>>(first: InputIterator, last: InputIterator): void; - /** - *

Insert or assign an element.

- * - *

Inserts an element or assigns to the current element if the key already exists.

- * - *

Because element keys in a {@link UniqueMap} are unique, the insertion operation checks whether - * each inserted element has a key equivalent to the one of an element already in the container, and - * if so, the element is assigned, returning an iterator to this existing element (if the function returns a - * value).

- * - *

For a similar container allowing for duplicate elements, see {@link MultiMap}.

- * - * @param key The key used both to look up and to insert if not found. - * @param value Value, the item. - * - * @return A {@link Pair}, with its member {@link Pair.first} set to an iterator pointing to either the newly - * inserted element or to the element with an equivalent key in the {@link UniqueMap}. The - * {@link Pair.second} element in the {@link Pair} is set to true if a new element was inserted or - * false if an equivalent key already existed so the value is assigned. - */ - insert_or_assign(key: Key, value: T): Pair, boolean>; - /** - *

Insert or assign an element.

- * - *

Inserts an element or assigns to the current element if the key already exists.

- * - *

Because element keys in a {@link UniqueMap} are unique, the insertion operation checks whether - * each inserted element has a key equivalent to the one of an element already in the container, and - * if so, the element is assigned, returning an iterator to this existing element (if the function returns a - * value).

- * - *

For a similar container allowing for duplicate elements, see {@link MultiMap}.

- * - * @param hint Hint for the position where the element can be inserted. - * @param key The key used both to look up and to insert if not found. - * @param value Value, the item. - * - * @return An iterator pointing to either the newly inserted element or to the element that already had an - * equivalent key in the {@link UniqueMap}. - */ - insert_or_assign(hint: MapIterator, key: Key, value: T): MapIterator; - /** - *

Insert or assign an element.

- * - *

Inserts an element or assigns to the current element if the key already exists.

- * - *

Because element keys in a {@link UniqueMap} are unique, the insertion operation checks whether - * each inserted element has a key equivalent to the one of an element already in the container, and - * if so, the element is assigned, returning an iterator to this existing element (if the function returns a - * value).

- * - *

For a similar container allowing for duplicate elements, see {@link MultiMap}.

- * - * @param hint Hint for the position where the element can be inserted. - * @param key The key used both to look up and to insert if not found. - * @param value Value, the item. - * - * @return An iterator pointing to either the newly inserted element or to the element that already had an - * equivalent key in the {@link UniqueMap}. - */ - insert_or_assign(hint: MapReverseIterator, key: Key, value: T): MapReverseIterator; - /** - * @hidden - */ - private insert_or_assign_with_key_value(key, value); - /** - * @hidden - */ - private insert_or_assign_with_hint(hint, key, value); - /** - *

Extract an element.

- * - *

Extracts the element pointed to by key and erases it from the {@link UniqueMap}.

- * - * @param key Key value of the element whose mapped value is accessed. - * - * @return A {@link Pair} containing the value pointed to by key. - */ - extract(key: Key): Pair; - /** - *

Extract an element.

- * - *

Extracts the element pointed to by key and erases it from the {@link UniqueMap}.

- * - * @param it An iterator pointing an element to extract. - * - * @return An iterator pointing to the element immediately following it prior to the element being - * erased. If no such element exists,returns {@link end end()}. - */ - extract(it: MapIterator): MapIterator; - /** - *

Extract an element.

- * - *

Extracts the element pointed to by key and erases it from the {@link UniqueMap}.

- * - * @param it An iterator pointing an element to extract. - * - * @return An iterator pointing to the element immediately following it prior to the element being - * erased. If no such element exists,returns {@link end end()}. - */ - extract(it: MapReverseIterator): MapReverseIterator; - /** - * @hidden - */ - private extract_by_key(key); - /** - * @hidden - */ - private extract_by_iterator(it); - /** - * @hidden - */ - private extract_by_reverse_iterator(it); - /** - * Merge two maps. - * - * Attempts to extract each element in *source* and insert it into this container. If there's an element in this - * container with key equivalent to the key of an element from *source*, tnen that element is not extracted from - * the *source*. Otherwise, no element with same key exists in this container, then that element will be - * transfered from the *source* to this container. - * - * @param source A {@link MapContainer map container} to transfer the elements from. - */ - merge(source: MapContainer): void; - } -} -declare namespace std.base { - /** - *

An abstract set.

- * - *

{@link SetContainer SetContainers} are containers that store elements allowing fast retrieval of - * individual elements based on their value.

- * - *

In an {@link SetContainer}, the value of an element is at the same time its key, used to uniquely - * identify it. Keys are immutable, therefore, the elements in an {@link SetContainer} cannot be modified - * once in the container - they can be inserted and removed, though.

- * - *

{@link SetContainer} stores elements, keeps sequence and enables indexing by inserting elements into a - * {@link List} and registering {@link ListIterator iterators} of the {@link data_ list container} to an index - * table like {@link RBTree tree} or {@link HashBuckets hash-table}.

- * - *

- *

- * - *

Container properties

- *
- *
Associative
- *
- * Elements in associative containers are referenced by their key and not by their absolute - * position in the container. - *
- * - *
Set
- *
The value of an element is also the key used to identify it.
- * - *
Unique keys
- *
No two elements in the container can have equivalent keys.
- *
- * - * @param Type of the elements. Each element in a {@link SetContainer} container is also identified - * by this value (each value is itself also the element's key). - * - * @author Jeongho Nam - */ - abstract class UniqueSet extends SetContainer { - /** - * @inheritdoc - */ - count(key: T): number; - /** - *

Insert an element.

- * - *

Extends the container by inserting new elements, effectively increasing the container {@link size} by - * the number of element inserted (zero or one).

- * - *

Because elements in a {@link UniqueSet UniqueSets} are unique, the insertion operation checks whether - * each inserted element is equivalent to an element already in the container, and if so, the element is not - * inserted, returning an iterator to this existing element (if the function returns a value).

- * - *

For a similar container allowing for duplicate elements, see {@link MultiSet}.

- * - * @param key Value to be inserted as an element. - * - * @return A {@link Pair}, with its member {@link Pair.first} set to an iterator pointing to either the newly - * inserted element or to the equivalent element already in the {@link UniqueSet}. The - * {@link Pair.second} element in the {@link Pair} is set to true if a new element was inserted or - * false if an equivalent element already existed. - */ - insert(val: T): Pair, boolean>; - /** - * @inheritdoc - */ - insert(hint: SetIterator, val: T): SetIterator; - /** - * @inheritdoc - */ - insert(hint: SetReverseIterator, val: T): SetReverseIterator; - /** - * @inheritdoc - */ - insert>(begin: InputIterator, end: InputIterator): void; - /** - *

Extract an element.

- * - *

Extracts the element pointed to by val and erases it from the {@link UniqueSet}.

- * - * @param val Value to be extracted. - * - * @return A value. - */ - extract(val: T): T; - /** - *

Extract an element.

- * - *

Extracts the element pointed to by key and erases it from the {@link UniqueMap}.

- * - * @param it An iterator pointing an element to extract. - * - * @return An iterator pointing to the element immediately following it prior to the element being - * erased. If no such element exists,returns {@link end end()}. - */ - extract(it: SetIterator): SetIterator; - /** - *

Extract an element.

- * - *

Extracts the element pointed to by key and erases it from the {@link UniqueMap}.

- * - * @param it An iterator pointing an element to extract. - * - * @return An iterator pointing to the element immediately following it prior to the element being - * erased. If no such element exists,returns {@link end end()}. - */ - extract(it: SetReverseIterator): SetReverseIterator; - /** - * @hidden - */ - private extract_by_key(val); - /** - * @hidden - */ - private extract_by_iterator(it); - /** - * @hidden - */ - private extract_by_reverse_iterator(it); - /** - * Merge two sets. - * - * Attempts to extract each element in *source* and insert it into this container. If there's an element in this - * container with key equivalent to the key of an element from *source*, tnen that element is not extracted from - * the *source*. Otherwise, no element with same key exists in this container, then that element will be - * transfered from the *source* to this container. - * - * @param source A {@link SetContainer set container} to transfer the elements from. - */ - merge(source: SetContainer): void; - } -} -declare namespace std.base { - /** - *

A node in an XTree.

- * - * @param Type of elements. - * - * @inventor Rudolf Bayer - * @author Migrated by Jeongho Nam - */ - class XTreeNode { - /** - * Parent of the node. - */ - parent: XTreeNode; - /** - * Left child in the node. - */ - left: XTreeNode; - /** - * Right child in the node. - */ - right: XTreeNode; - /** - * Value stored in the node. - */ - value: T; - /** - * Color of the node. - */ - color: Color; - /** - * Construct from value and color of node. - * - * @param value Value to be stored in. - * @param color Color of the node, red or black. - */ - constructor(value: T, color: Color); - /** - * Get grand-parent. - */ - readonly grand_parent: XTreeNode; - /** - * Get sibling, opposite side node in same parent. - */ - readonly sibling: XTreeNode; - /** - * Get uncle, parent's sibling. - */ - readonly uncle: XTreeNode; - } -} -declare namespace std.Deque { - type iterator = std.DequeIterator; - type reverse_iterator = std.DequeReverseIterator; -} -declare namespace std { - /** - *

Double ended queue.

- * - *

{@link Deque} (usually pronounced like "deck") is an irregular acronym of - * double-ended queue. Double-ended queues are sequence containers with dynamic sizes that can be - * expanded or contracted on both ends (either its front or its back).

- * - *

Specific libraries may implement deques in different ways, generally as some form of dynamic array. But in any - * case, they allow for the individual elements to be accessed directly through random access iterators, with storage - * handled automatically by expanding and contracting the container as needed.

- * - *

Therefore, they provide a functionality similar to vectors, but with efficient insertion and deletion of - * elements also at the beginning of the sequence, and not only at its end. But, unlike {@link Vector Vectors}, - * {@link Deque Deques} are not guaranteed to store all its elements in contiguous storage locations: accessing - * elements in a deque by offsetting a pointer to another element causes undefined behavior.

- * - *

Both {@link Vector}s and {@link Deque}s provide a very similar interface and can be used for similar purposes, - * but internally both work in quite different ways: While {@link Vector}s use a single array that needs to be - * occasionally reallocated for growth, the elements of a {@link Deque} can be scattered in different chunks of - * storage, with the container keeping the necessary information internally to provide direct access to any of its - * elements in constant time and with a uniform sequential interface (through iterators). Therefore, - * {@link Deque Deques} are a little more complex internally than {@link Vector}s, but this allows them to grow more - * efficiently under certain circumstances, especially with very long sequences, where reallocations become more - * expensive.

- * - *

For operations that involve frequent insertion or removals of elements at positions other than the beginning or - * the end, {@link Deque Deques} perform worse and have less consistent iterators and references than - * {@link List Lists}.

- * - *

- * - *

- * - *

Container properties

- *
- *
Sequence
- *
Elements in sequence containers are ordered in a strict linear sequence. Individual elements - * are accessed by their position in this sequence.
- * - *
Dynamic array
- *
Generally implemented as a dynamic array, it allows direct access to any element in the - * sequence and provides relatively fast addition/removal of elements at the beginning or the end - * of the sequence.
- *
- * - * @param Type of the elements. - * - * @reference http://www.cplusplus.com/reference/deque/deque/ - * @author Jeongho Nam - */ - class Deque extends base.Container implements base.IArrayContainer, base.IDequeContainer { - /** - * @hidden - */ - private static readonly ROW; - /** - * @hidden - */ - private static readonly MIN_CAPACITY; - /** - * @hidden - */ - private matrix_; - /** - * @hidden - */ - private size_; - /** - * @hidden - */ - private capacity_; - /** - * @hidden - */ - private get_col_size(); - /** - * @hidden - */ - private end_; - /** - * @hidden - */ - private rend_; - /** - *

Default Constructor.

- * - *

Constructs an empty container, with no elements.

- */ - constructor(); - /** - *

Initializer list Constructor.

- * - *

Constructs a container with a copy of each of the elements in array, in the same order.

- * - * @param array An array containing elements to be copied and contained. - */ - constructor(items: Array); - /** - *

Fill Constructor.

- * - *

Constructs a container with n elements. Each element is a copy of val (if provided).

- * - * @param n Initial container size (i.e., the number of elements in the container at construction). - * @param val Value to fill the container with. Each of the n elements in the container is - * initialized to a copy of this value. - */ - constructor(size: number, val: T); - /** - *

Copy Constructor.

- * - *

Constructs a container with a copy of each of the elements in container, in the same order.

- * - * @param container Another container object of the same type (with the same class template - * arguments T), whose contents are either copied or acquired. - */ - constructor(container: Deque); - /** - *

Range Constructor.

- * - *

Constructs a container with as many elements as the range (begin, end), with each - * element emplace-constructed from its corresponding element in that range, in the same order.

- * - * @param begin Input interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - */ - constructor(begin: Iterator, end: Iterator); - /** - * @inheritdoc - */ - assign>(begin: InputIterator, end: InputIterator): void; - /** - * @inheritdoc - */ - assign(n: number, val: T): void; - /** - * @inheritdoc - */ - reserve(capacity: number): void; - /** - * @inheritdoc - */ - clear(): void; - /** - * @inheritdoc - */ - begin(): DequeIterator; - /** - * @inheritdoc - */ - end(): DequeIterator; - /** - * @inheritdoc - */ - rbegin(): DequeReverseIterator; - /** - * @inheritdoc - */ - rend(): DequeReverseIterator; - /** - * @inheritdoc - */ - size(): number; - /** - * @inheritdoc - */ - empty(): boolean; - /** - * @inheritdoc - */ - capacity(): number; - /** - * @inheritdoc - */ - at(index: number): T; - /** - * @inheritdoc - */ - set(index: number, val: T): void; - /** - * @inheritdoc - */ - front(): T; - /** - * @inheritdoc - */ - back(): T; - /** - // Fetch row and column's index. - /** - * @hidden - */ - private fetch_index(index); - /** - * @inheritdoc - */ - push(...items: T[]): number; - /** - * @inheritdoc - */ - push_front(val: T): void; - /** - * @inheritdoc - */ - push_back(val: T): void; - /** - * @inheritdoc - */ - pop_front(): void; - /** - * @inheritdoc - */ - pop_back(): void; - /** - * @inheritdoc - */ - insert(position: DequeIterator, val: T): DequeIterator; - /** - * @inheritdoc - */ - insert(position: DequeIterator, n: number, val: T): DequeIterator; - /** - * @inheritdoc - */ - insert>(position: DequeIterator, begin: InputIterator, end: InputIterator): DequeIterator; - /** - * @inheritdoc - */ - insert(position: DequeReverseIterator, val: T): DequeReverseIterator; - /** - * @inheritdoc - */ - insert(position: DequeReverseIterator, n: number, val: T): DequeReverseIterator; - /** - * @inheritdoc - */ - insert>(position: DequeReverseIterator, begin: InputIterator, end: InputIterator): DequeReverseIterator; - /** - * @hidden - */ - private insert_by_val(position, val); - /** - * @hidden - */ - protected _Insert_by_repeating_val(position: DequeIterator, n: number, val: T): DequeIterator; - /** - * @hidden - */ - protected _Insert_by_range>(position: DequeIterator, begin: InputIterator, end: InputIterator): DequeIterator; - /** - * @hidden - */ - private insert_by_items(position, items); - /** - * @inheritdoc - */ - erase(position: DequeIterator): DequeIterator; - /** - * @inheritdoc - */ - erase(first: DequeIterator, last: DequeIterator): DequeIterator; - /** - * @inheritdoc - */ - erase(position: DequeReverseIterator): DequeReverseIterator; - /** - * @inheritdoc - */ - erase(first: DequeReverseIterator, last: DequeReverseIterator): DequeReverseIterator; - /** - * @hidden - */ - protected _Erase_by_range(first: DequeIterator, last: DequeIterator): DequeIterator; - /** - *

Swap content.

- * - *

Exchanges the content of the container by the content of obj, which is another - * {@link Deque container} object with same type of elements. Sizes and container type may differ.

- * - *

After the call to this member function, the elements in this container are those which were in obj - * before the call, and the elements of obj are those which were in this. All iterators, references and - * pointers remain valid for the swapped objects.

- * - *

Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that - * algorithm with an optimization that behaves like this member function.

- * - * @param obj Another {@link Deque container} of the same type of elements (i.e., instantiated - * with the same template parameter, T) whose content is swapped with that of this - * {@link container Deque}. - */ - swap(obj: Deque): void; - /** - * @inheritdoc - */ - swap(obj: base.IContainer): void; - } -} -declare namespace std { - /** - *

An iterator of {@link Deque}.

- * - *

- * - *

- * - * @author Jeongho Nam - */ - class DequeIterator extends Iterator implements base.IArrayIterator { - /** - * Sequence number of iterator in the source {@link Deque}. - */ - private index_; - /** - *

Construct from the source {@link Deque container}.

- * - *

Note

- *

Do not create the iterator directly, by yourself.

- *

Use {@link Deque.begin begin()}, {@link Deque.end end()} in {@link Deque container} instead.

- * - * @param source The source {@link Deque container} to reference. - * @param index Sequence number of the element in the source {@link Deque}. - */ - constructor(source: Deque, index: number); - /** - * @hidden - */ - private readonly deque; - /** - * @inheritdoc - */ - /** - * Set value of the iterator is pointing to. - * - * @param val Value to set. - */ - value: T; - /** - * @inheritdoc - */ - readonly index: number; - /** - * @inheritdoc - */ - prev(): DequeIterator; - /** - * @inheritdoc - */ - next(): DequeIterator; - /** - * @inheritdoc - */ - advance(n: number): DequeIterator; - /** - * @inheritdoc - */ - equals(obj: DequeIterator): boolean; - /** - * @inheritdoc - */ - swap(obj: DequeIterator): void; - } -} -declare namespace std { - /** - *

A reverse-iterator of Deque.

- * - *

- * - *

- * - * @param Type of the elements. - * - * @author Jeongho Nam - */ - class DequeReverseIterator extends ReverseIterator, DequeReverseIterator> implements base.IArrayIterator { - /** - * Construct from base iterator. - * - * @param base A reference of the base iterator, which iterates in the opposite direction. - */ - constructor(base: DequeIterator); - /** - * @hidden - */ - protected _Create_neighbor(base: DequeIterator): DequeReverseIterator; - /** - * @inheritdoc - */ - /** - * Set value of the iterator is pointing to. - * - * @param val Value to set. - */ - value: T; - /** - * Get index. - */ - readonly index: number; - } -} -declare namespace std { - /** - *

Function handling termination on exception

- * - *

Calls the current terminate handler.

- * - *

By default, the terminate handler calls abort. But this behavior can be redefined by calling - * {@link set_terminate}.

- * - *

This function is automatically called when no catch handler can be found for a thrown exception, - * or for some other exceptional circumstance that makes impossible to continue the exception handling process.

- * - *

This function is provided so that the terminate handler can be explicitly called by a program that needs to - * abnormally terminate, and works even if {@link set_terminate} has not been used to set a custom terminate handler - * (calling abort in this case).

- */ - function terminate(): void; - /** - *

Set terminate handler function.

- * - *

A terminate handler function is a function automatically called when the exception handling process has - * to be abandoned for some reason. This happens when no catch handler can be found for a thrown exception, or for - * some other exceptional circumstance that makes impossible to continue the exception handling process.

- * - *

Before this function is called by the program for the first time, the default behavior is to call abort.

- * - *

A program may explicitly call the current terminate handler function by calling {@link terminate}.

- * - * @param f Function that takes no parameters and returns no value (void). - */ - function set_terminate(f: () => void): void; - /** - *

Get terminate handler function.

- * - *

The terminate handler function is automatically called when no catch handler can be found - * for a thrown exception, or for some other exceptional circumstance that makes impossible to continue the exception - * handling process.

- * - *

If no such function has been set by a previous call to {@link set_terminate}, the function returns a - * null-pointer.

- * - * @return If {@link set_terminate} has previously been called by the program, the function returns the current - * terminate handler function. Otherwise, it returns a null-pointer. - */ - function get_terminate(): () => void; - /** - *

Standard exception class.

- * - *

Base class for standard exceptions.

- * - *

All objects thrown by components of the standard library are derived from this class. - * Therefore, all standard exceptions can be caught by catching this type by reference.

- * - *

- *

- * - * @reference http://www.cplusplus.com/reference/exception/exception - * @author Jeongho Nam - */ - class Exception extends Error { - /** - * A message representing specification about the Exception. - */ - private description; - /** - * Default Constructor. - */ - constructor(); - /** - *

Construct from a message.

- * - * @param message A message representing specification about the Exception. - */ - constructor(message: string); - /** - *

Get string identifying exception.

- *

Returns a string that may be used to identify the exception.

- * - *

The particular representation pointed by the returned value is implementation-defined. - * As a virtual function, derived classes may redefine this function so that specify value are - * returned.

- */ - what(): string; - /** - * @inheritdoc - */ - readonly message: string; - /** - * @inheritdoc - */ - readonly name: string; - } - /** - *

Logic error exception.

- * - *

This class defines the type of objects thrown as exceptions to report errors in the internal - * logical of the program, such as violation of logical preconditions or class invariants.

- * - *

These errors are presumably detectable before the program executes.

- * - *

It is used as a base class for several logical error exceptions.

- * - *

- *

- * - * @reference http://www.cplusplus.com/reference/stdexcept/logic_error - * @author Jeongho Nam - */ - class LogicError extends Exception { - /** - *

Construct from a message.

- * - * @param message A message representing specification about the Exception. - */ - constructor(message: string); - } - /** - *

Domain error exception.

- * - *

This class defines the type of objects thrown as exceptions to report domain errors.

- * - *

Generally, the domain of a mathematical function is the subset of values that it is defined for. - * For example, the square root function is only defined for non-negative numbers. Thus, a negative number - * for such a function would qualify as a domain error.

- * - *

No component of the standard library throws exceptions of this type. It is designed as a standard - * exception to be thrown by programs.

- * - *

- *

- * - * @reference http://www.cplusplus.com/reference/stdexcept/domain_error - * @author Jeongho Nam - */ - class DomainError extends LogicError { - /** - *

Construct from a message.

- * - * @param message A message representing specification about the Exception. - */ - constructor(message: string); - } - /** - *

Invalid argument exception.

- * - *

This class defines the type of objects thrown as exceptions to report an invalid argument.

- * - *

It is a standard exception that can be thrown by programs. Some components of the standard library - * also throw exceptions of this type to signal invalid arguments.

- * - *

- *

- * - * @reference http://www.cplusplus.com/reference/stdexcept/invalid_argument - * @author Jeongho Nam - */ - class InvalidArgument extends LogicError { - /** - *

Construct from a message.

- * - * @param message A message representing specification about the Exception. - */ - constructor(message: string); - } - /** - *

Length error exception.

- * - *

This class defines the type of objects thrown as exceptions to report a length error.

- * - *

It is a standard exception that can be thrown by programs. Some components of the standard library, - * such as vector and string also throw exceptions of this type to signal errors resizing.

- * - *

- *

- * - * @reference http://www.cplusplus.com/reference/stdexcept/length_error - * @author Jeongho Nam - */ - class LengthError extends LogicError { - /** - *

Construct from a message.

- * - * @param message A message representing specification about the Exception. - */ - constructor(message: string); - } - /** - *

Out-of-range exception.

- * - *

This class defines the type of objects thrown as exceptions to report an out-of-range error.

- * - *

It is a standard exception that can be thrown by programs. Some components of the standard library, - * such as vector, deque, string and bitset also throw exceptions of this type to signal arguments - * out of range.

- * - *

- *

- * - * @reference http://www.cplusplus.com/reference/stdexcept/out_of_range - * @author Jeongho Nam - */ - class OutOfRange extends LogicError { - /** - *

Construct from a message.

- * - * @param message A message representing specification about the Exception. - */ - constructor(message: string); - } - /** - *

Runtime error exception.

- * - *

This class defines the type of objects thrown as exceptions to report errors that can only be - * detected during runtime.

- * - *

It is used as a base class for several runtime error exceptions.

- * - *

- *

- * - * @reference http://www.cplusplus.com/reference/stdexcept/runtime_error - * @author Jeongho Nam - */ - class RuntimeError extends Exception { - /** - *

Construct from a message.

- * - * @param message A message representing specification about the Exception. - */ - constructor(message: string); - } - /** - *

Overflow error exception.

- * - *

This class defines the type of objects thrown as exceptions to arithmetic overflow errors.

- * - *

It is a standard exception that can be thrown by programs. Some components of the standard library - * also throw exceptions of this type to signal range errors.

- * - *

- *

- * - * @reference http://www.cplusplus.com/reference/stdexcept/overflow_error - * @author Jeongho Nam - */ - class OverflowError extends RuntimeError { - /** - *

Construct from a message.

- * - * @param message A message representing specification about the Exception. - */ - constructor(message: string); - } - /** - *

Underflow error exception.

- * - *

This class defines the type of objects thrown as exceptions to arithmetic underflow errors.

- * - *

No component of the standard library throws exceptions of this type. It is designed as a standard - * exception to be thrown by programs.

- * - *

- *

- * - * @reference http://www.cplusplus.com/reference/stdexcept/underflow_error - * @author Jeongho Nam - */ - class UnderflowError extends RuntimeError { - /** - *

Construct from a message.

- * - * @param message A message representing specification about the Exception. - */ - constructor(message: string); - } - /** - *

Range error exception.

- * - *

This class defines the type of objects thrown as exceptions to report range errors in internal - * computations.

- * - *

It is a standard exception that can be thrown by programs. Some components of the standard library - * also throw exceptions of this type to signal range errors.

- * - *

- *

- * - * @reference http://www.cplusplus.com/reference/stdexcept/range_error - * @author Jeongho Nam - */ - class RangeError extends RuntimeError { - /** - *

Construct from a message.

- * - * @param message A message representing specification about the Exception. - */ - constructor(message: string); - } -} -declare namespace std { - /** - *

Function object class for equality comparison.

- * - *

Binary function object class whose call returns whether its two arguments compare equal (as returned by - * operator ==).

- * - *

Generically, function objects are instances of a class with member function {@link IComparable.equal_to equal_to} - * defined. This member function allows the object to be used with the same syntax as a function call.

- * - * @param x First element to compare. - * @param y Second element to compare. - * - * @return Whether the arguments are equal. - */ - function equal_to(x: T, y: T): boolean; - /** - *

Function object class for non-equality comparison.

- * - *

Binary function object class whose call returns whether its two arguments compare not equal (as returned - * by operator operator!=).

- * - *

Generically, function objects are instances of a class with member function {@link IComparable.equal_to equal_to} - * defined. This member function allows the object to be used with the same syntax as a function call.

- * - * @param x First element to compare. - * @param y Second element to compare. - * - * @return Whether the arguments are not equal. - */ - function not_equal_to(x: T, y: T): boolean; - /** - *

Function for less-than inequality comparison.

- * - *

Binary function returns whether the its first argument compares less than the second.

- * - *

Generically, function objects are instances of a class with member function {@link IComparable.less less} - * defined. If an object doesn't have the method, then its own uid will be used to compare insteadly. - * This member function allows the object to be used with the same syntax as a function call.

- * - *

Objects of this class can be used on standard algorithms such as {@link sort sort()}, - * {@link merge merge()} or {@link TreeMap.lower_bound lower_bound()}.

- * - * @param Type of arguments to compare by the function call. The type shall supporrt the operation - * operator<() or method {@link IComparable.less less}. - * - * @param x First element, the standard of comparison. - * @param y Second element compare with the first. - * - * @return Whether the first parameter is less than the second. - */ - function less(x: T, y: T): boolean; - /** - *

Function object class for less-than-or-equal-to comparison.

- * - *

Binary function object class whose call returns whether the its first argument compares {@link less less than} or - * {@link equal_to equal to} the second (as returned by operator <=).

- * - *

Generically, function objects are instances of a class with member function {@link IComparable.less less} - * and {@link IComparable.equal_to equal_to} defined. This member function allows the object to be used with the same - * syntax as a function call.

- * - * @param x First element, the standard of comparison. - * @param y Second element compare with the first. - * - * @return Whether the x is {@link less less than} or {@link equal_to equal to} the y. - */ - function less_equal(x: T, y: T): boolean; - /** - *

Function for greater-than inequality comparison.

- * - *

Binary function returns whether the its first argument compares greater than the second.

- * - *

Generically, function objects are instances of a class with member function {@link less} and - * {@link equal_to equal_to()} defined. If an object doesn't have those methods, then its own uid will be used - * to compare insteadly. This member function allows the object to be used with the same syntax as a function - * call.

- * - *

Objects of this class can be used on standard algorithms such as {@link sort sort()}, - * {@link merge merge()} or {@link TreeMap.lower_bound lower_bound()}.

- * - * @param Type of arguments to compare by the function call. The type shall supporrt the operation - * operator>() or method {@link IComparable.greater greater}. - * - * @return Whether the x is greater than the y. - */ - function greater(x: T, y: T): boolean; - /** - *

Function object class for greater-than-or-equal-to comparison.

- * - *

Binary function object class whose call returns whether the its first argument compares - * {@link greater greater than} or {@link equal_to equal to} the second (as returned by operator >=).

- * - *

Generically, function objects are instances of a class with member function {@link IComparable.less less} - * defined. If an object doesn't have the method, then its own uid will be used to compare insteadly. - * This member function allows the object to be used with the same syntax as a function call.

- * - * @param x First element, the standard of comparison. - * @param y Second element compare with the first. - * - * @return Whether the x is {@link greater greater than} or {@link equal_to equal to} the y. - */ - function greater_equal(x: T, y: T): boolean; - /** - *

Logical AND function object class.

- * - *

Binary function object class whose call returns the result of the logical "and" operation between its two - * arguments (as returned by operator &&).

- * - *

Generically, function objects are instances of a class with member function operator() defined. This member - * function allows the object to be used with the same syntax as a function call.

- * - * @param x First element. - * @param y Second element. - * - * @return Result of logical AND operation. - */ - function logical_and(x: T, y: T): boolean; - /** - *

Logical OR function object class.

- * - *

Binary function object class whose call returns the result of the logical "or" operation between its two - * arguments (as returned by operator ||).

- * - *

Generically, function objects are instances of a class with member function operator() defined. This member - * function allows the object to be used with the same syntax as a function call.

- * - * @param x First element. - * @param y Second element. - * - * @return Result of logical OR operation. - */ - function logical_or(x: T, y: T): boolean; - /** - *

Logical NOT function object class.

- * - *

Unary function object class whose call returns the result of the logical "not" operation on its argument - * (as returned by operator !).

- * - *

Generically, function objects are instances of a class with member function operator() defined. This member - * function allows the object to be used with the same syntax as a function call.

- * - * @param x Target element. - * - * @return Result of logical NOT operation. - */ - function logical_not(x: T): boolean; - /** - *

Bitwise AND function object class.

- * - *

Binary function object class whose call returns the result of applying the bitwise "and" operation between - * its two arguments (as returned by operator &).

- * - * @param x First element. - * @param y Second element. - * - * @return Result of bitwise AND operation. - */ - function bit_and(x: number, y: number): number; - /** - *

Bitwise OR function object class.

- * - *

Binary function object class whose call returns the result of applying the bitwise "and" operation between - * its two arguments (as returned by operator &).

- * - * @param x First element. - * @param y Second element. - * - * @return Result of bitwise OR operation. - */ - function bit_or(x: number, y: number): number; - /** - *

Bitwise XOR function object class.

- * - *

Binary function object class whose call returns the result of applying the bitwise "exclusive or" - * operation between its two arguments (as returned by operator ^).

- * - * @param x First element. - * @param y Second element. - * - * @return Result of bitwise XOR operation. - */ - function bit_xor(x: number, y: number): number; - /** - *

Default hash function for number.

- * - *

Unary function that defines the default hash function used by the standard library.

- * - *

The functional call returns a hash value of its argument: A hash value is a value that depends solely on - * its argument, returning always the same value for the same argument (for a given execution of a program). The - * value returned shall have a small likelihood of being the same as the one returned for a different argument. - *

- * - * @param val Value to be hashed. - * - * @return Returns a hash value for its argument, as a value of type number. The number is an unsigned integer. - */ - function hash(val: number): number; - /** - *

Default hash function for string.

- * - *

Unary function that defines the default hash function used by the standard library.

- * - *

The functional call returns a hash value of its argument: A hash value is a value that depends solely on - * its argument, returning always the same value for the same argument (for a given execution of a program). The - * value returned shall have a small likelihood of being the same as the one returned for a different argument. - *

- * - * @param str A string to be hashed. - * - * @return Returns a hash value for its argument, as a value of type number. The number is an unsigned integer. - */ - function hash(str: string): number; - /** - *

Default hash function for Object.

- * - *

Unary function that defines the default hash function used by the standard library.

- * - *

The functional call returns a hash value of its argument: A hash value is a value that depends solely on - * its argument, returning always the same value for the same argument (for a given execution of a program). The - * value returned shall have a small likelihood of being the same as the one returned for a different argument. - *

- * - *

The default {@link hash} function of Object returns a value returned from {@link hash hash(number)} with - * an unique id of each Object. If you want to specify {@link hash} function of a specific class, then - * define a member function public hash(): number in the class.

- * - * @param obj Object to be hashed. - * - * @return Returns a hash value for its argument, as a value of type number. The number is an unsigned integer. - */ - function hash(obj: Object): number; - /** - *

Exchange contents of {@link IContainers containers}.

- * - *

The contents of container left are exchanged with those of right. Both container objects must have - * same type of elements (same template parameters), although sizes may differ.

- * - *

After the call to this member function, the elements in left are those which were in right before - * the call, and the elements of right are those which were in left. All iterators, references and - * pointers remain valid for the swapped objects.

- * - *

This is an overload of the generic algorithm swap that improves its performance by mutually transferring - * ownership over their assets to the other container (i.e., the containers exchange references to their data, without - * actually performing any element copy or movement): It behaves as if left. - * {@link IContainer.swap swap}(right) was called.

- * - * @param left A {@link IContainer container} to swap its contents. - * @param right A {@link IContainer container} to swap its contents. - */ - function swap(left: base.IContainer, right: base.IContainer): void; - /** - *

Exchange contents of queues.

- * - *

Exchanges the contents of left and right.

- * - * @param left A {@link Queue} container of the same type. Size may differ. - * @param right A {@link Queue} container of the same type. Size may differ. - */ - function swap(left: Queue, right: Queue): void; - /** - *

Exchange contents of {@link PriorityQueue PriorityQueues}.

- * - *

Exchanges the contents of left and right.

- * - * @param left A {@link PriorityQueue} container of the same type. Size may differ. - * @param right A {@link PriorityQueue} container of the same type. Size may differ. - */ - function swap(left: PriorityQueue, right: PriorityQueue): void; - /** - *

Exchange contents of {@link Stack Stacks}.

- * - *

Exchanges the contents of left and right.

- * - * @param left A {@link Stack} container of the same type. Size may differ. - * @param right A {@link Stack} container of the same type. Size may differ. - */ - function swap(left: Stack, right: Stack): void; - /** - *

Exchanges the contents of two {@link UniqueMap unique maps}.

- * - *

The contents of container left are exchanged with those of right. Both container objects must - * be of the same type (same template parameters), although sizes may differ.

- * - *

After the call to this member function, the elements in left are those which were in right - * before the call, and the elements of right are those which were in left. All iterators, references - * and pointers remain valid for the swapped objects.

- * - *

This is an overload of the generic algorithm swap that improves its performance by mutually transferring - * ownership over their assets to the other container (i.e., the containers exchange references to their data, - * without actually performing any element copy or movement): It behaves as if - * left.{@link UniqueMap.swap swap}(right) was called.

- * - * @param left An {@link UniqueMap unique map} to swap its conents. - * @param right An {@link UniqueMap unique map} to swap its conents. - */ - function swap(left: base.UniqueMap, right: base.UniqueMap): void; - /** - *

Exchanges the contents of two {@link MultiMap multi maps}.

- * - *

The contents of container left are exchanged with those of right. Both container objects must - * be of the same type (same template parameters), although sizes may differ.

- * - *

After the call to this member function, the elements in left are those which were in right - * before the call, and the elements of right are those which were in left. All iterators, references - * and pointers remain valid for the swapped objects.

- * - *

This is an overload of the generic algorithm swap that improves its performance by mutually transferring - * ownership over their assets to the other container (i.e., the containers exchange references to their data, - * without actually performing any element copy or movement): It behaves as if - * left.{@link MultiMap.swap swap}(right) was called.

- * - * @param left A {@link MultiMap multi map} to swap its conents. - * @param right A {@link MultiMap multi map} to swap its conents. - */ - function swap(left: base.MultiMap, right: base.MultiMap): void; -} -declare namespace std { - /** - *

Bind function arguments.

- * - *

Returns a function object based on fn, but with its arguments bound to args.

- * - *

Each argument may either be bound to a value or be a {@link placeholders placeholder}:

- *
    - *
  • If bound to a value, calling the returned function object will always use that value as argument.
  • - *
  • - * If a {@link placeholders placeholder}, calling the returned function object forwards an argument passed to the - * call (the one whose order number is specified by the placeholder). - *
  • - *
- * - *

Calling the returned object returns the same type as fn.

- * - * @param fn A function object, pointer to function or pointer to member. - * @param args List of arguments to bind: either values, or {@link placeholders}. - * - * @return A function object that, when called, calls fn with its arguments bound to args. If fn is - * a pointer to member, the first argument expected by the returned function is an object of the class fn - * is a member. - */ - function bind(fn: (...args: any[]) => Ret, ...args: any[]): (...args: any[]) => Ret; - /** - *

Bind function arguments.

- * - *

Returns a function object based on fn, but with its arguments bound to args.

- * - *

Each argument may either be bound to a value or be a {@link placeholders placeholder}:

- *
    - *
  • If bound to a value, calling the returned function object will always use that value as argument.
  • - *
  • - * If a {@link placeholders placeholder}, calling the returned function object forwards an argument passed to the - * call (the one whose order number is specified by the placeholder). - *
  • - *
- * - *

Calling the returned object returns the same type as fn.

- * - * @param fn A function object, pointer to function or pointer to member. - * @param thisArg This argument, owner object of the member method fn. - * @param args List of arguments to bind: either values, or {@link placeholders}. - * - * @return A function object that, when called, calls fn with its arguments bound to args. If fn is - * a pointer to member, the first argument expected by the returned function is an object of the class fn - * is a member. - */ - function bind(fn: (...args: any[]) => Ret, thisArg: T, ...args: any[]): (...args: any[]) => Ret; -} -/** - *

Bind argument placeholders.

- * - *
- * - *

When the function object returned by bind is called, an argument with placeholder {@link _1} is replaced by the - * first argument in the call, {@link _2} is replaced by the second argument in the call, and so on... For example:

- * - * - * let vec: Vector = new Vector(); - * - * let bind = std.bind(Vector.insert, _1, vec.end(), _2, _3); - * bind.apply(vec, 5, 1); // vec.insert(vec.end(), 5, 1); - * // [1, 1, 1, 1, 1] - * - * - *

When a call to {@link bind} is used as a subexpression in another call to bind, the {@link placeholders} - * are relative to the outermost {@link bind} expression.

- * - * @reference http://www.cplusplus.com/reference/functional/placeholders/ - * @author Jeongho Nam - */ -declare namespace std.placeholders { - /** - * @hidden - */ - class PlaceHolder { - private index_; - constructor(index: number); - readonly index: number; - } - /** - * Replaced by the first argument in the function call. - */ - const _1: PlaceHolder; - /** - * Replaced by the second argument in the function call. - */ - const _2: PlaceHolder; - /** - * Replaced by the third argument in the function call. - */ - const _3: PlaceHolder; - const _4: PlaceHolder; - const _5: PlaceHolder; - const _6: PlaceHolder; - const _7: PlaceHolder; - const _8: PlaceHolder; - const _9: PlaceHolder; - const _10: PlaceHolder; - const _11: PlaceHolder; - const _12: PlaceHolder; - const _13: PlaceHolder; - const _14: PlaceHolder; - const _15: PlaceHolder; - const _16: PlaceHolder; - const _17: PlaceHolder; - const _18: PlaceHolder; - const _19: PlaceHolder; - const _20: PlaceHolder; -} -declare namespace std.HashMap { - type iterator = std.MapIterator; - type reverse_iterator = std.MapReverseIterator; -} -declare namespace std { - /** - *

Hashed, unordered map.

- * - *

{@link HashMap}s are associative containers that store elements formed by the combination of a key value - * and a mapped value, and which allows for fast retrieval of individual elements based on their keys. - *

- * - *

In an {@link HashMap}, the key value is generally used to uniquely identify the element, while the - * mapped value is an object with the content associated to this key. Types of key and - * mapped value may differ.

- * - *

Internally, the elements in the {@link HashMap} are not sorted in any particular order with respect to either - * their key or mapped values, but organized into buckets depending on their hash values to allow - * for fast access to individual elements directly by their key values (with a constant average time complexity - * on average).

- * - *

{@link HashMap} containers are faster than {@link TreeMap} containers to access individual elements by their - * key, although they are generally less efficient for range iteration through a subset of their elements.

- * - *

- * - *

- * - *

Container properties

- *
- *
Associative
- *
Elements in associative containers are referenced by their key and not by their absolute - * position in the container.
- * - *
Hashed
- *
Hashed containers organize their elements using hash tables that allow for fast access to elements - * by their key.
- * - *
Map
- *
Each element associates a key to a mapped value: - * Keys are meant to identify the elements whose main content is the mapped value.
- * - *
Unique keys
- *
No two elements in the container can have equivalent keys.
- *
- * - * @param Type of the key values. - * Each element in an {@link HashMap} is uniquely identified by its key value. - * @param Type of the mapped value. - * Each element in an {@link HashMap} is used to store some data as its mapped value. - * - * @reference http://www.cplusplus.com/reference/unordered_map/unordered_map - * @author Jeongho Nam - */ - class HashMap extends base.UniqueMap implements base.IHashMap { - /** - * @hidden - */ - private hash_buckets_; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from elements. - */ - constructor(items: Pair[]); - /** - * Contruct from tuples. - * - * @param array Tuples to be contained. - */ - constructor(array: [Key, T][]); - /** - * Copy Constructor. - */ - constructor(container: HashMap); - /** - * Construct from range iterators. - */ - constructor(begin: Iterator>, end: Iterator>); - /** - * @inheritdoc - */ - clear(): void; - /** - * @inheritdoc - */ - find(key: Key): MapIterator; - /** - * @inheritdoc - */ - begin(): MapIterator; - /** - * @inheritdoc - */ - begin(index: number): MapIterator; - /** - * @inheritdoc - */ - end(): MapIterator; - /** - * @inheritdoc - */ - end(index: number): MapIterator; - /** - * @inheritdoc - */ - rbegin(): MapReverseIterator; - /** - * @inheritdoc - */ - rbegin(index: number): MapReverseIterator; - /** - * @inheritdoc - */ - rend(): MapReverseIterator; - /** - * @inheritdoc - */ - rend(index: number): MapReverseIterator; - /** - * @inheritdoc - */ - bucket_count(): number; - /** - * @inheritdoc - */ - bucket_size(index: number): number; - /** - * @inheritdoc - */ - max_load_factor(): number; - /** - * @inheritdoc - */ - max_load_factor(z: number): void; - /** - * @inheritdoc - */ - bucket(key: Key): number; - /** - * @inheritdoc - */ - reserve(n: number): void; - /** - * @inheritdoc - */ - rehash(n: number): void; - /** - * @hidden - */ - protected _Insert_by_pair(pair: Pair): any; - /** - * @hidden - */ - protected _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; - /** - * @hidden - */ - protected _Insert_by_range>>(first: InputIterator, last: InputIterator): void; - /** - * @inheritdoc - */ - protected _Handle_insert(first: MapIterator, last: MapIterator): void; - /** - * @inheritdoc - */ - protected _Handle_erase(first: MapIterator, last: MapIterator): void; - /** - *

Swap content.

- * - *

Exchanges the content of the container by the content of obj, which is another - * {@link HashMap map} of the same type. Sizes abd container type may differ.

- * - *

After the call to this member function, the elements in this container are those which were - * in obj before the call, and the elements of obj are those which were in this. All - * iterators, references and pointers remain valid for the swapped objects.

- * - *

Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that - * algorithm with an optimization that behaves like this member function.

- * - * @param obj Another {@link HashMap map container} of the same type of elements as this (i.e., - * with the same template parameters, Key and T) whose content is swapped - * with that of this {@link HashMap container}. - */ - swap(obj: HashMap): void; - /** - * @inheritdoc - */ - swap(obj: base.IContainer>): void; - } -} -declare namespace std.HashMultiMap { - type iterator = std.MapIterator; - type reverse_iterator = std.MapReverseIterator; -} -declare namespace std { - /** - *

Hashed, unordered Multimap.

- * - *

{@link HashMultiMap}s are associative containers that store elements formed by the combination of - * a key value and a mapped value, much like {@link HashMultiMap} containers, but allowing - * different elements to have equivalent keys.

- * - *

In an {@link HashMultiMap}, the key value is generally used to uniquely identify the - * element, while the mapped value is an object with the content associated to this key. - * Types of key and mapped value may differ.

- * - *

Internally, the elements in the {@link HashMultiMap} are not sorted in any particular order with - * respect to either their key or mapped values, but organized into buckets depending on - * their hash values to allow for fast access to individual elements directly by their key values - * (with a constant average time complexity on average).

- * - *

Elements with equivalent keys are grouped together in the same bucket and in such a way that - * an iterator can iterate through all of them. Iterators in the container are doubly linked iterators.

- * - *

- * - *

- * - *

Container properties

- *
- *
Associative
- *
Elements in associative containers are referenced by their key and not by their absolute - * position in the container.
- * - *
Hashed
- *
Hashed containers organize their elements using hash tables that allow for fast access to elements - * by their key.
- * - *
Map
- *
Each element associates a key to a mapped value: - * Keys are meant to identify the elements whose main content is the mapped value.
- * - *
Multiple equivalent keys
- *
The container can hold multiple elements with equivalent keys.
- *
- * - * @param Type of the key values. - * Each element in an {@link HashMultiMap} is identified by a key value. - * @param Type of the mapped value. - * Each element in an {@link HashMultiMap} is used to store some data as its mapped value. - * - * @reference http://www.cplusplus.com/reference/unordered_map/unordered_multimap - * @author Jeongho Nam - */ - class HashMultiMap extends base.MultiMap { - /** - * @hidden - */ - private hash_buckets_; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from elements. - */ - constructor(items: Pair[]); - /** - * Contruct from tuples. - * - * @param array Tuples to be contained. - */ - constructor(array: [Key, T][]); - /** - * Copy Constructor. - */ - constructor(container: HashMultiMap); - /** - * Construct from range iterators. - */ - constructor(begin: Iterator>, end: Iterator>); - /** - * @inheritdoc - */ - clear(): void; - /** - * @inheritdoc - */ - find(key: Key): MapIterator; - /** - * @inheritdoc - */ - count(key: Key): number; - /** - * @inheritdoc - */ - begin(): MapIterator; - /** - * @inheritdoc - */ - begin(index: number): MapIterator; - /** - * @inheritdoc - */ - end(): MapIterator; - /** - * @inheritdoc - */ - end(index: number): MapIterator; - /** - * @inheritdoc - */ - rbegin(): MapReverseIterator; - /** - * @inheritdoc - */ - rbegin(index: number): MapReverseIterator; - /** - * @inheritdoc - */ - rend(): MapReverseIterator; - /** - * @inheritdoc - */ - rend(index: number): MapReverseIterator; - /** - * @inheritdoc - */ - bucket_count(): number; - /** - * @inheritdoc - */ - bucket_size(n: number): number; - /** - * @inheritdoc - */ - max_load_factor(): number; - /** - * @inheritdoc - */ - max_load_factor(z: number): void; - /** - * @inheritdoc - */ - bucket(key: Key): number; - /** - * @inheritdoc - */ - reserve(n: number): void; - /** - * @inheritdoc - */ - rehash(n: number): void; - /** - * @hidden - */ - protected _Insert_by_pair(pair: Pair): any; - /** - * @hidden - */ - protected _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; - /** - * @hidden - */ - protected _Insert_by_range>>(first: InputIterator, last: InputIterator): void; - /** - * @inheritdoc - */ - protected _Handle_insert(first: MapIterator, last: MapIterator): void; - /** - * @inheritdoc - */ - protected _Handle_erase(first: MapIterator, last: MapIterator): void; - /** - *

Swap content.

- * - *

Exchanges the content of the container by the content of obj, which is another - * {@link HashMultiMap map} of the same type. Sizes abd container type may differ.

- * - *

After the call to this member function, the elements in this container are those which were - * in obj before the call, and the elements of obj are those which were in this. All - * iterators, references and pointers remain valid for the swapped objects.

- * - *

Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that - * algorithm with an optimization that behaves like this member function.

- * - * @param obj Another {@link HashMultiMap map container} of the same type of elements as this (i.e., - * with the same template parameters, Key and T) whose content is swapped - * with that of this {@link HashMultiMap container}. - */ - swap(obj: HashMultiMap): void; - /** - * @inheritdoc - */ - swap(obj: base.IContainer>): void; - } -} -declare namespace std.HashMultiSet { - type iterator = std.SetIterator; - type reverse_iterator = std.SetReverseIterator; -} -declare namespace std { - /** - *

Hashed, unordered Multiset.

- * - *

{@link HashMultiSet HashMultiSets} are containers that store elements in no particular order, allowing fast - * retrieval of individual elements based on their value, much like {@link HashMultiSet} containers, - * but allowing different elements to have equivalent values.

- * - *

In an {@link HashMultiSet}, the value of an element is at the same time its key, used to - * identify it. Keys are immutable, therefore, the elements in an {@link HashMultiSet} cannot be - * modified once in the container - they can be inserted and removed, though.

- * - *

Internally, the elements in the {@link HashMultiSet} are not sorted in any particular, but - * organized into buckets depending on their hash values to allow for fast access to individual - * elements directly by their values (with a constant average time complexity on average).

- * - *

Elements with equivalent values are grouped together in the same bucket and in such a way that an - * iterator can iterate through all of them. Iterators in the container are doubly linked iterators.

- * - *

- *

- * - *

Container properties

- *
- *
Associative
- *
Elements in associative containers are referenced by their key and not by their absolute - * position in the container.
- * - *
Hashed
- *
Hashed containers organize their elements using hash tables that allow for fast access to elements - * by their key.
- * - *
Set
- *
The value of an element is also the key used to identify it.
- * - *
Multiple equivalent keys
- *
The container can hold multiple elements with equivalent keys.
- *
- * - * @param Type of the elements. - * Each element in an {@link UnorderedMultiSet} is also identified by this value.. - * - * @reference http://www.cplusplus.com/reference/unordered_set/unordered_multiset - * @author Jeongho Nam - */ - class HashMultiSet extends base.MultiSet { - /** - * @hidden - */ - private hash_buckets_; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from elements. - */ - constructor(items: T[]); - /** - * Copy Constructor. - */ - constructor(container: HashMultiSet); - /** - * Construct from range iterators. - */ - constructor(begin: Iterator, end: Iterator); - /** - * @inheritdoc - */ - clear(): void; - /** - * @inheritdoc - */ - find(key: T): SetIterator; - /** - * @inheritdoc - */ - count(key: T): number; - /** - * @inheritdoc - */ - begin(): SetIterator; - /** - * @inheritdoc - */ - begin(index: number): SetIterator; - /** - * @inheritdoc - */ - end(): SetIterator; - /** - * @inheritdoc - */ - end(index: number): SetIterator; - /** - * @inheritdoc - */ - rbegin(): SetReverseIterator; - /** - * @inheritdoc - */ - rbegin(index: number): SetReverseIterator; - /** - * @inheritdoc - */ - rend(): SetReverseIterator; - /** - * @inheritdoc - */ - rend(index: number): SetReverseIterator; - /** - * @inheritdoc - */ - bucket_count(): number; - /** - * @inheritdoc - */ - bucket_size(n: number): number; - /** - * @inheritdoc - */ - max_load_factor(): number; - /** - * @inheritdoc - */ - max_load_factor(z: number): void; - /** - * @inheritdoc - */ - bucket(key: T): number; - /** - * @inheritdoc - */ - reserve(n: number): void; - /** - * @inheritdoc - */ - rehash(n: number): void; - /** - * @hidden - */ - protected _Insert_by_val(val: T): any; - /** - * @hidden - */ - protected _Insert_by_hint(hint: SetIterator, val: T): SetIterator; - /** - * @hidden - */ - protected _Insert_by_range>(first: InputIterator, last: InputIterator): void; - /** - * @inheritdoc - */ - protected _Handle_insert(first: SetIterator, last: SetIterator): void; - /** - * @inheritdoc - */ - protected _Handle_erase(first: SetIterator, last: SetIterator): void; - /** - *

Swap content.

- * - *

Exchanges the content of the container by the content of obj, which is another - * {@link HashMultiSet set} of the same type. Sizes abd container type may differ.

- * - *

After the call to this member function, the elements in this container are those which were - * in obj before the call, and the elements of obj are those which were in this. All - * iterators, references and pointers remain valid for the swapped objects.

- * - *

Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that - * algorithm with an optimization that behaves like this member function.

- * - * @param obj Another {@link HashMultiSet set container} of the same type of elements as this (i.e., - * with the same template parameters, Key and T) whose content is swapped - * with that of this {@link HashMultiSet container}. - */ - swap(obj: HashMultiSet): void; - /** - * @inheritdoc - */ - swap(obj: base.IContainer): void; - } -} -declare namespace std.HashSet { - type iterator = std.SetIterator; - type reverse_iterator = std.SetReverseIterator; -} -declare namespace std { - /** - *

Hashed, unordered set.

- * - *

{@link HashSet}s are containers that store unique elements in no particular order, and which - * allow for fast retrieval of individual elements based on their value.

- * - *

In an {@link HashSet}, the value of an element is at the same time its key, that - * identifies it uniquely. Keys are immutable, therefore, the elements in an {@link HashSet} cannot be - * modified once in the container - they can be inserted and removed, though.

- * - *

Internally, the elements in the {@link HashSet} are not sorted in any particular order, but - * organized into buckets depending on their hash values to allow for fast access to individual elements - * directly by their values (with a constant average time complexity on average).

- * - *

{@link HashSet} containers are faster than {@link TreeSet} containers to access individual - * elements by their key, although they are generally less efficient for range iteration through a - * subset of their elements.

- * - *

- *

- * - *

Container properties

- *
- *
Associative
- *
Elements in associative containers are referenced by their key and not by their absolute - * position in the container.
- * - *
Hashed
- *
Hashed containers organize their elements using hash tables that allow for fast access to elements - * by their key.
- * - *
Set
- *
The value of an element is also the key used to identify it.
- * - *
Unique keys
- *
No two elements in the container can have equivalent keys.
- *
- * - * @param Type of the elements. - * Each element in an {@link HashSet} is also uniquely identified by this value. - * - * @reference http://www.cplusplus.com/reference/unordered_set/unordered_set - * @author Jeongho Nam - */ - class HashSet extends base.UniqueSet implements base.IHashSet { - /** - * @hidden - */ - private hash_buckets_; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from elements. - */ - constructor(items: T[]); - /** - * Copy Constructor. - */ - constructor(container: HashSet); - /** - * Construct from range iterators. - */ - constructor(begin: Iterator, end: Iterator); - /** - * @inheritdoc - */ - clear(): void; - /** - * @inheritdoc - */ - find(key: T): SetIterator; - /** - * @inheritdoc - */ - begin(): SetIterator; - /** - * @inheritdoc - */ - begin(index: number): SetIterator; - /** - * @inheritdoc - */ - end(): SetIterator; - /** - * @inheritdoc - */ - end(index: number): SetIterator; - /** - * @inheritdoc - */ - rbegin(): SetReverseIterator; - /** - * @inheritdoc - */ - rbegin(index: number): SetReverseIterator; - /** - * @inheritdoc - */ - rend(): SetReverseIterator; - /** - * @inheritdoc - */ - rend(index: number): SetReverseIterator; - /** - * @inheritdoc - */ - bucket_count(): number; - /** - * @inheritdoc - */ - bucket_size(n: number): number; - /** - * @inheritdoc - */ - max_load_factor(): number; - /** - * @inheritdoc - */ - max_load_factor(z: number): void; - /** - * @inheritdoc - */ - bucket(key: T): number; - /** - * @inheritdoc - */ - reserve(n: number): void; - /** - * @inheritdoc - */ - rehash(n: number): void; - /** - * @hidden - */ - protected _Insert_by_val(val: T): any; - /** - * @hidden - */ - protected _Insert_by_hint(hint: SetIterator, val: T): SetIterator; - /** - * @hidden - */ - protected _Insert_by_range>(first: InputIterator, last: InputIterator): void; - /** - * @inheritdoc - */ - protected _Handle_insert(first: SetIterator, last: SetIterator): void; - /** - * @inheritdoc - */ - protected _Handle_erase(first: SetIterator, last: SetIterator): void; - /** - *

Swap content.

- * - *

Exchanges the content of the container by the content of obj, which is another - * {@link HashSet set} of the same type. Sizes abd container type may differ.

- * - *

After the call to this member function, the elements in this container are those which were - * in obj before the call, and the elements of obj are those which were in this. All - * iterators, references and pointers remain valid for the swapped objects.

- * - *

Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that - * algorithm with an optimization that behaves like this member function.

- * - * @param obj Another {@link HashSet set container} of the same type of elements as this (i.e., - * with the same template parameters, Key and T) whose content is swapped - * with that of this {@link HashSet container}. - */ - swap(obj: HashSet): void; - /** - * @inheritdoc - */ - swap(obj: base.IContainer): void; - } -} -declare namespace std { - /** - *

Comparable instance.

- * - *

{@link IComparable} is a common interface for objects who can compare each other.

- * - * @reference https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html - * @author Jeongho Nam - */ - interface IComparable extends Object { - /** - *

Indicates whether some other object is "equal to" this one.

- * - *

The {@link equal_to} method implements an equivalence relation on non-null object references:

- * - *
    - *
  • - * It is reflexive: for any non-null reference value x, x.equal_to(x) - * should return true. - *
  • - *
  • - * It is symmetric: for any non-null reference values x and y, - * x.equal_to(y) should return true if and only if y.equal_to(x) - * returns true.
  • - *
  • - * It is transitive: for any non-null reference values x, y, and - * z, if x.equal_to(y) returns true and y.equal_to(z) - * returns true, then x.equal_to(z) should return true. - *
  • - *
  • - * It is consistent: for any non-null reference values x and y, multiple - * invocations of x.equal_to(y) consistently return true or consistently return - * false, provided no information used in equal_to comparisons on the objects is modified. - *
  • - *
  • - * For any non-null reference value x, x.equal_to(null) should return - * false. - *
  • - *
- * - *

The {@link equal_to} method for interface {@link IComparable} implements the most discriminating possible - * equivalence relation on objects; that is, for any non-null reference values x and - * y, this method returns true if and only if x and y - * refer to the same object (x == y has the value true).

- * - *

Note that it is generally necessary to override the {@link hash_code} method whenever this method is - * overridden, so as to maintain the general contract for the {@link hash_code} method, which states that - * equal objects must have equal hash codes.

- * - *
    - *
  • {@link IComparable.equal_to} is called by {@link std.equal_to}.
  • - *
- * - * @param obj the reference object with which to compare. - * - * @return true if this object is the same as the obj argument; false otherwise. - */ - equals(obj: T): boolean; - /** - *

Less-than inequality comparison.

- * - *

Binary method returns whether the the instance compares less than the obj.

- * - *
    - *
  • - * {@link IComparable.less} is called by {@link std.less}. Also, this method can be used on standard - * algorithms such as {@link sort sort()}, {@link merge merge()} or - * {@link TreeMap.lower_bound lower_bound()}. - *
  • - *
- * - * @param obj the reference object with which to compare. - * - * @return Whether the first parameter is less than the second. - */ - less(obj: T): boolean; - /** - *

Issue a hash code.

- * - *

Returns a hash code value for the object. This method is supported for the benefit of hash tables such - * as those provided by hash containers; {@link HashSet}, {@link HashMap}, {@link MultiHashSet} and - * {@link MultiHashMap}.

- * - *

As much as is reasonably practical, the {@link hash_code} method defined by interface - * {@link IComparable} does return distinct integers for distinct objects. (This is typically implemented by - * converting the internal address of the object into an integer, but this implementation technique is not - * required by the JavaScript programming language.)

- * - *
    - *
  • - * {@link IComparable.hash_code} is called by {@link std.hash_code}. If you want to keep basically - * provided hash function, then returns {@link std.Hash.code}; return std.Hash.code(this); - *
  • - *
- * - * @return An hash code who represents the object. - */ - hashCode?(): number; - } -} -declare namespace std.List { - type iterator = std.ListIterator; - type reverse_iterator = std.ListReverseIterator; -} -declare namespace std { - /** - *

Doubly linked list.

- * - *

{@link List}s are sequence containers that allow constant time insert and erase operations anywhere within the - * sequence, and iteration in both directions.

- * - *

List containers are implemented as doubly-linked lists; Doubly linked lists can store each of the elements they - * contain in different and unrelated storage locations. The ordering is kept internally by the association to each - * element of a link to the element preceding it and a link to the element following it.

- * - *

Compared to other base standard sequence containers (array, vector and deque), lists perform generally better - * in inserting, extracting and moving elements in any position within the container for which an iterator has already - * been obtained, and therefore also in algorithms that make intensive use of these, like sorting algorithms.

- * - *

The main drawback of lists and forward_lists compared to these other sequence containers is that they lack - * direct access to the elements by their position; For example, to access the sixth element in a list, one has to - * iterate from a known position (like the beginning or the end) to that position, which takes linear time in the - * distance between these. They also consume some extra memory to keep the linking information associated to each - * element (which may be an important factor for large lists of small-sized elements).

- * - *

- * - *

- * - *

Container properties

- *
- *
Sequence
- *
Elements in sequence containers are ordered in a strict linear sequence. Individual elements are accessed by - * their position in this sequence.
- * - *
Doubly-linked list
- *
Each element keeps information on how to locate the next and the previous elements, allowing constant time - * insert and erase operations before or after a specific element (even of entire ranges), but no direct random - * access.
- *
- * - * @param Type of the elements. - * - * @reference http://www.cplusplus.com/reference/list/list/ - * @author Jeongho Nam - */ - class List extends base.ListContainer> { - private rend_; - /** - *

Default Constructor.

- * - *

Constructs an empty container, with no elements.

- */ - constructor(); - /** - *

Initializer list Constructor.

- * - *

Constructs a container with a copy of each of the elements in array, in the same order.

- * - * @param array An array containing elements to be copied and contained. - */ - constructor(items: Array); - /** - *

Fill Constructor.

- * - *

Constructs a container with n elements. Each element is a copy of val (if provided).

- * - * @param n Initial container size (i.e., the number of elements in the container at construction). - * @param val Value to fill the container with. Each of the n elements in the container is - * initialized to a copy of this value. - */ - constructor(size: number, val: T); - /** - *

Copy Constructor.

- * - *

Constructs a container with a copy of each of the elements in container, in the same order.

- * - * @param container Another container object of the same type (with the same class template - * arguments T), whose contents are either copied or acquired. - */ - constructor(container: List); - /** - *

Range Constructor.

- * - *

Constructs a container with as many elements as the range (begin, end), with each - * element emplace-constructed from its corresponding element in that range, in the same order.

- * - * @param begin Input interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - */ - constructor(begin: Iterator, end: Iterator); - /** - * @hidden - */ - protected _Create_iterator(prev: ListIterator, next: ListIterator, val: T): ListIterator; - /** - * @hidden - */ - protected _Set_begin(it: ListIterator): void; - /** - * @inheritdoc - */ - assign(n: number, val: T): void; - /** - * @inheritdoc - */ - assign>(begin: InputIterator, end: InputIterator): void; - /** - * @inheritdoc - */ - rbegin(): ListReverseIterator; - /** - * @inheritdoc - */ - rend(): ListReverseIterator; - /** - * @inheritdoc - */ - front(): T; - /** - * @inheritdoc - */ - back(): T; - /** - *

Insert an element.

- * - *

The container is extended by inserting a new element before the element at the specified - * position. This effectively increases the {@link List.size List size} by the amount of elements - * inserted.

- * - *

Unlike other standard sequence containers, {@link List} is specifically designed to be efficient - * inserting and removing elements in any position, even in the middle of the sequence.

- * - * @param position Position in the container where the new element is inserted. - * {@link iterator}> is a member type, defined as a - * {@link ListIterator bidirectional iterator} type that points to elements. - * @param val Value to be inserted as an element. - * - * @return An iterator that points to the newly inserted element; val. - */ - insert(position: ListIterator, val: T): ListIterator; - /** - *

Insert elements by repeated filling.

- * - *

The container is extended by inserting a new element before the element at the specified - * position. This effectively increases the {@link List.size List size} by the amount of elements - * inserted.

- * - *

Unlike other standard sequence containers, {@link List} is specifically designed to be efficient - * inserting and removing elements in any position, even in the middle of the sequence.

- * - * @param position Position in the container where the new elements are inserted. The {@link iterator} is a - * member type, defined as a {@link ListIterator bidirectional iterator} type that points to - * elements. - * @param size Number of elements to insert. - * @param val Value to be inserted as an element. - * - * @return An iterator that points to the first of the newly inserted elements. - */ - insert(position: ListIterator, size: number, val: T): ListIterator; - /** - *

Insert elements by range iterators.

- * - *

The container is extended by inserting a new element before the element at the specified - * position. This effectively increases the {@link List.size List size} by the amount of elements - * inserted.

- * - *

Unlike other standard sequence containers, {@link List} is specifically designed to be efficient - * inserting and removing elements in any position, even in the middle of the sequence.

- * - * @param position Position in the container where the new elements are inserted. The {@link iterator} is a - * member type, defined as a {@link ListIterator bidirectional iterator} type that points to - * elements. - * @param begin An iterator specifying range of the begining element. - * @param end An iterator specifying range of the ending element. - * - * @return An iterator that points to the first of the newly inserted elements. - */ - insert>(position: ListIterator, begin: InputIterator, end: InputIterator): ListIterator; - /** - *

Insert an element.

- * - *

The container is extended by inserting a new element before the element at the specified - * position. This effectively increases the {@link List.size List size} by the amount of elements - * inserted.

- * - *

Unlike other standard sequence containers, {@link List} is specifically designed to be efficient - * inserting and removing elements in any position, even in the middle of the sequence.

- * - * @param position Position in the container where the new element is inserted. - * {@link iterator}> is a member type, defined as a - * {@link ListReverseIterator bidirectional iterator} type that points to elements. - * @param val Value to be inserted as an element. - * - * @return An iterator that points to the newly inserted element; val. - */ - insert(position: ListReverseIterator, val: T): ListReverseIterator; - /** - *

Insert elements by repeated filling.

- * - *

The container is extended by inserting a new element before the element at the specified - * position. This effectively increases the {@link List.size List size} by the amount of elements - * inserted.

- * - *

Unlike other standard sequence containers, {@link List} is specifically designed to be efficient - * inserting and removing elements in any position, even in the middle of the sequence.

- * - * @param position Position in the container where the new elements are inserted. The {@link iterator} is a - * member type, defined as a {@link ListReverseIterator bidirectional iterator} type that points to - * elements. - * @param size Number of elements to insert. - * @param val Value to be inserted as an element. - * - * @return An iterator that points to the first of the newly inserted elements. - */ - insert(position: ListReverseIterator, size: number, val: T): ListReverseIterator; - /** - *

Insert elements by range iterators.

- * - *

The container is extended by inserting a new element before the element at the specified - * position. This effectively increases the {@link List.size List size} by the amount of elements - * inserted.

- * - *

Unlike other standard sequence containers, {@link List} is specifically designed to be efficient - * inserting and removing elements in any position, even in the middle of the sequence.

- * - * @param position Position in the container where the new elements are inserted. The {@link iterator} is a - * member type, defined as a {@link ListReverseIterator bidirectional iterator} type that points to - * elements. - * @param begin An iterator specifying range of the begining element. - * @param end An iterator specifying range of the ending element. - * - * @return An iterator that points to the first of the newly inserted elements. - */ - insert>(position: ListReverseIterator, begin: InputIterator, end: InputIterator): ListReverseIterator; - /** - *

Erase an element.

- * - *

Removes from the {@link List} either a single element; position.

- * - *

This effectively reduces the container size by the number of element removed.

- * - *

Unlike other standard sequence containers, {@link List} objects are specifically designed to be - * efficient inserting and removing elements in any position, even in the middle of the sequence.

- * - * @param position Iterator pointing to a single element to be removed from the {@link List}. - * - * @return An iterator pointing to the element that followed the last element erased by the function call. - * This is the {@link end end()} if the operation erased the last element in the sequence. - */ - erase(position: ListIterator): ListIterator; - /** - *

Erase elements.

- * - *

Removes from the {@link List} container a range of elements.

- * - *

This effectively reduces the container {@link size} by the number of elements removed.

- * - *

Unlike other standard sequence containers, {@link List} objects are specifically designed to be - * efficient inserting and removing elements in any position, even in the middle of the sequence.

- * - * @param begin An iterator specifying a range of beginning to erase. - * @param end An iterator specifying a range of end to erase. - * - * @return An iterator pointing to the element that followed the last element erased by the function call. - * This is the {@link end end()} if the operation erased the last element in the sequence. - */ - erase(begin: ListIterator, end: ListIterator): ListIterator; - /** - *

Erase an element.

- * - *

Removes from the {@link List} either a single element; position.

- * - *

This effectively reduces the container size by the number of element removed.

- * - *

Unlike other standard sequence containers, {@link List} objects are specifically designed to be - * efficient inserting and removing elements in any position, even in the middle of the sequence.

- * - * @param position Iterator pointing to a single element to be removed from the {@link List}. - * - * @return An iterator pointing to the element that followed the last element erased by the function call. - * This is the {@link rend rend()} if the operation erased the last element in the sequence. - */ - erase(position: ListReverseIterator): ListReverseIterator; - /** - *

Erase elements.

- * - *

Removes from the {@link List} container a range of elements.

- * - *

This effectively reduces the container {@link size} by the number of elements removed.

- * - *

Unlike other standard sequence containers, {@link List} objects are specifically designed to be - * efficient inserting and removing elements in any position, even in the middle of the sequence.

- * - * @param begin An iterator specifying a range of beginning to erase. - * @param end An iterator specifying a range of end to erase. - * - * @return An iterator pointing to the element that followed the last element erased by the function call. - * This is the {@link rend rend()} if the operation erased the last element in the sequence. - */ - erase(begin: ListReverseIterator, end: ListReverseIterator): ListReverseIterator; - /** - *

Remove duplicate values.

- * - *

Removes all but the first element from every consecutive group of equal elements in the

- * - *

Notice that an element is only removed from the {@link List} container if it compares equal to the - * element immediately preceding it. Thus, this function is especially useful for sorted lists.

- */ - unique(): void; - /** - *

Remove duplicate values.

- * - *

Removes all but the first element from every consecutive group of equal elements in the

- * - *

The argument binary_pred is a specific comparison function that determine the uniqueness - * of an element. In fact, any behavior can be implemented (and not only an equality comparison), but notice - * that the function will call binary_pred(it.value, it.prev().value) for all pairs of elements - * (where it is an iterator to an element, starting from the second) and remove it - * from the {@link List} if the predicate returns true. - * - *

Notice that an element is only removed from the {@link List} container if it compares equal to the - * element immediately preceding it. Thus, this function is especially useful for sorted lists.

- * - * @param binary_pred Binary predicate that, taking two values of the same type than those contained in the - * {@link List}, returns true to remove the element passed as first argument - * from the container, and false otherwise. This shall be a function pointer - * or a function object. - */ - unique(binary_pred: (left: T, right: T) => boolean): void; - /** - *

Remove elements with specific value.

- * - *

Removes from the container all the elements that compare equal to val. This calls the - * destructor of these objects and reduces the container {@link size} by the number of elements removed.

- * - *

Unlike member function {@link List.erase}, which erases elements by their position (using an - * iterator), this function ({@link List.remove}) removes elements by their value.

- * - *

A similar function, {@link List.remove_if}, exists, which allows for a condition other than an - * equality comparison to determine whether an element is removed.

- * - * @param val Value of the elements to be removed. - */ - remove(val: T): void; - /** - *

Remove elements fulfilling condition.

- * - *

Removes from the container all the elements for which pred returns true. This - * calls the destructor of these objects and reduces the container {@link size} by the number of elements - * removed.

- * - *

The function calls pred(it.value) for each element (where it is an iterator - * to that element). Any of the elements in the list for which this returns true, are removed - * from the

- * - * @param pred Unary predicate that, taking a value of the same type as those contained in the forward_list - * object, returns true for those values to be removed from the container, and - * false for those remaining. This can either be a function pointer or a function - * object. - */ - remove_if(pred: (val: T) => boolean): void; - /** - *

Merge sorted {@link List Lists}.

- * - *

Merges obj into the {@link List} by transferring all of its elements at their respective - * ordered positions into the container (both containers shall already be ordered). - *

- * - *

This effectively removes all the elements in obj (which becomes {@link empty}), and inserts - * them into their ordered position within container (which expands in {@link size} by the number of elements - * transferred). The operation is performed without constructing nor destroying any element: they are - * transferred, no matter whether obj is an lvalue or an rvalue, or whether the value_type supports - * move-construction or not.

- * - *

This function requires that the {@link List} containers have their elements already ordered by value - * ({@link less}) before the call. For an alternative on unordered {@link List Lists}, see - * {@link List.splice}.

- * - *

Assuming such ordering, each element of obj is inserted at the position that corresponds to its - * value according to the strict weak ordering defined by {@link less}. The resulting order of equivalent - * elements is stable (i.e., equivalent elements preserve the relative order they had before the call, and - * existing elements precede those equivalent inserted from obj).

- * - * The function does nothing if this == obj. - * - * @param obj A {@link List} object of the same type (i.e., with the same template parameters, T). - * Note that this function modifies obj no matter whether an lvalue or rvalue reference is - * passed. - */ - merge(obj: List): void; - /** - *

Merge sorted {@link List Lists}.

- * - *

Merges obj into the {@link List} by transferring all of its elements at their respective - * ordered positions into the container (both containers shall already be ordered). - *

- * - *

This effectively removes all the elements in obj (which becomes {@link empty}), and inserts - * them into their ordered position within container (which expands in {@link size} by the number of elements - * transferred). The operation is performed without constructing nor destroying any element: they are - * transferred, no matter whether obj is an lvalue or an rvalue, or whether the value_type supports - * move-construction or not.

- * - *

The argument compare is a specific predicate to perform the comparison operation between - * elements. This comparison shall produce a strict weak ordering of the elements (i.e., a consistent - * transitive comparison, without considering its reflexiveness). - * - *

This function requires that the {@link List} containers have their elements already ordered by - * compare before the call. For an alternative on unordered {@link List Lists}, see - * {@link List.splice}.

- * - *

Assuming such ordering, each element of obj is inserted at the position that corresponds to its - * value according to the strict weak ordering defined by compare. The resulting order of equivalent - * elements is stable (i.e., equivalent elements preserve the relative order they had before the call, and - * existing elements precede those equivalent inserted from obj).

- * - * The function does nothing if this == obj. - * - * @param obj A {@link List} object of the same type (i.e., with the same template parameters, T). - * Note that this function modifies obj no matter whether an lvalue or rvalue reference is - * passed. - * @param compare Binary predicate that, taking two values of the same type than those contained in the - * {@link list}, returns true if the first argument is considered to go before - * the second in the strict weak ordering it defines, and false otherwise. - * This shall be a function pointer or a function object. - */ - merge(obj: List, compare: (left: T, right: T) => boolean): void; - /** - *

Transfer elements from {@link List} to {@link List}.

- * - *

Transfers elements from obj into the container, inserting them at position.

- * - *

This effectively inserts all elements into the container and removes them from obj, altering - * the sizes of both containers. The operation does not involve the construction or destruction of any - * element. They are transferred, no matter whether obj is an lvalue or an rvalue, or whether the - * value_type supports move-construction or not.

- * - *

This first version (1) transfers all the elements of obj into the

- * - * @param position Position within the container where the elements of obj are inserted. - * @param obj A {@link List} object of the same type (i.e., with the same template parameters, T). - */ - splice(position: ListIterator, obj: List): void; - /** - *

Transfer an element from {@link List} to {@link List}.

- * - *

Transfers an element from obj, which is pointed by an {@link ListIterator iterator} it, - * into the container, inserting the element at specified position.

- * - *

This effectively inserts an element into the container and removes it from obj, altering the - * sizes of both containers. The operation does not involve the construction or destruction of any element. - * They are transferred, no matter whether obj is an lvalue or an rvalue, or whether the value_type - * supports move-construction or not.

- * - *

This second version (2) transfers only the element pointed by it from obj into the - *

- * - * @param position Position within the container where the element of obj is inserted. - * @param obj A {@link List} object of the same type (i.e., with the same template parameters, T). - * This parameter may be this if position points to an element not actually - * being spliced. - * @param it {@link ListIterator Iterator} to an element in obj. Only this single element is - * transferred. - */ - splice(position: ListIterator, obj: List, it: ListIterator): void; - /** - *

Transfer elements from {@link List} to {@link List}.

- * - *

Transfers elements from obj into the container, inserting them at position.

- * - *

This effectively inserts those elements into the container and removes them from obj, altering - * the sizes of both containers. The operation does not involve the construction or destruction of any - * element. They are transferred, no matter whether obj is an lvalue or an rvalue, or whether the - * value_type supports move-construction or not.

- * - *

This third version (3) transfers the range [begin, end) from obj into the - *

- * - * @param position Position within the container where the elements of obj are inserted. - * @param obj A {@link List} object of the same type (i.e., with the same template parameters, T). - * This parameter may be this if position points to an element not actually - * being spliced. - * @param begin {@link ListIterator An Iterator} specifying initial position of a range of elements in - * obj. Transfers the elements in the range [begin, end) to - * position. - * @param end {@link ListIterator An Iterator} specifying final position of a range of elements in - * obj. Transfers the elements in the range [begin, end) to - * position. Notice that the range includes all the elements between begin and - * end, including the element pointed by begin but not the one pointed by end. - */ - splice(position: ListIterator, obj: List, begin: ListIterator, end: ListIterator): void; - /** - *

Sort elements in

- * - *

Sorts the elements in the {@link List}, altering their position within the

- * - *

The sorting is performed by applying an algorithm that uses {@link less}. This comparison shall - * produce a strict weak ordering of the elements (i.e., a consistent transitive comparison, without - * considering its reflexiveness).

- * - *

The resulting order of equivalent elements is stable: i.e., equivalent elements preserve the relative - * order they had before the call.

- * - *

The entire operation does not involve the construction, destruction or copy of any element object. - * Elements are moved within the

- */ - sort(): void; - /** - *

Sort elements in

- * - *

Sorts the elements in the {@link List}, altering their position within the

- * - *

The sorting is performed by applying an algorithm that uses compare. This comparison shall - * produce a strict weak ordering of the elements (i.e., a consistent transitive comparison, without - * considering its reflexiveness).

- * - *

The resulting order of equivalent elements is stable: i.e., equivalent elements preserve the relative - * order they had before the call.

- * - *

The entire operation does not involve the construction, destruction or copy of any element object. - * Elements are moved within the

- * - * @param compare Binary predicate that, taking two values of the same type of those contained in the - * {@link List}, returns true if the first argument goes before the second - * argument in the strict weak ordering it defines, and false otherwise. This - * shall be a function pointer or a function object. - */ - sort(compare: (left: T, right: T) => boolean): void; - /** - * @hidden - */ - private qsort(first, last, compare); - /** - * @hidden - */ - private partition(first, last, compare); - /** - *

Swap content.

- * - *

Exchanges the content of the container by the content of obj, which is another - * {@link List container} object with same type of elements. Sizes and container type may differ.

- * - *

After the call to this member function, the elements in this container are those which were in obj - * before the call, and the elements of obj are those which were in this. All iterators, references and - * pointers remain valid for the swapped objects.

- * - *

Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that - * algorithm with an optimization that behaves like this member function.

- * - * @param obj Another {@link List container} of the same type of elements (i.e., instantiated - * with the same template parameter, T) whose content is swapped with that of this - * {@link container List}. - */ - swap(obj: List): void; - /** - * @inheritdoc - */ - swap(obj: base.IContainer): void; - } -} -declare namespace std { - /** - *

An iterator, node of a List.

- * - *

- * - *

- * - * @author Jeongho Nam - */ - class ListIterator extends base.ListIteratorBase { - /** - * Initializer Constructor. - * - * #### Note - * Do not create the iterator directly, by yourself. - * - * Use {@link List.begin begin()}, {@link List.end end()} in {@link List container} instead. - * - * @param source The source {@link List container} to reference. - * @param prev A refenrece of previous node ({@link ListIterator iterator}). - * @param next A refenrece of next node ({@link ListIterator iterator}). - * @param value Value to be stored in the node (iterator). - */ - constructor(source: List, prev: ListIterator, next: ListIterator, value: T); - /** - * @inheritdoc - */ - prev(): ListIterator; - /** - * @inheritdoc - */ - next(): ListIterator; - /** - * @inheritdoc - */ - advance(step: number): ListIterator; - /** - * @inheritdoc - */ - /** - * Set value of the iterator is pointing to. - * - * @param val Value to set. - */ - value: T; - /** - * @inheritdoc - */ - equals(obj: ListIterator): boolean; - /** - * @inheritdoc - */ - swap(obj: ListIterator): void; - } -} -declare namespace std { - /** - *

A reverse-iterator of List.

- * - *

- * - *

- * - * @param Type of the elements. - * - * @author Jeongho Nam - */ - class ListReverseIterator extends ReverseIterator, ListReverseIterator> implements base.ILinearIterator { - /** - * Construct from base iterator. - * - * @param base A reference of the base iterator, which iterates in the opposite direction. - */ - constructor(base: ListIterator); - /** - * @hidden - */ - protected _Create_neighbor(base: ListIterator): ListReverseIterator; - /** - * @inheritdoc - */ - /** - * Set value of the iterator is pointing to. - * - * @param val Value to set. - */ - value: T; - } -} -declare namespace std.Vector { - type iterator = std.VectorIterator; - type reverse_iterator = std.VectorReverseIterator; -} -declare namespace std { - /** - *

Vector, the dynamic array.

- * - *

{@link Vector}s are sequence containers representing arrays that can change in size.

- * - *

Just like arrays, {@link Vector}s use contiguous storage locations for their elements, which means that - * their elements can also be accessed using offsets on regular pointers to its elements, and just as efficiently - * as in arrays. But unlike arrays, their size can change dynamically, with their storage being handled - * automatically by the container.

- * - *

Internally, {@link Vector}s use a dynamically allocated array to store their elements. This array may need - * to be reallocated in order to grow in size when new elements are inserted, which implies allocating a new - * array and moving all elements to it. This is a relatively expensive task in terms of processing time, and - * thus, {@link Vector}s do not reallocate each time an element is added to the container.

- * - *

Instead, {@link Vector} containers may allocate some extra storage to accommodate for possible growth, and - * thus the container may have an actual {@link capacity} greater than the storage strictly needed to contain its - * elements (i.e., its {@link size}). Libraries can implement different strategies for growth to balance between - * memory usage and reallocations, but in any case, reallocations should only happen at logarithmically growing - * intervals of {@link size} so that the insertion of individual elements at the end of the {@link Vector} can be - * provided with amortized constant time complexity (see {@link push_back push_back()}).

- * - *

Therefore, compared to arrays, {@link Vector}s consume more memory in exchange for the ability to manage - * storage and grow dynamically in an efficient way.

- * - *

Compared to the other dynamic sequence containers ({@link Deque}s, {@link List}s), {@link Vector Vectors} - * are very efficient accessing its elements (just like arrays) and relatively efficient adding or removing - * elements from its end. For operations that involve inserting or removing elements at positions other than the - * end, they perform worse than the others, and have less consistent iterators and references than {@link List}s. - *

- * - *

- * - *

- * - *

Container properties

- *
- *
Sequence
- *
- * Elements in sequence containers are ordered in a strict linear sequence. Individual elements are - * accessed by their position in this sequence. - *
- * - *
Dynamic array
- *
- * Allows direct access to any element in the sequence, even through pointer arithmetics, and provides - * relatively fast addition/removal of elements at the end of the sequence. - *
- *
- * - * @param Type of the elements. - * - * @reference http://www.cplusplus.com/reference/vector/vector - * @author Jeongho Nam - */ - class Vector extends Array implements base.IContainer, base.IArrayContainer { - /** - * @hidden - */ - private end_; - /** - * @hidden - */ - private rend_; - /** - *

Default Constructor.

- * - *

Constructs an empty container, with no elements.

- */ - constructor(); - /** - * @inheritdoc - */ - constructor(array: Array); - /** - *

Initializer list Constructor.

- * - *

Constructs a container with a copy of each of the elements in array, in the same order.

- * - * @param array An array containing elements to be copied and contained. - */ - constructor(n: number); - /** - *

Fill Constructor.

- * - *

Constructs a container with n elements. Each element is a copy of val (if provided).

- * - * @param n Initial container size (i.e., the number of elements in the container at construction). - * @param val Value to fill the container with. Each of the n elements in the container is - * initialized to a copy of this value. - */ - constructor(n: number, val: T); - /** - *

Copy Constructor.

- * - *

Constructs a container with a copy of each of the elements in container, in the same order.

- * - * @param container Another container object of the same type (with the same class template - * arguments T), whose contents are either copied or acquired. - */ - constructor(container: Vector); - /** - *

Range Constructor.

- * - *

Constructs a container with as many elements as the range (begin, end), with each - * element emplace-constructed from its corresponding element in that range, in the same order.

- * - * @param begin Input interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - */ - constructor(begin: Iterator, end: Iterator); - /** - * @inheritdoc - */ - assign>(begin: InputIterator, end: InputIterator): void; - /** - * @inheritdoc - */ - assign(n: number, val: T): void; - /** - * @inheritdoc - */ - reserve(size: number): void; - /** - * @inheritdoc - */ - clear(): void; - /** - * @inheritdoc - */ - begin(): VectorIterator; - /** - * @inheritdoc - */ - end(): VectorIterator; - /** - * @inheritdoc - */ - rbegin(): VectorReverseIterator; - /** - * @inheritdoc - */ - rend(): VectorReverseIterator; - /** - * @inheritdoc - */ - size(): number; - /** - * @inheritdoc - */ - capacity(): number; - /** - * @inheritdoc - */ - empty(): boolean; - /** - * @inheritdoc - */ - at(index: number): T; - /** - * @inheritdoc - */ - set(index: number, val: T): T; - /** - * @inheritdoc - */ - front(): T; - /** - * @inheritdoc - */ - back(): T; - /** - * @inheritdoc - */ - push_back(val: T): void; - /** - *

Insert an element.

- * - *

The {@link Vector} is extended by inserting new element before the element at the specified - * position, effectively increasing the container size by one.

- * - *

This causes an automatic reallocation of the allocated storage space if -and only if- the new - * {@link size} surpasses the current {@link capacity}.

- * - *

Because {@link Vector}s use an Array as their underlying storage, inserting element in - * positions other than the {@link end end()} causes the container to relocate all the elements that were - * after position to its new position. This is generally an inefficient operation compared to the one - * performed for the same operation by other kinds of sequence containers (such as {@link List}).

- * - * @param position Position in the {@link Vector} where the new element is inserted. - * {@link iterator} is a member type, defined as a - * {@link VectorIterator random access iterator} type that points to elements. - * @param val Value to be copied to the inserted element. - * - * @return An iterator that points to the newly inserted element. - */ - insert(position: VectorIterator, val: T): VectorIterator; - /** - *

Insert elements by repeated filling.

- * - *

The {@link Vector} is extended by inserting new elements before the element at the specified - * position, effectively increasing the container size by the number of elements inserted.

- * - *

This causes an automatic reallocation of the allocated storage space if -and only if- the new - * {@link size} surpasses the current {@link capacity}.

- * - *

Because {@link Vector}s use an Array as their underlying storage, inserting elements in - * positions other than the {@link end end()} causes the container to relocate all the elements that were - * after position to their new positions. This is generally an inefficient operation compared to the - * one performed for the same operation by other kinds of sequence containers (such as {@link List}). - * - * @param position Position in the {@link Vector} where the new elements are inserted. - * {@link iterator} is a member type, defined as a - * {@link VectorIterator random access iterator} type that points to elements. - * @param n Number of elements to insert. Each element is initialized to a copy of val. - * @param val Value to be copied (or moved) to the inserted elements. - * - * @return An iterator that points to the first of the newly inserted elements. - */ - insert(position: VectorIterator, n: number, val: T): VectorIterator; - /** - *

Insert elements by range iterators.

- * - *

The {@link Vector} is extended by inserting new elements before the element at the specified - * position, effectively increasing the container size by the number of elements inserted by range - * iterators.

- * - *

This causes an automatic reallocation of the allocated storage space if -and only if- the new - * {@link size} surpasses the current {@link capacity}.

- * - *

Because {@link Vector}s use an Array as their underlying storage, inserting elements in - * positions other than the {@link end end()} causes the container to relocate all the elements that were - * after position to their new positions. This is generally an inefficient operation compared to the - * one performed for the same operation by other kinds of sequence containers (such as {@link List}). - * - * @param position Position in the {@link Vector} where the new elements are inserted. - * {@link iterator} is a member type, defined as a - * {@link VectorIterator random access iterator} type that points to elements. - * @param begin Input interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - * - * @return An iterator that points to the first of the newly inserted elements. - */ - insert>(position: VectorIterator, begin: InputIterator, end: InputIterator): VectorIterator; - /** - *

Insert an element.

- * - *

The {@link Vector} is extended by inserting new element before the element at the specified - * position, effectively increasing the container size by one.

- * - *

This causes an automatic reallocation of the allocated storage space if -and only if- the new - * {@link size} surpasses the current {@link capacity}.

- * - *

Because {@link Vector}s use an Array as their underlying storage, inserting element in - * positions other than the {@link end end()} causes the container to relocate all the elements that were - * after position to its new position. This is generally an inefficient operation compared to the one - * performed for the same operation by other kinds of sequence containers (such as {@link List}).

- * - * @param position Position in the {@link Vector} where the new element is inserted. - * {@link iterator} is a member type, defined as a - * {@link VectorIterator random access iterator} type that points to elements. - * @param val Value to be copied to the inserted element. - * - * @return An iterator that points to the newly inserted element. - */ - insert(position: VectorReverseIterator, val: T): VectorReverseIterator; - /** - *

Insert elements by repeated filling.

- * - *

The {@link Vector} is extended by inserting new elements before the element at the specified - * position, effectively increasing the container size by the number of elements inserted.

- * - *

This causes an automatic reallocation of the allocated storage space if -and only if- the new - * {@link size} surpasses the current {@link capacity}.

- * - *

Because {@link Vector}s use an Array as their underlying storage, inserting elements in - * positions other than the {@link end end()} causes the container to relocate all the elements that were - * after position to their new positions. This is generally an inefficient operation compared to the - * one performed for the same operation by other kinds of sequence containers (such as {@link List}). - * - * @param position Position in the {@link Vector} where the new elements are inserted. - * {@link iterator} is a member type, defined as a - * {@link VectorIterator random access iterator} type that points to elements. - * @param n Number of elements to insert. Each element is initialized to a copy of val. - * @param val Value to be copied (or moved) to the inserted elements. - * - * @return An iterator that points to the first of the newly inserted elements. - */ - insert(position: VectorReverseIterator, n: number, val: T): VectorReverseIterator; - /** - *

Insert elements by range iterators.

- * - *

The {@link Vector} is extended by inserting new elements before the element at the specified - * position, effectively increasing the container size by the number of elements inserted by range - * iterators.

- * - *

This causes an automatic reallocation of the allocated storage space if -and only if- the new - * {@link size} surpasses the current {@link capacity}.

- * - *

Because {@link Vector}s use an Array as their underlying storage, inserting elements in - * positions other than the {@link end end()} causes the container to relocate all the elements that were - * after position to their new positions. This is generally an inefficient operation compared to the - * one performed for the same operation by other kinds of sequence containers (such as {@link List}). - * - * @param position Position in the {@link Vector} where the new elements are inserted. - * {@link iterator} is a member type, defined as a - * {@link VectorIterator random access iterator} type that points to elements. - * @param begin Input interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - * - * @return An iterator that points to the first of the newly inserted elements. - */ - insert>(position: VectorReverseIterator, begin: InputIterator, end: InputIterator): VectorReverseIterator; - /** - * @hidden - */ - private insert_by_val(position, val); - /** - * @hidden - */ - protected _Insert_by_repeating_val(position: VectorIterator, n: number, val: T): VectorIterator; - /** - * @hidden - */ - protected _Insert_by_range>(position: VectorIterator, first: InputIterator, last: InputIterator): VectorIterator; - /** - * @inheritdoc - */ - pop_back(): void; - /** - *

Erase element.

- * - *

Removes from the {@link Vector} either a single element; position.

- * - *

This effectively reduces the container size by the number of element removed.

- * - *

Because {@link Vector}s use an Array as their underlying storage, erasing an element in - * position other than the {@link end end()} causes the container to relocate all the elements after the - * segment erased to their new positions. This is generally an inefficient operation compared to the one - * performed for the same operation by other kinds of sequence containers (such as {@link List}).

- * - * @param position Iterator pointing to a single element to be removed from the {@link Vector}. - * - * @return An iterator pointing to the new location of the element that followed the last element erased by - * the function call. This is the {@link end end()} if the operation erased the last element in the - * sequence. - */ - erase(position: VectorIterator): VectorIterator; - /** - *

Erase element.

- * - *

Removes from the Vector either a single element; position.

- * - *

This effectively reduces the container size by the number of elements removed.

- * - *

Because {@link Vector}s use an Array as their underlying storage, erasing elements in - * position other than the {@link end end()} causes the container to relocate all the elements after the - * segment erased to their new positions. This is generally an inefficient operation compared to the one - * performed for the same operation by other kinds of sequence containers (such as {@link List}).

- * - * @param begin An iterator specifying a range of beginning to erase. - * @param end An iterator specifying a range of end to erase. - * - * @return An iterator pointing to the new location of the element that followed the last element erased by - * the function call. This is the {@link rend rend()} if the operation erased the last element in the - * sequence. - */ - erase(first: VectorIterator, last: VectorIterator): VectorIterator; - /** - *

Erase element.

- * - *

Removes from the {@link Vector} either a single element; position.

- * - *

This effectively reduces the container size by the number of element removed.

- * - *

Because {@link Vector}s use an Array as their underlying storage, erasing an element in - * position other than the {@link end end()} causes the container to relocate all the elements after the - * segment erased to their new positions. This is generally an inefficient operation compared to the one - * performed for the same operation by other kinds of sequence containers (such as {@link List}).

- * - * @param position Iterator pointing to a single element to be removed from the {@link Vector}. - * - * @return An iterator pointing to the new location of the element that followed the last element erased by - * the function call. This is the {@link rend rend()} if the operation erased the last element in the - * sequence. - */ - erase(position: VectorReverseIterator): VectorReverseIterator; - /** - *

Erase element.

- * - *

Removes from the Vector either a single element; position.

- * - *

This effectively reduces the container size by the number of elements removed.

- * - *

Because {@link Vector}s use an Array as their underlying storage, erasing elements in - * position other than the {@link end end()} causes the container to relocate all the elements after the - * segment erased to their new positions. This is generally an inefficient operation compared to the one - * performed for the same operation by other kinds of sequence containers (such as {@link List}).

- * - * @param begin An iterator specifying a range of beginning to erase. - * @param end An iterator specifying a range of end to erase. - * - * @return An iterator pointing to the new location of the element that followed the last element erased by - * the function call. This is the {@link end end()} if the operation erased the last element in the - * sequence. - */ - erase(first: VectorReverseIterator, last: VectorReverseIterator): VectorReverseIterator; - /** - * @hidden - */ - protected _Erase_by_range(first: VectorIterator, last: VectorIterator): VectorIterator; - /** - *

Swap content.

- * - *

Exchanges the content of the container by the content of obj, which is another - * {@link Vector container} object with same type of elements. Sizes and container type may differ.

- * - *

After the call to this member function, the elements in this container are those which were in obj - * before the call, and the elements of obj are those which were in this. All iterators, references and - * pointers remain valid for the swapped objects.

- * - *

Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that - * algorithm with an optimization that behaves like this member function.

- * - * @param obj Another {@link Vector container} of the same type of elements (i.e., instantiated - * with the same template parameter, T) whose content is swapped with that of this - * {@link container Vector}. - */ - swap(obj: Vector): void; - /** - * @inheritdoc - */ - swap(obj: base.IContainer): void; - } -} -declare namespace std { - /** - *

An iterator of Vector.

- * - *

- * - *

- * - * @param Type of the elements. - * - * @author Jeongho Nam - */ - class VectorIterator extends Iterator implements base.IArrayIterator { - /** - * Sequence number of iterator in the source {@link Vector}. - */ - private index_; - /** - *

Construct from the source {@link Vector container}.

- * - *

Note

- *

Do not create the iterator directly, by yourself.

- *

Use {@link Vector.begin begin()}, {@link Vector.end end()} in {@link Vector container} instead.

- * - * @param source The source {@link Vector container} to reference. - * @param index Sequence number of the element in the source {@link Vector}. - */ - constructor(source: Vector, index: number); - /** - * @hidden - */ - private readonly vector; - /** - * @inheritdoc - */ - /** - * Set value of the iterator is pointing to. - * - * @param val Value to set. - */ - value: T; - /** - * Get index. - */ - readonly index: number; - /** - * @inheritdoc - */ - prev(): VectorIterator; - /** - * @inheritdoc - */ - next(): VectorIterator; - /** - * @inheritdoc - */ - advance(n: number): VectorIterator; - /** - * @inheritdoc - */ - equals(obj: VectorIterator): boolean; - /** - * @inheritdoc - */ - swap(obj: VectorIterator): void; - toString(): number; - } -} -declare namespace std { - /** - *

A reverse-iterator of Vector.

- * - *

- * - *

- * - * @param Type of the elements. - * - * @author Jeongho Nam - */ - class VectorReverseIterator extends ReverseIterator, VectorReverseIterator> implements base.IArrayIterator { - /** - * Construct from base iterator. - * - * @param base A reference of the base iterator, which iterates in the opposite direction. - */ - constructor(base: VectorIterator); - /** - * @hidden - */ - protected _Create_neighbor(base: VectorIterator): VectorReverseIterator; - /** - * @inheritdoc - */ - /** - * Set value of the iterator is pointing to. - * - * @param val Value to set. - */ - value: T; - /** - * Get index. - */ - readonly index: number; - } -} -declare namespace std { - /** - *

FIFO queue.

- * - *

{@link Queue}s are a type of container adaptor, specifically designed to operate in a FIFO context - * (first-in first-out), where elements are inserted into one end of the container and extracted from the other. - *

- * - *

{@link Queue}s are implemented as containers adaptors, which are classes that use an encapsulated object of - * a specific container class as its underlying container, providing a specific set of member functions to access - * its elements. Elements are pushed into the {@link IDeque.back back()} of the specific container and popped from - * its {@link IDeque.front front()}.

- * - *

{@link container_ The underlying container} may be one of the standard container class template or some - * other specifically designed container class. This underlying container shall support at least the following - * operations:

- * - *
    - *
  • empty
  • - *
  • size
  • - *
  • front
  • - *
  • back
  • - *
  • push_back
  • - *
  • pop_front
  • - *
- * - *

The standard container classes {@link Deque} and {@link List} fulfill these requirements. - * By default, if no container class is specified for a particular {@link Queue} class instantiation, the standard - * container {@link List} is used.

- * - *

- * - *

- * - * @param Type of elements. - * - * @reference http://www.cplusplus.com/reference/queue/queue - * @author Jeongho Nam - */ - class Queue { - /** - * The underlying object for implementing the FIFO - */ - private container_; - /** - * Default Constructor. - */ - constructor(); - /** - * Copy Constructor. - */ - constructor(container: Queue); - /** - *

Return size.

- *

Returns the number of elements in the {@link Queue}.

- * - *

This member function effectively calls member {@link IDeque.size size()} of the - * {@link container_ underlying container} object.

- * - * @return The number of elements in the {@link container_ underlying container}. - */ - size(): number; - /** - *

Test whether container is empty.

- *

returns whether the {@link Queue} is empty: i.e. whether its size is zero.

- * - *

This member function efeectively calls member {@link IDeque.empty empty()} of the - * {@link container_ underlying container} object.

- * - * @return true if the {@link container_ underlying container}'s size is 0, - * false otherwise.

- */ - empty(): boolean; - /** - *

Access next element.

- *

Returns a value of the next element in the {@link Queue}.

- * - *

The next element is the "oldest" element in the {@link Queue} and the same element that is popped out - * from the queue when {@link pop Queue.pop()} is called.

- * - *

This member function effectively calls member {@link IDeque.front front()} of the - * {@link container_ underlying container} object.

- * - * @return A value of the next element in the {@link Queue}. - */ - front(): T; - /** - *

Access last element.

- * - *

Returns a vaue of the last element in the queue. This is the "newest" element in the queue (i.e. the - * last element pushed into the queue).

- * - *

This member function effectively calls the member function {@link IDeque.back back()} of the - * {@link container_ underlying container} object.

- * - * @return A value of the last element in the {@link Queue}. - */ - back(): T; - /** - *

Insert element.

- * - *

Inserts a new element at the end of the {@link Queue}, after its current last element. - * The content of this new element is initialized to val.

- * - *

This member function effectively calls the member function {@link IDeque.push_back push_back()} of the - * {@link container_ underlying container} object.

- * - * @param val Value to which the inserted element is initialized. - */ - push(val: T): void; - /** - *

Remove next element.

- * - *

Removes the next element in the {@link Queue}, effectively reducing its size by one.

- * - *

The element removed is the "oldest" element in the {@link Queue} whose value can be retrieved by calling - * member {@link front Queue.front()}

. - * - *

This member function effectively calls the member function {@link IDeque.pop_front pop_front()} of the - * {@link container_ underlying container} object.

- */ - pop(): void; - /** - *

Swap contents.

- * - *

Exchanges the contents of the container adaptor (this) by those of obj.

- * - *

This member function calls the non-member function {@link IContainer.swap swap} (unqualified) to swap - * the {@link container_ underlying containers}.

- * - * @param obj Another {@link Queue} container adaptor of the same type (i.e., instantiated with the same - * template parameter, T). Sizes may differ.

- */ - swap(obj: Queue): void; - } -} -declare namespace std { - /** - *

Priority queue.

- * - *

{@link PriorityQueue Priority queues} are a type of container adaptors, specifically designed such that its - * first element is always the greatest of the elements it contains, according to some strict weak ordering - * criterion.

- * - *

This context is similar to a heap, where elements can be inserted at any moment, and only the - * max heap element can be retrieved (the one at the top in the {@link PriorityQueue priority queue}).

- * - *

{@link PriorityQueue Priority queues} are implemented as container adaptors, which are classes that - * use an encapsulated object of a specific container class as its {@link container_ underlying container}, - * providing a specific set of member functions to access its elements. Elements are popped from the "back" - * of the specific container, which is known as the top of the {@link PriorityQueue Priority queue}.

- * - *

The {@link container_ underlying container} may be any of the standard container class templates or some - * other specifically designed container class. The container shall be accessible through - * {@link IArrayIterator random access iterators} and support the following operations:

- * - *
    - *
  • empty()
  • - *
  • size()
  • - *
  • front()
  • - *
  • push_back()
  • - *
  • pop_back()
  • - *
- * - *

The standard container classes {@link Vector} and {@link Deque} fulfill these requirements. By default, if - * no container class is specified for a particular {@link PriorityQueue} class instantiation, the standard - * container {@link Vector} is used.

- * - *

Support of {@link IArrayIterator random access iterators} is required to keep a heap structure internally - * at all times. This is done automatically by the container adaptor by automatically calling the algorithm - * functions make_heap, push_heap and pop_heap when needed.

- * - * @param Type of the elements. - * - * @reference http://www.cplusplus.com/reference/queue/priority_queue/ - * @author Jeongho Nam - */ - class PriorityQueue { - /** - *

The underlying container for implementing the priority queue.

- * - *

Following standard definition from the C++ committee, the underlying container should be one of - * {@link Vector} or {@link Deque}, however, I've adopted {@link TreeMultiSet} instead of them. Of course, - * there are proper reasons for adapting the {@link TreeMultiSet} even violating standard advice.

- * - *

Underlying container of {@link PriorityQueue} must keep a condition; the highest (or lowest) - * element must be placed on the terminal node for fast retrieval and deletion. To keep the condition with - * {@link Vector} or {@link Deque}, lots of times will only be spent for re-arranging elements. It calls - * rearrangement functions like make_heap, push_heap and pop_head for rearrangement.

- * - *

However, the {@link TreeMultiSet} container always keeps arrangment automatically without additional - * operations and it even meets full criteria of {@link PriorityQueue}. Those are the reason why I've adopted - * {@link TreeMultiSet} as the underlying container of {@link PriorityQueue}.

- */ - private container_; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from compare. - * - * @param compare A binary predicate determines order of elements. - */ - constructor(compare: (left: T, right: T) => boolean); - /** - * Contruct from elements. - * - * @param array Elements to be contained. - */ - constructor(array: Array); - /** - * Contruct from elements with compare. - * - * @param array Elements to be contained. - * @param compare A binary predicate determines order of elements. - */ - constructor(array: Array, compare: (left: T, right: T) => boolean); - /** - * Copy Constructor. - */ - constructor(container: base.IContainer); - /** - * Copy Constructor with compare. - * - * @param container A container to be copied. - * @param compare A binary predicate determines order of elements. - */ - constructor(container: base.IContainer, compare: (left: T, right: T) => boolean); - /** - * Range Constructor. - * - * @param begin Input interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - */ - constructor(begin: Iterator, end: Iterator); - /** - * Range Constructor with compare. - * - * @param begin Input interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - * @param compare A binary predicate determines order of elements. - */ - constructor(begin: Iterator, end: Iterator, compare: (left: T, right: T) => boolean); - /** - *

Return size.

- * - *

Returns the number of elements in the {@link PriorityQueue}.

- * - *

This member function effectively calls member {@link IArray.size size} of the - * {@link container_ underlying container} object.

- * - * @return The number of elements in the underlying - */ - size(): number; - /** - *

Test whether container is empty.

- * - *

Returns whether the {@link PriorityQueue} is empty: i.e. whether its {@link size} is zero.

- * - *

This member function effectively calls member {@link IARray.empty empty} of the - * {@link container_ underlying container} object.

- */ - empty(): boolean; - /** - *

Access top element.

- * - *

Returns a constant reference to the top element in the {@link PriorityQueue}.

- * - *

The top element is the element that compares higher in the {@link PriorityQueue}, and the next that is - * removed from the container when {@link PriorityQueue.pop} is called.

- * - *

This member function effectively calls member {@link IArray.front front} of the - * {@link container_ underlying container} object.

- * - * @return A reference to the top element in the {@link PriorityQueue}. - */ - top(): T; - /** - *

Insert element.

- * - *

Inserts a new element in the {@link PriorityQueue}. The content of this new element is initialized to - * val. - * - *

This member function effectively calls the member function {@link IArray.push_back push_back} of the - * {@link container_ underlying container} object, and then reorders it to its location in the heap by calling - * the push_heap algorithm on the range that includes all the elements of the

- * - * @param val Value to which the inserted element is initialized. - */ - push(val: T): void; - /** - *

Remove top element.

- * - *

Removes the element on top of the {@link PriorityQueue}, effectively reducing its {@link size} by one. - * The element removed is the one with the highest (or lowest) value.

- * - *

The value of this element can be retrieved before being popped by calling member - * {@link PriorityQueue.top}.

- * - *

This member function effectively calls the pop_heap algorithm to keep the heap property of - * {@link PriorityQueue PriorityQueues} and then calls the member function {@link IArray.pop_back pop_back} of - * the {@link container_ underlying container} object to remove the element.

- */ - pop(): void; - /** - *

Swap contents.

- * - *

Exchanges the contents of the container adaptor by those of obj, swapping both the - * {@link container_ underlying container} value and their comparison function using the corresponding - * {@link std.swap swap} non-member functions (unqualified).

- * - *

This member function has a noexcept specifier that matches the combined noexcept of the - * {@link IArray.swap swap} operations on the {@link container_ underlying container} and the comparison - * functions.

- * - * @param obj {@link PriorityQueue} container adaptor of the same type (i.e., instantiated with the same - * template parameters, T). Sizes may differ. - */ - swap(obj: PriorityQueue): void; - } -} -declare namespace std { - /** - *

LIFO stack.

- * - *

{@link Stack}s are a type of container adaptor, specifically designed to operate in a LIFO context - * (last-in first-out), where elements are inserted and extracted only from one end of the

- * - *

{@link Stack}s are implemented as containers adaptors, which are classes that use an encapsulated object of - * a specific container class as its underlying container, providing a specific set of member functions to - * access its elements. Elements are pushed/popped from the {@link ILinearContainer.back back()} of the - * {@link ILinearContainer specific container}, which is known as the top of the {@link Stack}.

- * - *

{@link container_ The underlying container} may be any of the standard container class templates or some - * other specifically designed container class. The container shall support the following operations:

- * - *
    - *
  • empty
  • - *
  • size
  • - *
  • front
  • - *
  • back
  • - *
  • push_back
  • - *
  • pop_back
  • - *
- * - *

The standard container classes {@link Vector}, {@link Deque} and {@link List} fulfill these requirements. - * By default, if no container class is specified for a particular {@link Stack} class instantiation, the standard - * container {@link List} is used.

- * - *

- * - *

- * - * @param Type of elements. - * - * @reference http://www.cplusplus.com/reference/stack/stack - * @author Jeongho Nam - */ - class Stack { - /** - * The underlying object for implementing the LIFO - */ - private container_; - /** - * Default Constructor. - */ - constructor(); - /** - * Copy Constructor. - */ - constructor(stack: Stack); - /** - *

Return size.

- * - *

Returns the number of elements in the {@link Stack}.

- * - *

This member function effectively calls member {@link ILinearContainer.size size()} of the - * {@link container_ underlying container} object.

- * - * @return The number of elements in the {@link container_ underlying container}. - */ - size(): number; - /** - *

Test whether container is empty.

- * - *

returns whether the {@link Stack} is empty: i.e. whether its size is zero.

- * - *

This member function effectively calls member {@link ILinearContainer.empty empty()} of the - * {@link container_ underlying container} object.

- * - * @return true if the underlying container's size is 0, - * false otherwise.

- */ - empty(): boolean; - /** - *

Access next element.

- * - *

Returns a value of the top element in the {@link Stack}

. - * - *

Since {@link Stack}s are last-in first-out containers, the top element is the last element inserted into - * the {@link Stack}.

- * - *

This member function effectively calls member {@link ILinearContainer.back back()} of the - * {@link container_ underlying container} object.

- * - * @return A value of the top element in the {@link Stack}. - */ - top(): T; - /** - *

Insert element.

- * - *

Inserts a new element at the top of the {@link Stack}, above its current top element.

- * - *

This member function effectively calls the member function - * {@link ILinearContainer.push_back push_back()} of the {@link container_ underlying container} object.

- * - * @param val Value to which the inserted element is initialized. - */ - push(val: T): void; - /** - *

Remove top element.

- * - *

Removes the element on top of the {@link Stack}, effectively reducing its size by one.

- * - *

The element removed is the latest element inserted into the {@link Stack}, whose value can be retrieved - * by calling member {@link top Stack.top()}

. - * - *

This member function effectively calls the member function {@link ILinearContainer.pop_back pop_back()} - * of the {@link container_ underlying container} object.

- */ - pop(): void; - /** - *

Swap contents.

- * - *

Exchanges the contents of the container adaptor (this) by those of obj.

- * - *

This member function calls the non-member function {@link IContainer.swap swap} (unqualified) to swap - * the {@link container_ underlying containers}.

- * - * @param obj Another {@link Stack} container adaptor of the same type (i.e., instantiated with the same - * template parameter, T). Sizes may differ.

- */ - swap(obj: Stack): void; - } -} -declare namespace std.TreeSet { - type iterator = std.SetIterator; - type reverse_iterator = std.SetReverseIterator; -} -declare namespace std { - /** - *

Tree-structured set, std::set of STL.

- * - *

{@link TreeSet}s are containers that store unique elements following a specific order.

- * - *

In a {@link TreeSet}, the value of an element also identifies it (the value is itself the - * key, of type T), and each value must be unique. The value of the elements in a - * {@link TreeSet} cannot be modified once in the container (the elements are always const), but they - * can be inserted or removed from the container.

- * - *

Internally, the elements in a {@link TreeSet} are always sorted following a specific strict weak - * ordering criterion indicated by its internal comparison method (of {@link less}).

- * - *

{@link TreeSet} containers are generally slower than {@link HashSet} containers to access - * individual elements by their key, but they allow the direct iteration on subsets based on their - * order.

- * - *

{@link TreeSet}s are typically implemented as binary search trees.

- * - *

- *

- * - *

Container properties

- *
- *
Associative
- *
- * Elements in associative containers are referenced by their key and not by their absolute - * position in the container. - *
- * - *
Ordered
- *
- * The elements in the container follow a strict order at all times. All inserted elements are - * given a position in this order. - *
- * - *
Set
- *
The value of an element is also the key used to identify it.
- * - *
Unique keys
- *
No two elements in the container can have equivalent keys.
- *
- * - * @param Type of the elements. - * Each element in an {@link TreeSet} is also uniquely identified by this value. - * - * @reference http://www.cplusplus.com/reference/set/set - * @author Jeongho Nam - */ - class TreeSet extends base.UniqueSet implements base.ITreeSet { - /** - * @hidden - */ - private tree_; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from compare. - * - * @param compare A binary predicate determines order of elements. - */ - constructor(compare: (x: T, y: T) => boolean); - /** - * Contruct from elements. - * - * @param array Elements to be contained. - */ - constructor(array: Array); - /** - * Contruct from elements with compare. - * - * @param array Elements to be contained. - * @param compare A binary predicate determines order of elements. - */ - constructor(array: Array, compare: (x: T, y: T) => boolean); - /** - * Copy Constructor. - */ - constructor(container: TreeMultiSet); - /** - * Copy Constructor with compare. - * - * @param container A container to be copied. - * @param compare A binary predicate determines order of elements. - */ - constructor(container: TreeMultiSet, compare: (x: T, y: T) => boolean); - /** - * Range Constructor. - * - * @param begin Input interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - */ - constructor(begin: Iterator, end: Iterator); - /** - * Construct from range and compare. - * - * @param begin Input interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - * @param compare A binary predicate determines order of elements. - */ - constructor(begin: Iterator, end: Iterator, compare: (x: T, y: T) => boolean); - /** - * @inheritdoc - */ - clear(): void; - /** - * @inheritdoc - */ - find(val: T): SetIterator; - /** - * @inheritdoc - */ - key_comp(): (x: T, y: T) => boolean; - /** - * @inheritdoc - */ - value_comp(): (x: T, y: T) => boolean; - /** - * @inheritdoc - */ - lower_bound(val: T): SetIterator; - /** - * @inheritdoc - */ - upper_bound(val: T): SetIterator; - /** - * @inheritdoc - */ - equal_range(val: T): Pair, SetIterator>; - /** - * @hidden - */ - protected _Insert_by_val(val: T): any; - protected _Insert_by_hint(hint: SetIterator, val: T): SetIterator; - /** - * @hidden - */ - protected _Insert_by_range>(first: InputIterator, last: InputIterator): void; - /** - * @inheritdoc - */ - protected _Handle_insert(first: SetIterator, last: SetIterator): void; - /** - * @inheritdoc - */ - protected _Handle_erase(first: SetIterator, last: SetIterator): void; - /** - *

Swap content.

- * - *

Exchanges the content of the container by the content of obj, which is another - * {@link TreeSet set} of the same type. Sizes abd container type may differ.

- * - *

After the call to this member function, the elements in this container are those which were - * in obj before the call, and the elements of obj are those which were in this. All - * iterators, references and pointers remain valid for the swapped objects.

- * - *

Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that - * algorithm with an optimization that behaves like this member function.

- * - * @param obj Another {@link TreeSet set container} of the same type of elements as this (i.e., - * with the same template parameters, Key and T) whose content is swapped - * with that of this {@link TreeSet container}. - */ - swap(obj: TreeSet): void; - /** - * @inheritdoc - */ - swap(obj: base.IContainer): void; - } -} -declare namespace std.TreeMap { - type iterator = std.MapIterator; - type reverse_iterator = std.MapReverseIterator; -} -declare namespace std { - /** - *

Tree-structured map, std::map of STL.

- * - *

{@link TreeMap TreeMaps} are associative containers that store elements formed by a combination of a - * key value (Key) and a mapped value (T), following order.

- * - *

In a {@link TreeMap}, the key values are generally used to sort and uniquely identify the elements, - * while the mapped values store the content associated to this key. The types of key and - * mapped value may differ, and are grouped together in member type value_type, which is a {@link Pair} - * type combining both:

- * - *

typedef Pair value_type;

- * - *

Internally, the elements in a {@link TreeMap} are always sorted by its key following a - * strict weak ordering criterion indicated by its internal comparison method {@link less}. - * - *

{@link TreeMap} containers are generally slower than {@link HashMap HashMap} containers to access individual - * elements by their key, but they allow the direct iteration on subsets based on their order.

- * - *

{@link TreeMap}s are typically implemented as binary search trees.

- * - *

- *

- * - *

Container properties

- *
- *
Associative
- *
Elements in associative containers are referenced by their key and not by their absolute - * position in the container.
- * - *
Ordered
- *
The elements in the container follow a strict order at all times. All inserted elements are - * given a position in this order.
- * - *
Map
- *
Each element associates a key to a mapped value: - * Keys are meant to identify the elements whose main content is the mapped value.
- * - *
Unique keys
- *
No two elements in the container can have equivalent keys.
- *
- * - * @param Type of the keys. Each element in a map is uniquely identified by its key value. - * @param Type of the mapped value. Each element in a map stores some data as its mapped value. - * - * @reference http://www.cplusplus.com/reference/map/map - * @author Jeongho Nam - */ - class TreeMap extends base.UniqueMap implements base.ITreeMap { - /** - * @hidden - */ - private tree_; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from compare. - * - * @param compare A binary predicate determines order of elements. - */ - constructor(compare: (x: Key, y: Key) => boolean); - /** - * Contruct from elements. - * - * @param array Elements to be contained. - */ - constructor(array: Array>); - /** - * Contruct from elements. - * - * @param array Elements to be contained. - * @param compare A binary predicate determines order of elements. - */ - constructor(array: Array>, compare: (x: Key, y: Key) => boolean); - /** - * Contruct from tuples. - * - * @param array Tuples to be contained. - */ - constructor(array: Array<[Key, T]>); - /** - * Contruct from tuples. - * - * @param array Tuples to be contained. - * @param compare A binary predicate determines order of elements. - */ - constructor(array: Array<[Key, T]>, compare: (x: Key, y: Key) => boolean); - /** - * Copy Constructor. - * - * @param container Another map to copy. - */ - constructor(container: TreeMap); - /** - * Copy Constructor. - * - * @param container Another map to copy. - * @param compare A binary predicate determines order of elements. - */ - constructor(container: TreeMap, compare: (x: Key, y: Key) => boolean); - /** - * Range Constructor. - * - * @param begin nput interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - */ - constructor(begin: Iterator>, end: Iterator>); - /** - * Range Constructor. - * - * @param begin nput interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - * @param compare A binary predicate determines order of elements. - */ - constructor(begin: Iterator>, end: Iterator>, compare: (x: Key, y: Key) => boolean); - /** - * @inheritdoc - */ - clear(): void; - /** - * @inheritdoc - */ - find(key: Key): MapIterator; - /** - * @inheritdoc - */ - key_comp(): (x: Key, y: Key) => boolean; - /** - * @inheritdoc - */ - value_comp(): (x: Pair, y: Pair) => boolean; - /** - * @inheritdoc - */ - lower_bound(key: Key): MapIterator; - /** - * @inheritdoc - */ - upper_bound(key: Key): MapIterator; - /** - * @inheritdoc - */ - equal_range(key: Key): Pair, MapIterator>; - /** - * @hidden - */ - protected _Insert_by_pair(pair: Pair): any; - /** - * @hidden - */ - protected _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; - /** - * @hidden - */ - protected _Insert_by_range>>(first: InputIterator, last: InputIterator): void; - /** - * @inheritdoc - */ - protected _Handle_insert(first: MapIterator, last: MapIterator): void; - /** - * @inheritdoc - */ - protected _Handle_erase(first: MapIterator, last: MapIterator): void; - /** - *

Swap content.

- * - *

Exchanges the content of the container by the content of obj, which is another - * {@link TreeMap map} of the same type. Sizes abd container type may differ.

- * - *

After the call to this member function, the elements in this container are those which were - * in obj before the call, and the elements of obj are those which were in this. All - * iterators, references and pointers remain valid for the swapped objects.

- * - *

Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that - * algorithm with an optimization that behaves like this member function.

- * - * @param obj Another {@link TreeMap map container} of the same type of elements as this (i.e., - * with the same template parameters, Key and T) whose content is swapped - * with that of this {@link TreeMap container}. - */ - swap(obj: TreeMap): void; - /** - * @inheritdoc - */ - swap(obj: base.IContainer>): void; - } -} -declare namespace std.TreeMultiSet { - type iterator = std.SetIterator; - type reverse_iterator = std.SetReverseIterator; -} -declare namespace std { - /** - *

Tree-structured multiple-key set.

- * - *

{@link TreeMultiSet TreeMultiSets} are containers that store elements following a specific order, and - * where multiple elements can have equivalent values.

- * - *

In a {@link TreeMultiSet}, the value of an element also identifies it (the value is itself - * the key, of type T). The value of the elements in a {@link TreeMultiSet} cannot - * be modified once in the container (the elements are always const), but they can be inserted or removed - * from the container.

- * - *

Internally, the elements in a {@link TreeMultiSet TreeMultiSets} are always sorted following a strict - * weak ordering criterion indicated by its internal comparison method (of {@link IComparable.less less}).

- * - *

{@link TreeMultiSet} containers are generally slower than {@link HashMultiSet} containers - * to access individual elements by their key, but they allow the direct iteration on subsets based on - * their order.

- * - *

{@link TreeMultiSet TreeMultiSets} are typically implemented as binary search trees.

- * - *

- *

- * - *

Container properties

- *
- *
Associative
- *
- * Elements in associative containers are referenced by their key and not by their absolute - * position in the container. - *
- * - *
Ordered
- *
- * The elements in the container follow a strict order at all times. All inserted elements are - * given a position in this order. - *
- * - *
Set
- *
The value of an element is also the key used to identify it.
- * - *
Multiple equivalent keys
- *
Multiple elements in the container can have equivalent keys.
- *
- * - * @param Type of the elements. Each element in a {@link TreeMultiSet} container is also identified - * by this value (each value is itself also the element's key). - * - * @reference http://www.cplusplus.com/reference/set/multiset - * @author Jeongho Nam - */ - class TreeMultiSet extends base.MultiSet implements base.ITreeSet { - /** - * @hidden - */ - private tree_; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from compare. - * - * @param compare A binary predicate determines order of elements. - */ - constructor(compare: (x: T, y: T) => boolean); - /** - * Contruct from elements. - * - * @param array Elements to be contained. - */ - constructor(array: Array); - /** - * Contruct from elements with compare. - * - * @param array Elements to be contained. - * @param compare A binary predicate determines order of elements. - */ - constructor(array: Array, compare: (x: T, y: T) => boolean); - /** - * Copy Constructor. - */ - constructor(container: TreeMultiSet); - /** - * Copy Constructor with compare. - * - * @param container A container to be copied. - * @param compare A binary predicate determines order of elements. - */ - constructor(container: TreeMultiSet, compare: (x: T, y: T) => boolean); - /** - * Range Constructor. - * - * @param begin Input interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - */ - constructor(begin: Iterator, end: Iterator); - /** - * Construct from range and compare. - * - * @param begin Input interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - * @param compare A binary predicate determines order of elements. - */ - constructor(begin: Iterator, end: Iterator, compare: (x: T, y: T) => boolean); - /** - * @inheritdoc - */ - clear(): void; - /** - * @inheritdoc - */ - find(val: T): SetIterator; - /** - * @inheritdoc - */ - count(val: T): number; - /** - * @inheritdoc - */ - key_comp(): (x: T, y: T) => boolean; - /** - * @inheritdoc - */ - value_comp(): (x: T, y: T) => boolean; - /** - * @inheritdoc - */ - lower_bound(val: T): SetIterator; - /** - * @inheritdoc - */ - upper_bound(val: T): SetIterator; - /** - * @inheritdoc - */ - equal_range(val: T): Pair, SetIterator>; - /** - * @hidden - */ - protected _Insert_by_val(val: T): any; - /** - * @hidden - */ - protected _Insert_by_hint(hint: SetIterator, val: T): SetIterator; - /** - * @hidden - */ - protected _Insert_by_range>(first: InputIterator, last: InputIterator): void; - /** - * @inheritdoc - */ - protected _Handle_insert(first: SetIterator, last: SetIterator): void; - /** - * @inheritdoc - */ - protected _Handle_erase(first: SetIterator, last: SetIterator): void; - /** - *

Swap content.

- * - *

Exchanges the content of the container by the content of obj, which is another - * {@link TreeMultiSet set} of the same type. Sizes abd container type may differ.

- * - *

After the call to this member function, the elements in this container are those which were - * in obj before the call, and the elements of obj are those which were in this. All - * iterators, references and pointers remain valid for the swapped objects.

- * - *

Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that - * algorithm with an optimization that behaves like this member function.

- * - * @param obj Another {@link TreeMultiSet set container} of the same type of elements as this (i.e., - * with the same template parameters, Key and T) whose content is swapped - * with that of this {@link TreeMultiSet container}. - */ - swap(obj: TreeMultiSet): void; - /** - * @inheritdoc - */ - swap(obj: base.IContainer): void; - } -} -declare namespace std.TreeMultiMap { - type iterator = std.MapIterator; - type reverse_iterator = std.MapReverseIterator; -} -declare namespace std { - /** - *

Tree-structured multiple-key map.

- * - *

{@link TreeMultiMap TreeMultiMaps} are associative containers that store elements formed by a combination of - * a key value and a mapped value, following a specific order, and where multiple elements can - * have equivalent keys.

- * - *

In a {@link TreeMultiMap}, the key values are generally used to sort and uniquely identify - * the elements, while the mapped values store the content associated to this key. The types of - * key and mapped value may differ, and are grouped together in member type - * value_type, which is a {@link Pair} type combining both:

- * - *

typedef Pair value_type;

- * - *

Internally, the elements in a {@link TreeMultiMap}are always sorted by its key following a - * strict weak ordering criterion indicated by its internal comparison method (of {@link less}).

- * - *

{@link TreeMultiMap}containers are generally slower than {@link HashMap} containers - * to access individual elements by their key, but they allow the direct iteration on subsets based - * on their order.

- * - *

{@link TreeMultiMap TreeMultiMaps} are typically implemented as binary search trees.

- * - *

< - * img src="http://samchon.github.io/typescript-stl/images/design/class_diagram/map_containers.png" style="max-width: 100%" />

- * - *

Container properties

- *
- *
Associative
- *
- * Elements in associative containers are referenced by their key and not by their absolute - * position in the container. - *
- * - *
Ordered
- *
- * The elements in the container follow a strict order at all times. All inserted elements are - * given a position in this order. - *
- * - *
Map
- *
- * Each element associates a key to a mapped value: - * Keys are meant to identify the elements whose main content is the mapped value. - *
- * - *
Multiple equivalent keys
- *
Multiple elements in the container can have equivalent keys.
- *
- * - * @param Type of the keys. Each element in a map is uniquely identified by its key value. - * @param Type of the mapped value. Each element in a map stores some data as its mapped value. - * - * @reference http://www.cplusplus.com/reference/map/multimap - * @author Jeongho Nam - */ - class TreeMultiMap extends base.MultiMap implements base.ITreeMap { - /** - * @hidden - */ - private tree_; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from compare. - * - * @param compare A binary predicate determines order of elements. - */ - constructor(compare: (x: Key, y: Key) => boolean); - /** - * Contruct from elements. - * - * @param array Elements to be contained. - */ - constructor(array: Array>); - /** - * Contruct from elements. - * - * @param array Elements to be contained. - * @param compare A binary predicate determines order of elements. - */ - constructor(array: Array>, compare: (x: Key, y: Key) => boolean); - /** - * Contruct from tuples. - * - * @param array Tuples to be contained. - */ - constructor(array: Array<[Key, T]>); - /** - * Contruct from tuples. - * - * @param array Tuples to be contained. - * @param compare A binary predicate determines order of elements. - */ - constructor(array: Array<[Key, T]>, compare: (x: Key, y: Key) => boolean); - /** - * Copy Constructor. - * - * @param container Another map to copy. - */ - constructor(container: TreeMultiMap); - /** - * Copy Constructor. - * - * @param container Another map to copy. - * @param compare A binary predicate determines order of elements. - */ - constructor(container: TreeMultiMap, compare: (x: Key, y: Key) => boolean); - /** - * Range Constructor. - * - * @param begin nput interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - */ - constructor(begin: Iterator>, end: Iterator>); - /** - * Range Constructor. - * - * @param begin nput interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - * @param compare A binary predicate determines order of elements. - */ - constructor(begin: Iterator>, end: Iterator>, compare: (x: Key, y: Key) => boolean); - /** - * @inheritdoc - */ - clear(): void; - /** - * @inheritdoc - */ - find(key: Key): MapIterator; - /** - * @inheritdoc - */ - count(key: Key): number; - /** - * @inheritdoc - */ - key_comp(): (x: Key, y: Key) => boolean; - /** - * @inheritdoc - */ - value_comp(): (x: Pair, y: Pair) => boolean; - /** - * @inheritdoc - */ - lower_bound(key: Key): MapIterator; - /** - * @inheritdoc - */ - upper_bound(key: Key): MapIterator; - /** - * @inheritdoc - */ - equal_range(key: Key): Pair, MapIterator>; - /** - * @hidden - */ - protected _Insert_by_pair(pair: Pair): any; - /** - * @hidden - */ - protected _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; - /** - * @hidden - */ - protected _Insert_by_range>>(first: InputIterator, last: InputIterator): void; - /** - * @inheritdoc - */ - protected _Handle_insert(first: MapIterator, last: MapIterator): void; - /** - * @inheritdoc - */ - protected _Handle_erase(first: MapIterator, last: MapIterator): void; - /** - *

Swap content.

- * - *

Exchanges the content of the container by the content of obj, which is another - * {@link TreeMapMulti map} of the same type. Sizes abd container type may differ.

- * - *

After the call to this member function, the elements in this container are those which were - * in obj before the call, and the elements of obj are those which were in this. All - * iterators, references and pointers remain valid for the swapped objects.

- * - *

Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that - * algorithm with an optimization that behaves like this member function.

- * - * @param obj Another {@link TreeMapMulti map container} of the same type of elements as this (i.e., - * with the same template parameters, Key and T) whose content is swapped - * with that of this {@link TreeMapMulti container}. - */ - swap(obj: TreeMultiMap): void; - /** - * @inheritdoc - */ - swap(obj: base.IContainer>): void; - } -} -declare namespace std { - /** - *

System error exception.

- * - *

This class defines the type of objects thrown as exceptions to report conditions originating during - * runtime from the operating system or other low-level application program interfaces which have an - * associated {@link ErrorCode}.

- * - *

The class inherits from {@link RuntimeError}, to which it adds an {@link ErrorCode} as - * member code (and defines a specialized what member).

- * - *

- *

- * - * @reference http://www.cplusplus.com/reference/system_error/system_error - * @author Jeongho Nam - */ - class SystemError extends RuntimeError { - /** - * @hidden - */ - protected code_: ErrorCode; - /** - * Construct from an error code. - * - * @param code An {@link ErrorCode} object. - */ - constructor(code: ErrorCode); - /** - * Construct from an error code and message. - * - * @param code An {@link ErrorCode} object. - * @param message A message incorporated in the string returned by member {@link what what()}. - */ - constructor(code: ErrorCode, message: string); - /** - * Construct from a numeric value and error category. - * - * @param val A numerical value identifying an error code. - * @param category A reference to an {@link ErrorCode} object. - */ - constructor(val: number, category: ErrorCategory); - /** - * Construct from a numeric value, error category and message. - * - * @param val A numerical value identifying an error code. - * @param category A reference to an {@link ErrorCode} object. - * @param message A message incorporated in the string returned by member {@link what what()}. - */ - constructor(val: number, category: ErrorCategory, message: string); - /** - *

Get error code.

- * - *

Returns the {@link ErrorCode} object associated with the exception.

- * - *

This value is either the {@link ErrorCode} passed to the construction or its equivalent - * (if constructed with a value and a {@link category}.

- * - * @return The {@link ErrorCode} associated with the object. - */ - code(): ErrorCode; - } -} -declare namespace std { - /** - *

Error category.

- * - *

This type serves as a base class for specific category types.

- * - *

Category types are used to identify the source of an error. They also define the relation between - * {@link ErrorCode} and {@link ErrorCondition}objects of its category, as well as the message set for {@link ErrorCode} - * objects. - * - *

Objects of these types have no distinct values and are not-copyable and not-assignable, and thus can only be - * passed by reference. As such, only one object of each of these types shall exist, each uniquely identifying its own - * category: all error codes and conditions of a same category shall return a reference to same object.

- * - *

- *

- * - * @reference http://www.cplusplus.com/reference/system_error/error_category - * @author Jeongho Nam - */ - abstract class ErrorCategory { - /** - * Default Constructor. - */ - constructor(); - /** - *

Return category name.

- * - *

In derived classes, the function returns a string naming the category.

- * - *

In {@link ErrorCategory}, it is a pure virtual member function.

- * - *
    - *
  • In the {@link GenericCategory} object, it returns "generic".
  • - *
  • In the {@link SystemCategory} object, it returns "system".
  • - *
  • In the {@link IOStreamCategory} object, it returns "iostream".
  • - *
- * - * @return The category name. - */ - abstract name(): string; - /** - *

Error message.

- * - *

In derived classes, the function returns a string object with a message describing the error condition - * denoted by val.

- * - *

In {@link ErrorCategory}, it is a pure virtual member function.

- * - *

This function is called both by {@link ErrorCode.message ErrorCode.message()} and - * {@link ErrorCondition.message ErrorCondition.message()} to obtain the corresponding message in the - * {@link category}. Therefore, numerical values used by custom error codes and - * {@link ErrorCondition error conditions} should only match for a category if they describe the same error.

- * - * @param val A numerical value identifying an error condition. - * If the {@link ErrorCategory} object is the {@link GenericCategory}, this argument is equivalent to an - * {@link errno} value. - * - * @return A string object with the message. - */ - abstract message(val: number): string; - /** - *

Default error condition.

- * - *

Returns the default {@link ErrorCondition}object of this category that is associated with the - * {@link ErrorCode} identified by a value of val.

- * - *

Its definition in the base class {@link ErrorCategory} returns the same as constructing an - * {@link ErrorCondition} object with: - * - *

new ErrorCondition(val, *this);

- * - *

As a virtual member function, this behavior can be overriden in derived classes.

- * - *

This function is called by the default definition of member {@link equivalent equivalent()}, which is used to - * compare {@link ErrorCondition error conditions} with error codes.

- * - * @param val A numerical value identifying an error condition. - * - * @return The default {@link ErrorCondition}object associated with condition value val for this category. - */ - default_error_condition(val: number): ErrorCondition; - /** - *

Check error code equivalence.

- * - *

Checks whether, for the category, an {@link ErrorCode error code} is equivalent to an - * {@link ErrorCondition error condition.

- * - *

This function is called by the overloads of comparison operators when an {@link ErrorCondition} object is - * compared to an {@link ErrorCode} object to check for equality or inequality. If either one of those objects' - * {@link ErrorCategory categories} considers the other equivalent using this function, they are considered - * equivalent by the operator.

- * - *

As a virtual member function, this behavior can be overridden in derived classes to define a different - * correspondence mechanism for each {@link ErrorCategory} type.

- * - * @param val_code A numerical value identifying an error code. - * @param cond An object of an {@link ErrorCondition} type. - * - * @return true if the arguments are considered equivalent. false otherwise. - */ - equivalent(val_code: number, cond: ErrorCondition): boolean; - /** - *

Check error code equivalence.

- * - *

Checks whether, for the category, an {@link ErrorCode error code} is equivalent to an - * {@link ErrorCondition error condition.

- * - *

This function is called by the overloads of comparison operators when an {@link ErrorCondition} object is - * compared to an {@link ErrorCode} object to check for equality or inequality. If either one of those objects' - * {@link ErrorCategory categories} considers the other equivalent using this function, they are considered - * equivalent by the operator.

- * - *

As a virtual member function, this behavior can be overridden in derived classes to define a different - * correspondence mechanism for each {@link ErrorCategory} type.

- * - * @param code An object of an {@link ErrorCode} type. - * @param val_cond A numerical value identifying an error code. - * - * @return true if the arguments are considered equivalent. false otherwise. - */ - equivalent(code: ErrorCode, val_cond: number): boolean; - } -} -declare namespace std { - /** - *

Error condition.

- * - *

Objects of this type hold a condition {@link value} associated with a {@link category}.

- * - *

Objects of this type describe errors in a generic way so that they may be portable across different - * systems. This is in contrast with {@link ErrorCode} objects, that may contain system-specific - * information.

- * - *

Because {@link ErrorCondition}objects can be compared with error_code objects directly by using - * relational operators, {@link ErrorCondition}objects are generally used to check whether - * a particular {@link ErrorCode} obtained from the system matches a specific error condition no matter - * the system.

- * - *

The {@link ErrorCategory categories} associated with the {@link ErrorCondition} and the - * {@link ErrorCode} define the equivalences between them.

- * - *

- *

- * - * @reference http://www.cplusplus.com/reference/system_error/error_condition - * @author Jeongho Nam - */ - class ErrorCondition extends base.ErrorInstance { - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from a numeric value and error category. - * - * @param val A numerical value identifying an error condition. - * @param category A reference to an {@link ErrorCategory} object. - */ - constructor(val: number, category: ErrorCategory); - } -} -declare namespace std { - /** - *

Error code.

- * - *

Objects of this type hold an error code {@link value} associated with a {@link category}.

- * - *

The operating system and other low-level applications and libraries generate numerical error codes to - * represent possible results. These numerical values may carry essential information for a specific platform, - * but be non-portable from one platform to another.

- * - *

Objects of this class associate such numerical codes to {@link ErrorCategory error categories}, so that they - * can be interpreted when needed as more abstract (and portable) {@link ErrorCondition error conditions}.

- * - *

- *

- * - * @reference http://www.cplusplus.com/reference/system_error/error_code - * @author Jeongho Nam - */ - class ErrorCode extends base.ErrorInstance { - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from a numeric value and error category. - * - * @param val A numerical value identifying an error code. - * @param category A reference to an {@link ErrorCategory} object. - */ - constructor(val: number, category: ErrorCategory); - } -} -declare namespace std { - /** - *

Running on Node.

- * - *

Test whether the JavaScript is running on Node.

- * - * @references http://stackoverflow.com/questions/17575790/environment-detection-node-js-or-browser - */ - function is_node(): boolean; - /** - *

Pair of values.

- * - *

This class couples together a pair of values, which may be of different types (T1 and - * T2). The individual values can be accessed through its public members {@link first} and - * {@link second}.

- * - * @param Type of member {@link first}. - * @param Type of member {@link second}. - * - * @reference http://www.cplusplus.com/reference/utility/pair - * @author Jeongho Nam - */ - class Pair implements IComparable> { - /** - *

A first value in the Pair.

- */ - first: T1; - /** - *

A second value in the Pair.

- */ - second: T2; - /** - *

Construct from pair values.

- * - * @param first The first value of the Pair - * @param second The second value of the Pair - */ - constructor(first: T1, second: T2); - /** - *

Whether a Pair is equal with the Pair.

- *

Compare each first and second value of two Pair(s) and returns whether they are equal or not.

- * - *

If stored key and value in a Pair are not number or string but an object like a class or struct, - * the comparison will be executed by a member method (SomeObject)::equal_to(). If the object does not have - * the member method equal_to(), only address of pointer will be compared.

- * - * @param obj A Map to compare - * @return Indicates whether equal or not. - */ - equals(pair: Pair): boolean; - /** - * @inheritdoc - */ - less(pair: Pair): boolean; - } - /** - *

Construct {@link Pair} object.

- * - *

Constructs a {@link Pair} object with its {@link Pair.first first} element set to x and its - * {@link Pair.second second} element set to y.

- * - *

The template types can be implicitly deduced from the arguments passed to {@link make_pair}.

- * - *

{@link Pair} objects can be constructed from other {@link Pair} objects containing different types, if the - * respective types are implicitly convertible.

- * - * @param x Value for member {@link Pair.first first}. - * @param y Value for member {@link Pair.second second}. - * - * @return A {@link Pair} object whose elements {@link Pair.first first} and {@link Pair.second second} are set to - * x and y respectivelly. - */ - function make_pair(x: T1, y: T2): Pair; -} -declare namespace std { - /** - * Type definition of {@link Vector} and it's the original name used in C++. - */ - export import vector = Vector; - /** - * Type definition of {@link List} and it's the original name used in C++. - */ - export import list = List; - /** - * Type definition of {@link Deque} and it's the original name used in C++. - */ - export import deque = Deque; - /** - * Type definition of {@link Stack} and it's the original name used in C++. - */ - type stack = Stack; - /** - * Type definition of {@link Queue} and it's the original name used in C++. - */ - type queue = Queue; - /** - * Type definition of {@link PriorityQueue} and it's the original name used in C++. - */ - type priority_queue = PriorityQueue; - var stack: typeof Stack; - var queue: typeof Queue; - var priority_queue: typeof PriorityQueue; - /** - * Type definition of {@link TreeSet} and it's the original name used in C++. - */ - export import set = TreeSet; - /** - * Type definition of {@link TreeMultiSet} and it's the original name used in C++. - */ - export import multiset = TreeMultiSet; - /** - * Type definition of {@link HashSet} and it's the original name used in C++. - */ - export import unordered_set = HashSet; - /** - * Type definition of {@link HashMultiSet} and it's the original name used in C++. - */ - export import unordered_multiset = HashMultiSet; - /** - * Type definition of {@link TreeMap} and it's the original name used in C++. - */ - export import map = TreeMap; - /** - * Type definition of {@link TreeMultiMap} and it's the original name used in C++. - */ - export import multimap = TreeMultiMap; - /** - * Type definition of {@link HashMap} and it's the original name used in C++. - */ - export import unordered_map = HashMap; - /** - * Type definition of {@link HashMultiMap} and it's the original name used in C++. - */ - export import unordered_multimap = HashMultiMap; - type exception = Exception; - type logic_error = LogicError; - type domain_error = DomainError; - type invalid_argument = InvalidArgument; - type length_error = LengthError; - type out_of_range = OutOfRange; - type runtime_error = RuntimeError; - type overflow_error = OverflowError; - type underflow_error = UnderflowError; - type range_error = RangeError; - type system_error = SystemError; - type error_category = ErrorCategory; - type error_condition = ErrorCondition; - type error_code = ErrorCode; - var exception: typeof Exception; - var logic_error: typeof LogicError; - var domain_error: typeof DomainError; - var invalid_argument: typeof InvalidArgument; - var length_error: typeof LengthError; - var out_of_range: typeof OutOfRange; - var runtime_error: typeof RuntimeError; - var overflow_error: typeof OverflowError; - var underflow_error: typeof UnderflowError; - var range_error: typeof RangeError; - var system_error: typeof SystemError; - var error_category: typeof ErrorCategory; - var error_condition: typeof ErrorCondition; - var error_code: typeof ErrorCode; -} +} \ No newline at end of file diff --git a/uws/index.d.ts b/uws/index.d.ts index 1d6de452c5..89578fc22d 100644 --- a/uws/index.d.ts +++ b/uws/index.d.ts @@ -1,11 +1,10 @@ -// Type definitions for µWS +// Type definitions for uWS 0.13 // Project: https://github.com/uWebSockets/uWebSockets // Definitions by: York Yao // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// - import * as events from 'events'; import * as http from 'http'; import * as https from 'https'; @@ -151,6 +150,16 @@ declare namespace WebSocket { addListener(event: string, listener: () => void): this; } + export interface UwsHttp { + createServer(requestListener?: (request: http.IncomingMessage, response: http.ServerResponse) => void): http.Server; + // any to avoid express definitions + getExpressApp(express: any): any; + getResponsePrototype(): http.ServerResponse; + getRequestPrototype(): http.IncomingMessage; + } + + export const http: UwsHttp; + export function createServer(options?: IServerOptions, connectionListener?: (client: WebSocket) => void): Server; export function connect(address: string, openListener?: Function): void; diff --git a/uws/uws-tests.ts b/uws/uws-tests.ts index 059f6b224f..5d0b2ed3c6 100644 --- a/uws/uws-tests.ts +++ b/uws/uws-tests.ts @@ -1,11 +1,13 @@ import * as WebSocket from 'uws'; -import * as fs from'fs'; +import {Buffer} from 'buffer'; +import * as http from'http'; import * as https from'https'; +import * as fs from'fs'; const WebSocketServer = WebSocket.Server; const non_ssl = new WebSocketServer({ port: 3000 }); -var non_ssl_disconnections = 0; +let non_ssl_disconnections = 0; non_ssl.on('connection', function(ws) { ws.on('message', function(message) { ws.send(message); @@ -30,7 +32,7 @@ const httpsServer = https.createServer(options, (req: any, res: any) => { const ssl = new WebSocketServer({ server: httpsServer }); -var ssl_disconnections = 0; +let ssl_disconnections = 0; ssl.on('connection', function(ws) { ws.on('message', function(message) { ws.send(message); @@ -44,3 +46,29 @@ ssl.on('connection', function(ws) { }); httpsServer.listen(3001); + +/** + * HTTP module. + */ + +const document: Buffer = Buffer.from('Hello world!'); + +const server: http.Server = WebSocket.http.createServer( + (req: http.IncomingMessage, res: http.ServerResponse): void => { + if (req.method === 'POST') { + const body: Buffer[] = []; + + req.on('data', (chunk: Buffer) => { + body.push(Buffer.from(chunk)); + }).on('end', () => { + res.end('You posted me this: ' + Buffer.concat(body).toString()); + }); + // handle some GET url + } else if (req.url === '/') { + res.end(document); + } else { + res.end('Unknown request by: ' + req.headers['user-agent']); + } +}); + +server.listen(3002); diff --git a/vanilla-tilt/index.d.ts b/vanilla-tilt/index.d.ts new file mode 100644 index 0000000000..828ca47513 --- /dev/null +++ b/vanilla-tilt/index.d.ts @@ -0,0 +1,112 @@ +// Type definitions for vanilla-tilt 1.3 +// Project: https://github.com/micku7zu/vanilla-tilt.js +// Definitions by: Livio Brunner +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * A smooth 3D tilt javascript library forked from Tilt.js (jQuery version). + */ +export declare namespace VanillaTilt { + /** + * Options which configures the tilting + */ + interface TiltOptions { + /** + * Reverse the tilt direction + */ + reverse?: boolean; + /** + * Max tilt rotation (degrees) + */ + max?: number; + /** + * Transform perspective, the lower the more extreme the tilt gets. + */ + perspective?: number; + /** + * 2 = 200%, 1.5 = 150%, etc.. + */ + scale?: number; + /** + * Speed of the enter/exit transition + */ + speed?: number; + /** + * Set a transition on enter/exit. + */ + transition?: boolean; + /** + * What axis should be disabled. Can be X or Y. + */ + axis?: null | "x" | "y"; + /** + * If the tilt effect has to be reset on exit. + */ + reset?: boolean; + /** + * Easing on enter/exit. + */ + easing?: string; + } + + export interface TiltValues { + /** + * The current tilt on the X axis + */ + tiltX: number; + /** + * The current tilt on the Y axis + */ + tiltY: number; + /** + * The current percentage on the X axis + */ + percentageX: number; + /** + * The current percentage on the Y axis + */ + percentageY: number; + } + + export interface HTMLVanillaTiltElement extends HTMLElement { + vanillaTilt: VanillaTilt + } +} + +/** + * A smooth 3D tilt javascript library forked from Tilt.js (jQuery version). + */ +export declare class VanillaTilt { + /** + * Creates a new instance of a VanillaTilt element. + * @param element The element, which should be a VanillaTilt element + * @param settings Settings which configures the element + */ + constructor(element: HTMLElement, settings?: VanillaTilt.TiltOptions); + /** + * Initializes one or multiple elements + * @param elements The element, which should tilt + * @param settings Settings, which configures the elements + */ + static init(elements: HTMLElement | HTMLElement[], settings?: VanillaTilt.TiltOptions): void; + /** + * Resets the styling + */ + reset(): void; + /** + * Get values of instance + */ + getValues(): VanillaTilt.TiltValues; + /** + * Destroys the instance and removes the listeners. + */ + destroy(): void; + /** + * Start listening to events + */ + addEventListeners(): void; + /** + * Stop listening to events + */ + removeEventListener(): void; +} diff --git a/vanilla-tilt/tsconfig.json b/vanilla-tilt/tsconfig.json new file mode 100644 index 0000000000..f95783a19d --- /dev/null +++ b/vanilla-tilt/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "vanilla-tilt-tests.ts" + ] +} diff --git a/vanilla-tilt/tslint.json b/vanilla-tilt/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/vanilla-tilt/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/vanilla-tilt/vanilla-tilt-tests.ts b/vanilla-tilt/vanilla-tilt-tests.ts new file mode 100644 index 0000000000..80691885c4 --- /dev/null +++ b/vanilla-tilt/vanilla-tilt-tests.ts @@ -0,0 +1,29 @@ +import { VanillaTilt } from './index.d'; + +let element: VanillaTilt = new VanillaTilt(document.createElement('a'), { + axis: 'y', + easing: 'cubic-besizer(0.9, 0.9, 0.9)', + max: 2, + perspective: 100, + reset: true, + reverse: true, + scale: 2, + speed: 200 +}); + +VanillaTilt.init(document.createElement('a'), { + axis: 'x' +}); + +element.removeEventListener(); + +VanillaTilt.init([document.createElement('a')], { + axis: null +}); + + +let values: VanillaTilt.TiltValues = element.getValues(); +values.percentageX; +values.percentageY; +values.tiltX; +values.tiltY; diff --git a/webpack/index.d.ts b/webpack/index.d.ts index 4f6ae6e211..18ab5274ba 100644 --- a/webpack/index.d.ts +++ b/webpack/index.d.ts @@ -1,6 +1,10 @@ // Type definitions for webpack 2.2 // Project: https://github.com/webpack/webpack -// Definitions by: Qubo , Matt Lewis , Benjamin Lim , Boris Cherny +// Definitions by: Qubo +// Matt Lewis +// Benjamin Lim +// Boris Cherny +// Tommy Troy Lin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -661,7 +665,20 @@ declare namespace webpack { */ class BannerPlugin extends Plugin { - constructor(banner: any, options: any); + constructor(options: string | BannerPlugin.Options); + } + + namespace BannerPlugin { + type Filter = string | RegExp; + + interface Options { + banner: string; + entryOnly?: boolean; + exclude?: Filter | Filter[]; + include?: Filter | Filter[]; + raw?: boolean; + test?: Filter | Filter[]; + } } class ContextReplacementPlugin extends Plugin { diff --git a/webpack/webpack-tests.ts b/webpack/webpack-tests.ts index c1369f78bc..8ab05c1de4 100644 --- a/webpack/webpack-tests.ts +++ b/webpack/webpack-tests.ts @@ -257,7 +257,18 @@ plugin = new webpack.IgnorePlugin(requestRegExp, contextRegExp); plugin = new webpack.PrefetchPlugin(context, request); plugin = new webpack.PrefetchPlugin(request); -plugin = new webpack.BannerPlugin(banner, options); +plugin = new webpack.BannerPlugin('banner'); +plugin = new webpack.BannerPlugin({ + banner: 'banner' +}); +plugin = new webpack.BannerPlugin({ + banner: 'banner', + entryOnly: true, + exclude: /index/, + include: 'test', + raw: false, + test: ['test', /index/] +}); plugin = new webpack.optimize.DedupePlugin(); plugin = new webpack.optimize.LimitChunkCountPlugin(options); plugin = new webpack.optimize.MinChunkSizePlugin(options);

This namespace declares an unspecified number of objects: _1, _2, _3, ..., which are - * used to specify placeholders in calls to function {@link std.bind}.