From 6b080a6bbf559cc352345f191b8e1aee555d1cf6 Mon Sep 17 00:00:00 2001 From: eloekset Date: Tue, 1 Mar 2016 15:21:45 +0100 Subject: [PATCH 001/402] Globalize definition for NuGet package v0.1.3. --- globalize/globalize-0.1.3.d.ts | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 globalize/globalize-0.1.3.d.ts diff --git a/globalize/globalize-0.1.3.d.ts b/globalize/globalize-0.1.3.d.ts new file mode 100644 index 0000000000..8fbd4934b1 --- /dev/null +++ b/globalize/globalize-0.1.3.d.ts @@ -0,0 +1,25 @@ +// Type definitions for Globalize v?.? NuGet package v0.1.3 +// Project: https://github.com/jquery/globalize +// Definitions by: Aram Taieb +// Definitions: https://github.com/afromogli/DefinitelyTyped + +interface GlobalizeStatic { + addCultureInfo(cultureName: string, baseCultureName: string, info: any): void; + findClosestCulture(name: string): any; + format(value: any, format: string): string; + format(value: any, format: string, cultureSelector: string): string; + localize(key: string): string; + localize(key: string, cultureSelector: string): string; + parseDate(value: any): Date; + parseDate(value: any, formats: any): Date; + parseDate(value: any, formats: any, culture: string): Date; + parseInt(value: any): number; + parseInt(value: any, radix: number): number; + parseInt(value: any, radix: number, cultureSelector: string): number; + parseFloat(value: any): number; + parseFloat(value: any, radix: number): number; + parseFloat(value: any, radix: number, cultureSelector: string): number; + culture(cultureSelector: string): any; +} + +declare var Globalize: GlobalizeStatic; From 876883d0fd58dc1e24d3f3c147b5f33dfbfb56df Mon Sep 17 00:00:00 2001 From: eloekset Date: Wed, 2 Mar 2016 16:39:17 +0100 Subject: [PATCH 002/402] Created test file for the 0.1.3 definition. --- globalize/globalize-0.1.3-tests.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 globalize/globalize-0.1.3-tests.ts diff --git a/globalize/globalize-0.1.3-tests.ts b/globalize/globalize-0.1.3-tests.ts new file mode 100644 index 0000000000..4e3e9056ed --- /dev/null +++ b/globalize/globalize-0.1.3-tests.ts @@ -0,0 +1,11 @@ +/// +module Tests { + Globalize.culture('en-US'); + Globalize.addCultureInfo('nb-NO', 'no', { messages: {Test: "Test"} }); + var cult = Globalize.findClosestCulture('nb-NO'); + var numberString = Globalize.format(1.245, 'n2'); + var testString = Globalize.localize('Test'); + var dateParsed = Globalize.parseDate('2016-02-03'); + var intParsed = Globalize.parseInt('123'); + var floatParsed = Globalize.parseFloat('12.3'); +} \ No newline at end of file From d9e6d03e769ee7013bee70e4f73c8e59d932d91d Mon Sep 17 00:00:00 2001 From: eloekset Date: Wed, 2 Mar 2016 16:40:20 +0100 Subject: [PATCH 003/402] Set NuGet version 0.1.3 as Globalize version. --- globalize/globalize-0.1.3.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/globalize/globalize-0.1.3.d.ts b/globalize/globalize-0.1.3.d.ts index 8fbd4934b1..b31a1cc092 100644 --- a/globalize/globalize-0.1.3.d.ts +++ b/globalize/globalize-0.1.3.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Globalize v?.? NuGet package v0.1.3 +// Type definitions for Globalize v0.1.3 (NuGet package version) // Project: https://github.com/jquery/globalize // Definitions by: Aram Taieb // Definitions: https://github.com/afromogli/DefinitelyTyped From af57239852657e951b4635b045558892373b8166 Mon Sep 17 00:00:00 2001 From: James Tarling Date: Mon, 9 May 2016 09:23:49 +0100 Subject: [PATCH 004/402] Fix for duplicate USB event (#9236) --- chrome/chrome-app.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chrome/chrome-app.d.ts b/chrome/chrome-app.d.ts index 1891b960e0..3b63357986 100644 --- a/chrome/chrome-app.d.ts +++ b/chrome/chrome-app.d.ts @@ -685,7 +685,7 @@ declare namespace chrome.usb { interface DeviceEvent extends chrome.events.Event<(device: Device) => void> {} export var onDeviceAdded: DeviceEvent; - export var onDeviceAdded: DeviceEvent; + export var onDeviceRemoved: DeviceEvent; export function getDevices(options: { vendorId?: number, productId?: number, filters?: DeviceFilter[] }, callback: (devices: Device[]) => void): void; export function getUserSelectedDevices(options: { multiple?: boolean, filters?: DeviceFilter[] }, callback: (devices: Device[]) => void): void; From f882b322b97b1ad84388c1765c65e2752cdbf23b Mon Sep 17 00:00:00 2001 From: Ramil Kadraliev Date: Mon, 9 May 2016 12:24:39 +0400 Subject: [PATCH 005/402] Renamed queryString in SignalR.Hub.Options to qs (#9214) for setting query string parameter Signalr's method 'hubConnection' processes 'options.qs' parameter , not 'options.queryString' --- signalr/signalr.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/signalr/signalr.d.ts b/signalr/signalr.d.ts index ea150d71f9..a46116fd75 100644 --- a/signalr/signalr.d.ts +++ b/signalr/signalr.d.ts @@ -76,7 +76,7 @@ declare namespace SignalR { } interface Options { - queryString?: string; + qs?: string; logging?: boolean; useDefaultPath?: boolean; } From 4119c4ab78a72a9dcb36a5dc89e99c12f22804a0 Mon Sep 17 00:00:00 2001 From: Rajab Shakirov Date: Mon, 9 May 2016 11:25:37 +0300 Subject: [PATCH 006/402] update react-calendar-timeline.d.ts (#9238) by issue: https://github.com/namespace-ee/react-calendar-timeline/issues/17#issuecomment-217128161 --- react-calendar-timeline/react-calendar-timeline.d.ts | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/react-calendar-timeline/react-calendar-timeline.d.ts b/react-calendar-timeline/react-calendar-timeline.d.ts index c44b70a59d..a10d73f1f8 100644 --- a/react-calendar-timeline/react-calendar-timeline.d.ts +++ b/react-calendar-timeline/react-calendar-timeline.d.ts @@ -7,8 +7,11 @@ declare module "react-calendar-timeline" { interface ReactCalendarTimeline { - groups?:any; - items?:{ + groups: { + id: number; + title: string; + }[]; + items:{ id: number; group: number; title?: string; @@ -53,8 +56,8 @@ declare module "react-calendar-timeline" { onCanvasClick?(groupId:any, time:any, e:any): any; onItemDoubleClick?(itemId:any): any; moveResizeValidator?(action:any, itemId:any, time:any): any; - defaultTimeStart: any; - defaultTimeEnd: any; + defaultTimeStart?: any; + defaultTimeEnd?: any; visibleTimeStart?: any; visibleTimeEnd?: any; onTimeChange?(visibleTimeStart:any, visibleTimeEnd:any): any; From 557f08618657576067da5e5ab836b961ec8ba38a Mon Sep 17 00:00:00 2001 From: "jacky.chen" Date: Mon, 9 May 2016 18:28:09 +1000 Subject: [PATCH 007/402] Fixed the incorrect parameter type in the constructor of https.Agent (#9232) --- node/node-tests.ts | 26 ++++++++++++++++++++++++++ node/node.d.ts | 13 +++++++------ 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/node/node-tests.ts b/node/node-tests.ts index 603fb7719c..1361a7206f 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -8,6 +8,7 @@ import * as util from "util"; import * as crypto from "crypto"; import * as tls from "tls"; import * as http from "http"; +import * as https from "https"; import * as net from "net"; import * as tty from "tty"; import * as dgram from "dgram"; @@ -367,6 +368,31 @@ namespace http_tests { }); } +//////////////////////////////////////////////////// +/// Https tests : http://nodejs.org/api/https.html +//////////////////////////////////////////////////// +namespace https_tests { + var agent: https.Agent = new https.Agent({ + keepAlive: true, + keepAliveMsecs: 10000, + maxSockets: Infinity, + maxFreeSockets: 256, + maxCachedSessions: 100 + }); + + var agent: https.Agent = https.globalAgent; + + https.request({ + agent: false + }); + https.request({ + agent: agent + }); + https.request({ + agent: undefined + }); +} + //////////////////////////////////////////////////// /// TTY tests : http://nodejs.org/api/tty.html //////////////////////////////////////////////////// diff --git a/node/node.d.ts b/node/node.d.ts index 184bd02a78..bc6e25c9d5 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -870,7 +870,7 @@ declare module "https" { SNICallback?: (servername: string) => any; } - export interface RequestOptions extends http.RequestOptions{ + export interface RequestOptions extends http.RequestOptions { pfx?: any; key?: any; passphrase?: string; @@ -881,13 +881,14 @@ declare module "https" { secureProtocol?: string; } - export interface Agent { - maxSockets: number; - sockets: any; - requests: any; + export interface Agent extends http.Agent { } + + export interface AgentOptions extends http.AgentOptions { + maxCachedSessions?: number; } + export var Agent: { - new (options?: RequestOptions): Agent; + new (options?: AgentOptions): Agent; }; export interface Server extends tls.Server { } export function createServer(options: ServerOptions, requestListener?: Function): Server; From cd61385a5d5ede6a1a7d51d9ebc50c2a76718c0f Mon Sep 17 00:00:00 2001 From: Leonid Suprun Date: Mon, 9 May 2016 12:32:18 +0400 Subject: [PATCH 008/402] sugarjs: DateRange update (#9243) --- sugar/sugar.d.ts | 141 ++++++++++++++++------------------------------- 1 file changed, 48 insertions(+), 93 deletions(-) diff --git a/sugar/sugar.d.ts b/sugar/sugar.d.ts index 8acff9b436..217ffb110e 100644 --- a/sugar/sugar.d.ts +++ b/sugar/sugar.d.ts @@ -8,23 +8,23 @@ sugar-1.3.9.d.ts may be freely distributed under the MIT license. Copyright (c) 2013 Josh Baldwin https://github.com/jbaldwin/sugar.d.ts 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 +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 +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 +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. */ @@ -263,7 +263,7 @@ interface String { /** * Escapes characters in a string to make a valid URL. * @returns URL escaped string. - * @extra If [param] is true, it will also escape valid URL + * @extra If [param] is true, it will also escape valid URL * characters for use as a URL parameter. * @example * 'http://foo.com/"bar"'.escapeURL() -> 'http://foo.com/%22bar%22' @@ -293,7 +293,7 @@ interface String { * Converts full-width characters (zenkaku) to half-width (hankaku). * @param mode default = 'all' * @returns Converted string to hankaku. - * @extra [mode] accepts any combination of + * @extra [mode] accepts any combination of * "a" (alphabet), * "n" (numbers), * "k" (katakana), @@ -1002,7 +1002,7 @@ interface Number { * Takes the number as milliseconds and returns a unit-adjusted localized string. * @param locale Locale to convert the ms to, default = currentLocale. * @returns String representation of the duration in [locale]. - * @extra This method is the same as %Date#relative% without + * @extra This method is the same as %Date#relative% without * the localized equivalent of "from now" or "ago". * [locale] can be passed as the first (and only) parameter. * Note that this method is only available when the dates @@ -1548,7 +1548,7 @@ interface Number { * @extra Note that "months" is ambiguous as a unit of time. * If the target date falls on a day that does not exist * (ie. August 31 -> February 31), the date will be shifted - * to the last day of the month. Be careful using %monthsAgo% + * to the last day of the month. Be careful using %monthsAgo% * if you need exact precision. * @set * millisecondAgo @@ -2349,7 +2349,7 @@ interface Array { * Groups the array by . * @param map Property on the elements in the array. * @param fn Optional callback for each group, default = No callback. - * @returns + * @returns * @extra Will return an object with keys equal to the grouped values. * may be a mapping function, or a string acting as a shortcut. * Optionally calls [fn] for each group. @@ -2608,7 +2608,7 @@ interface Array { /** * Returns the elements in the array with the most commonly occuring value. - * @param map Property on each element in the array or + * @param map Property on each element in the array or * @returns Array of elements that have the most common property. * @extra [map] may be a function mapping the value to be checked or a string * acting as a shortcut. @@ -2815,7 +2815,7 @@ interface Array { * ['a','b'].subtract('b','c') -> ['a'] **/ subtract(...args: T[]): T[]; - + /** * @see subtract **/ @@ -2859,7 +2859,7 @@ interface Array { /** * Returns an array containing all elements in all arrays with duplicates removed. * @method union([a1], [a2], ...) - * @param array + * @param array * @returns Union between the original array and . * @extra This method will also correctly operate on arrays of objects. * @example @@ -2944,7 +2944,7 @@ interface ObjectStatic { * Object.fromQueryString('foo[]=1&foo[]=2') -> { foo: [1,2] } **/ fromQueryString(str: string, deep?: boolean): T; - + /** * Returns true if is an object of that type. * @method Object.is[Type]() @@ -3232,8 +3232,8 @@ interface ObjectStatic { * @param key Property to check to see if it exists on . * @returns True if exists on , otherwise false. * @extra This method is considered safer than %Object#hasOwnProperty% when - * using objects as hashes. See - * http://www.devthought.com/2012/01/18/an-object-is-not-a-hash/ + * using objects as hashes. See + * http://www.devthought.com/2012/01/18/an-object-is-not-a-hash/ * for more. * @example * Object.has({ foo: 'bar' }, 'foo') -> true @@ -3689,8 +3689,8 @@ interface Object { * @param key Property to check to see if it exists on . * @returns True if exists on , otherwise false. * @extra This method is considered safer than %Object#hasOwnProperty% when - * using objects as hashes. See - * http://www.devthought.com/2012/01/18/an-object-is-not-a-hash/ + * using objects as hashes. See + * http://www.devthought.com/2012/01/18/an-object-is-not-a-hash/ * for more. * @example * Object.has({ foo: 'bar' }, 'foo') -> true @@ -4274,7 +4274,7 @@ interface Date { * @see addMilliseconds **/ addMonths(num: number, reset?: boolean): Date; - + /** * @see addMilliseconds **/ @@ -4386,7 +4386,7 @@ interface Date { * tokens. Locale-specific formats are %short%, %long%, and %full% which * have their own aliases and can be called with %date.short()%, etc. * If is not specified the %long% format is assumed. [locale] - * specifies a locale code to use (if not specified the current locale + * specifies a locale code to use (if not specified the current locale * is used). See @date_format for more details. * @set * short @@ -4484,7 +4484,7 @@ interface Date { * Returns true if the date is before . * @method isBefore(, [margin] = 0) * @returns Boolean - * @extra [margin] is to allow extra margin of error (in ms). will accept + * @extra [margin] is to allow extra margin of error (in ms). will accept * a date object, timestamp, or text format. If not specified, is * assumed to be now. See @date_format for more. * @example @@ -4916,6 +4916,16 @@ interface DateRange { start: Date; end: Date; + /** + * Clamps to be within the range if it falls outside. + * @param d Date to clamp + * @returns or closest range limit + * @example + * Date.range('2001', '2002').clamp(Date.create('2000')) -> Mon Jan 01 2001 00:00:00 + * Date.range('2001', '2002').clamp(Date.create('2002')) -> Mon Jan 01 2002 00:00:00 + **/ + clamp(d: Date): Date; + /** * Returns true if is contained inside the DateRange. * may be a date or another DateRange. @@ -4931,70 +4941,6 @@ interface DateRange { **/ contains(d: DateRange): boolean; - /** - * Return the duration of the DateRange in milliseconds. - * @returns Duration of the DateRange in milliseconds. - * @example - * Date.range('2003', '2005').duration() -> 94694400000 - **/ - duration(): number; - - /** - * Increments through the date range for each [unit], calling [fn] if it is passed. - * Returns an array of each increment visited. - * @method each[Unit]([fn]) - * @param fn Callback function for each date in the requested increments. - * @returns Array of Dates for each increment. - * @set - * eachMillisecond - * eachSecond - * eachMinute - * eachHour - * eachDay - * eachWeek - * eachMonth - * eachYear - * @example - * Date.range('2003-01', '2003-02').eachMonth() -> [...] - * Date.range('2003-01-15', '2003-01-16').eachDay() -> [...] - **/ - eachMillisecond(fn?: (d: Date) => void): Date[]; - - /** - * @see eachMillisecond - **/ - eachSecond(fn?: (d: Date) => void): Date[]; - - /** - * @see eachMillisecond - **/ - eachMinute(fn?: (d: Date) => void): Date[]; - - /** - * @see eachMillisecond - **/ - eachHour(fn?: (d: Date) => void): Date[]; - - /** - * @see eachMillisecond - **/ - eachDay(fn?: (d: Date) => void): Date[]; - - /** - * @see eachMillisecond - **/ - eachWeek(fn?: (d: Date) => void): Date[]; - - /** - * @see eachMillisecond - **/ - eachMonth(fn?: (d: Date) => void): Date[]; - - /** - * @see eachMillisecond - **/ - eachYear(fn?: (d: Date) => void): Date[]; - /** * Iterates through the DateRange for every , * calling [fn] if it is passed. Returns an array of each increment visited. @@ -5039,6 +4985,15 @@ interface DateRange { **/ isValid(): boolean; + /** + * Return the span of the DateRange in milliseconds. The span includes both the + * start and the end. + * @returns Duration of the DateRange in milliseconds. + * @example + * Date.range('2003', '2005').span() -> 63158400001 # (731 day + 1 mcsec) + **/ + span(): number; + /** * Returns a string representation of the DateRange. * @returns String representation of the DateRange. From 00cb57670891e4b830b90227e8ffac64beba97c4 Mon Sep 17 00:00:00 2001 From: Andrey Lipatkin Date: Mon, 9 May 2016 11:36:26 +0300 Subject: [PATCH 009/402] Fixing favIconUrl property name typo for TabChangeInfo class (#9249) * Fixing favIconUrl property name typo for TabChangeInfo class * Empty commit to trigger Travis CI --- chrome/chrome.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chrome/chrome.d.ts b/chrome/chrome.d.ts index cdb48b2767..bdd0271fca 100644 --- a/chrome/chrome.d.ts +++ b/chrome/chrome.d.ts @@ -6210,7 +6210,7 @@ declare namespace chrome.tabs { * The tab's new favicon URL. * @since Chrome 27. */ - faviconUrl?: string; + favIconUrl?: string; /** * The tab's new title. * @since Chrome 48. From d9e73fad7d1dedbd31ef214fb737ee3a7cab58ab Mon Sep 17 00:00:00 2001 From: Linda_pp Date: Mon, 9 May 2016 17:37:39 +0900 Subject: [PATCH 010/402] github-electron: Fix callback's return type of app.makeSingleInstance() (#9250) The callback should return `void`, not `boolean`. https://github.com/electron/electron/blob/master/docs/api/app.md#appmakesingleinstancecallback --- github-electron/github-electron-main-tests.ts | 1 - github-electron/github-electron.d.ts | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/github-electron/github-electron-main-tests.ts b/github-electron/github-electron-main-tests.ts index a2c40c1d68..00798c382b 100644 --- a/github-electron/github-electron-main-tests.ts +++ b/github-electron/github-electron-main-tests.ts @@ -45,7 +45,6 @@ var shouldQuit = app.makeSingleInstance(function(commandLine, workingDirectory) if (mainWindow.isMinimized()) mainWindow.restore(); mainWindow.focus(); } - return true; }); if (shouldQuit) { diff --git a/github-electron/github-electron.d.ts b/github-electron/github-electron.d.ts index dfcff3d83c..11223154fb 100644 --- a/github-electron/github-electron.d.ts +++ b/github-electron/github-electron.d.ts @@ -280,7 +280,7 @@ declare namespace Electron { * multiple instances of your app to run, this will ensure that only a single instance * of your app is running, and other instances signal this instance and exit. */ - makeSingleInstance(callback: (args: string[], workingDirectory: string) => boolean): boolean; + makeSingleInstance(callback: (args: string[], workingDirectory: string) => void): boolean; /** * Changes the Application User Model ID to id. */ From b332be4e133ae75c915c8dd2f4b1fe9ac4a45aa4 Mon Sep 17 00:00:00 2001 From: Isman Usoh Date: Mon, 9 May 2016 15:38:42 +0700 Subject: [PATCH 011/402] Add a new type definition for Randomstring (#9252) * Create randomstring-tests.ts * Create randomstring.d.ts --- randomstring/randomstring-tests.ts | 18 ++++++++++++++++++ randomstring/randomstring.d.ts | 19 +++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 randomstring/randomstring-tests.ts create mode 100644 randomstring/randomstring.d.ts diff --git a/randomstring/randomstring-tests.ts b/randomstring/randomstring-tests.ts new file mode 100644 index 0000000000..d612b15daf --- /dev/null +++ b/randomstring/randomstring-tests.ts @@ -0,0 +1,18 @@ +/// + +import * as randomstring from "randomstring"; + +randomstring.generate(); + +randomstring.generate(24); + +randomstring.generate({ + length: 12, + readable: true, + capitalization: "", + charset: "alphabetic" +}); + +randomstring.generate({ + charset: "abc" +}); diff --git a/randomstring/randomstring.d.ts b/randomstring/randomstring.d.ts new file mode 100644 index 0000000000..e683cef6b7 --- /dev/null +++ b/randomstring/randomstring.d.ts @@ -0,0 +1,19 @@ +// Type definitions for randomstring 1.1.4 +// Project: https://github.com/klughammer/node-randomstring +// Definitions by: Isman Usoh +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace Randomstring { + interface GenerateOptions { + length?: number; + readable?: boolean; + charset?: string; + capitalization?: string; + } + + function generate(options?: GenerateOptions): string; +} + +declare module "randomstring" { + export = Randomstring; +} From 66dcd24735660b5f0a11d4beff4df2323de639ef Mon Sep 17 00:00:00 2001 From: Gwyn Judd Date: Tue, 10 May 2016 02:57:56 +1200 Subject: [PATCH 012/402] Made fragmentOverride parameter for loadUrl optional (#9229) --- backbone/backbone-global.d.ts | 2 +- backbone/backbone-tests.ts | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/backbone/backbone-global.d.ts b/backbone/backbone-global.d.ts index 2d40a2a8a4..ef0a10f006 100644 --- a/backbone/backbone-global.d.ts +++ b/backbone/backbone-global.d.ts @@ -316,7 +316,7 @@ declare namespace Backbone { stop(): void; route(route: string, callback: Function): number; checkUrl(e?: any): void; - loadUrl(fragmentOverride: string): boolean; + loadUrl(fragmentOverride?: string): boolean; navigate(fragment: string, options?: any): boolean; static started: boolean; options: any; diff --git a/backbone/backbone-tests.ts b/backbone/backbone-tests.ts index 3669a6c4e1..50632712a6 100644 --- a/backbone/backbone-tests.ts +++ b/backbone/backbone-tests.ts @@ -166,6 +166,9 @@ function test_collection() { ////////// Backbone.history.start(); +Backbone.History.started; +Backbone.history.loadUrl(); +Backbone.history.loadUrl('12345'); namespace v1Changes { namespace events { From 9ea072966d697b32eec28a760a610992b54b8bbe Mon Sep 17 00:00:00 2001 From: Joseph M Blank Date: Mon, 9 May 2016 08:01:48 -0700 Subject: [PATCH 013/402] Added definition for jQuery Steps. (#9230) * Added definition for jQuery Steps. * Renamed files to match npm naming. * Fixed reference in test file. --- jquery-steps/jquery-steps-tests.ts | 101 ++++++++ jquery-steps/jquery-steps.d.ts | 357 +++++++++++++++++++++++++++++ 2 files changed, 458 insertions(+) create mode 100644 jquery-steps/jquery-steps-tests.ts create mode 100644 jquery-steps/jquery-steps.d.ts diff --git a/jquery-steps/jquery-steps-tests.ts b/jquery-steps/jquery-steps-tests.ts new file mode 100644 index 0000000000..e0125a3c0f --- /dev/null +++ b/jquery-steps/jquery-steps-tests.ts @@ -0,0 +1,101 @@ +/// +/// + +var labels: JQuerySteps.LabelSettings = { + cancel: 'Cancel', + current: 'Current:', + pagination: 'Paging', + finish: 'Done', + next: 'Next >', + previous: '< Previous', + loading: 'Loading...' +} + +var onStepChangingFunc: JQuerySteps.FunctionOnStepChanging = (event, currentIndex, newIndex): boolean => true; + +var onStepChangedFunc: JQuerySteps.FunctionOnStepChanged = (event, currentIndex, priorIndex) => {}; + +var onCancelledFunc: JQuerySteps.FunctionOnCancelled = (event) => {}; + +var onFinishingFunc: JQuerySteps.FunctionOnFinishing= (event, currentIndex): boolean => true; + +var onFinishedFunc: JQuerySteps.FunctionOnFinished = (event, currentIndex) => {}; + +var onInitFunc: JQuerySteps.FunctionOnInit = (event, currentIndex) => {}; + +var onContentLoadedFunc: JQuerySteps.FunctionOnContentLoaded = (event, currentIndex) => {}; + +var settings: JQuerySteps.Settings = { + headerTag: 'h3', + bodyTag: 'section', + contentContainerTag: 'div', + actionContainerTag: 'div', + stepsContainerTag: 'div', + cssClass: 'wizard', + stepsOrientation: 'vertical', + titleTemplate: '#title#', + loadingTemplate: ' #text#', + autoFocus: true, + enableAllSteps: true, + enableKeyNavigation: false, + enablePagination: false, + suppressPaginationOnFocus: false, + enableContentCache: false, + enableCancelButton: true, + enableFinishButton: false, + showFinishButtonAlways: true, + forceMoveForward: true, + saveState: true, + startIndex: 1, + transitionEffect: 'slideLeft', + transitionEffectSpeed: 400, + labels: labels, + onCanceled: onCancelledFunc, + onContentLoaded: onContentLoadedFunc, + onFinished: onFinishedFunc, + onFinishing: onFinishingFunc, + onInit: onInitFunc, + onStepChanged: onStepChangedFunc, + onStepChanging: onStepChangingFunc +} + +var wizard = $('.wizard').JQuerySteps(settings); + +var newStep1: JQuerySteps.Step = { + content: '
Content
', + title: 'Step 1' +} + +var test1 = wizard.add(newStep1); + +var newStep2: JQuerySteps.Step = { + content: '
Content
', + title: 'Step 2', + contentMode: 'async', + contentUrl: 'data.xml' +} + +var test2 = wizard.insert(0, newStep2); + +var test3 = wizard.remove(1); + +var test4 = wizard.getCurrentStep(); + +var test5 = wizard.getCurrentIndex(); + +var test6 = wizard.getStep(0); + +var newStep3: JQuerySteps.Step = { + content: '
Content
', + title: 'Step 1' +} + +var test7 = wizard.insert(0, newStep3); + +var test8 = wizard.next(); + +var test9 = wizard.previous(); + +wizard.finish(); + +wizard.destroy(); diff --git a/jquery-steps/jquery-steps.d.ts b/jquery-steps/jquery-steps.d.ts new file mode 100644 index 0000000000..4b250e6708 --- /dev/null +++ b/jquery-steps/jquery-steps.d.ts @@ -0,0 +1,357 @@ +// Type definitions for jQuery Steps v1.1.0 +// Project: http://www.jquery-steps.com/ +// Definitions by: Joseph Blank +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface JQuery { + JQuerySteps(param?: JQuerySteps.Settings): JQuerySteps.JQuerySteps; +} + +declare module JQuerySteps { + + //#region "JQuerySteps" + + export interface JQuerySteps { + /** + * Adds a new step. (chainable) + */ + add(step: Step): JQuerySteps; + + /** + * Inserts a new step to a specific position. (chainable) + */ + insert(index: number, step: Step): JQuerySteps; + + /** + * Removes a specific step by an given index. + */ + remove(index: number): boolean; + + /** + * Gets the current step object. + */ + getCurrentStep(): Step; + + /** + * Gets the current step index. + */ + getCurrentIndex(): number; + + /** + * Gets a specific step object by index. + */ + getStep(index: number): Step; + + /** + * Routes to the previous step. + */ + next(): boolean; + + /** + * Routes to the next step. + */ + previous(): boolean; + + /** + * Triggers the onFinishing and onFinished event. + */ + finish(): void; + + /** + * Removes the control functionality completely and transforms the current state to the initial HTML structure. + */ + destroy(): void; + + /** + * Skips a certain amount of steps. Not yet implemented! + */ + skip(count: number): boolean; + } + + //#endregion "JQuerySteps" + + //#region "Settings" + export interface Settings { + //#region "Appearance" + + /** + * The header tag is used to find the step button text within the declared wizard area. Default value is h1. + */ + headerTag?: string; + + /** + * The body tag is used to find the step content within the declared wizard area. Default value is div. + */ + bodyTag?: string; + + /** + * The content container tag which will be used to wrap all step contents. Default value is div. + */ + contentContainerTag?: string; + + /** + * The action container tag which will be used to wrap the pagination navigation. Default value is div. + */ + actionContainerTag?: string; + + /** + * The steps container tag which will be used to wrap the steps navigation. Default value is div. + */ + stepsContainerTag?: string; + + /** + * The css class which will be added to the outer component wrapper. Default value is wizard. + */ + cssClass?: string; + + /** + * Determines whether the steps are vertically or horizontally oriented. Default value is horizontal or 0. + * This can be horizontal (0) or vertical (1). + */ + stepsOrientation?: string|number; + + //#endregion "Appearance" + + //#region "Templates" + + /** + * The title template which will be used to create a step button. Default value is span class="number">#index#. #title#. + */ + titleTemplate?: string; + + /** + * The loading template which will be used to create the loading animation. Default value is #text#. + */ + loadingTemplate?: string; + + //#endregion "Templates" + + //#region "Behavior" + + /** + * Sets the focus to the first wizard instance in order to enable the key navigation from the begining if true. Default value is false. + */ + autoFocus?: boolean; + + /** + * Enables all steps from the begining if true (all steps are clickable). Default value is false. + */ + enableAllSteps?: boolean; + + /** + * Enables keyboard navigation if true (arrow left and arrow right). Default value is true. + */ + enableKeyNavigation?: boolean; + + /** + * Enables pagination (next, previous and finish button) if true. Default value is true. + */ + enablePagination?: boolean; + + /** + * Suppresses pagination if a form field is focused. Default value is true. + */ + suppressPaginationOnFocus?: boolean; + + /** + * Enables cache for async loaded or iframe embedded content. Default value is true. + */ + enableContentCache?: boolean; + + /** + * Shows the cancel button if enabled. Default value is false. + */ + enableCancelButton?: boolean; + + /** + * Shows the finish button if enabled. Default value is true. + */ + enableFinishButton?: boolean; + + /** + * Shows the finish button always (on each step; right beside the next button) if true. Otherwise the next button will be replaced by the finish button if the last step becomes active. Default value is false. + */ + showFinishButtonAlways?: boolean; + + /** + * Prevents jumping to a previous step. Default value is false. + */ + forceMoveForward?: boolean; + + /** + * Saves the current state (step position) to a cookie. By coming next time the last active step becomes activated. Default value is false. + */ + saveState?: boolean; + + /** + * The position to start on (zero-based). Default value is 0. + */ + startIndex?: number; + + //#endregion "Behavior" + + //#region "Transition Effects" + + /** + * The animation effect which will be used for step transitions. Default value is none or 0. + * This can be none (0), fade (1), slide (2) or slideLeft (3). + */ + transitionEffect?: string|number; + + /** + * Animation speed for step transitions (in milliseconds). Default value is 200. + */ + transitionEffectSpeed?: number; + + //#endregion "Transition Effects" + + //#region "Events" + + /** + * Fires before the step changes and can be used to prevent step changing by returning false. + */ + onStepChanging?: FunctionOnStepChanging; + + /** + * Fires after the step has changed. + */ + onStepChanged?: FunctionOnStepChanged; + + /** + * Fires after cancellation. + */ + onCanceled?: FunctionOnCancelled; + + /** + * Fires before finishing and can be used to prevent completion by returning false. Very useful for form validation. + */ + onFinishing?: FunctionOnFinishing; + + /** + * Fires after completion. + */ + onFinished?: FunctionOnFinished; + + /** + * Fires when the wizard is initialized. + */ + onInit?: FunctionOnInit; + + /** + * Fires after async content is loaded. + */ + onContentLoaded?: FunctionOnContentLoaded; + + //#endregion "Events" + + //#region "Labels" + + labels?: LabelSettings; + + //#endregion "Labels" + } + //#endregion "Settings" + + //#region "Label Settings" + + interface LabelSettings { + + /** + * Label for the cancel button. Default value is Cancel. + */ + cancel?: string; + + /** + * This label is important for accessability reasons. Indicates which step is activated. Default value is current step:. + */ + current?: string; + + /** + * This label is important for accessability reasons and describes the kind of navigation. Default value is Pagination. + */ + pagination?: string; + + /** + * Label for the finish button. Default value is Finish. + */ + finish?: string; + + /** + * Label for the next button. Default value is Next. + */ + next?: string; + + /** + * Label for the previous button. Default value is Previous. + */ + previous?: string; + + /** + * Label for the loading animation. Default value is Loading ... . + */ + loading?: string; + + } + + //#endregion "Label Settings" + + //#region "Callback Functions" + + interface FunctionOnStepChanging { + (event: string, currentIndex: number, newIndex: number): boolean; + } + + interface FunctionOnStepChanged { + (event: string, currentIndex: number, priorIndex: number): void; + } + + interface FunctionOnCancelled { + (event: string): void; + } + + interface FunctionOnFinishing { + (event: string, currentIndex: number): boolean; + } + + interface FunctionOnFinished { + (event: string, currentIndex: number): void; + } + + interface FunctionOnInit { + (event: string, currentIndex: number): void; + } + + interface FunctionOnContentLoaded { + (event: string, currentIndex: number): void; + } + + //#endregion "Callback Functions" + + //#region "Step Object" + + interface Step { + + /** + * The step title (HTML). + */ + title?: string; + + /** + * The step content (HTML). + */ + content?: string; + + /** + * Indicates how the content will be loaded. + * This can be html (0), iframe (1), or async (2). + */ + contentMode?: string|number; + + /** + * The URI that refers to the content. + */ + contentUrl?: string; + } + + //#endregion "Step Object" +} From 70e45e7ac8d35546bf9c6e0e680ac1b353378824 Mon Sep 17 00:00:00 2001 From: goonsunday Date: Mon, 9 May 2016 23:03:58 +0800 Subject: [PATCH 014/402] Add optional parameter extraHeaders to soap method. (#9233) --- soap/soap.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/soap/soap.d.ts b/soap/soap.d.ts index 36f50309b7..21fcb98514 100644 --- a/soap/soap.d.ts +++ b/soap/soap.d.ts @@ -13,7 +13,7 @@ declare module 'soap' { } interface Client extends events.EventEmitter { setSecurity(s: WSSecurity): void; - [method: string]: (args: any, fn: (err: any, result: any) => void, options?: any) => void; + [method: string]: (args: any, fn: (err: any, result: any) => void, options?: any, extraHeaders?: any) => void; addSoapHeader(headJSON: any): void; } function createClient(wsdlPath: string, options: any, fn: (err: any, client: Client) => void): void; From d907a0156a86dc4257701d08c736e50679236572 Mon Sep 17 00:00:00 2001 From: Luka Jeran Date: Mon, 9 May 2016 17:04:41 +0200 Subject: [PATCH 015/402] Fix IFormController methods in angular.d.ts (#9234) --- angularjs/angular.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 3d2b248637..98484e16f4 100644 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -389,9 +389,9 @@ declare namespace angular { $submitted: boolean; $error: any; $pending: any; - $addControl(control: INgModelController): void; - $removeControl(control: INgModelController): void; - $setValidity(validationErrorKey: string, isValid: boolean, control: INgModelController): void; + $addControl(control: INgModelController | IFormController): void; + $removeControl(control: INgModelController | IFormController): void; + $setValidity(validationErrorKey: string, isValid: boolean, control: INgModelController | IFormController): void; $setDirty(): void; $setPristine(): void; $commitViewValue(): void; From e42789a720709a86b0bc39bce8ea81a8d12c4917 Mon Sep 17 00:00:00 2001 From: Matthieu Mourisson Date: Mon, 9 May 2016 17:23:29 +0200 Subject: [PATCH 016/402] Add type definition for morris.js (morrisjs.github.io/morris.js/) (#9189) * Added definition for line, area and donut chart options * Added bar charts options * Added JSDoc everywhere * Added morris-test.ts test * Added SetData function on chart objects * renamed morris.d.ts to morris.js.d.ts * rename morris-test.ts to morris-tests.ts * test fix * file renaming --- morris.js/morris.js-tests.ts | 79 +++++++++++++++++++ morris.js/morris.js.d.ts | 146 +++++++++++++++++++++++++++++++++++ 2 files changed, 225 insertions(+) create mode 100644 morris.js/morris.js-tests.ts create mode 100644 morris.js/morris.js.d.ts diff --git a/morris.js/morris.js-tests.ts b/morris.js/morris.js-tests.ts new file mode 100644 index 0000000000..93f3ab95c5 --- /dev/null +++ b/morris.js/morris.js-tests.ts @@ -0,0 +1,79 @@ +/// + +let data = [{ + label: "2010-5-1", + value: 15 +}]; + +let donutChart = Morris.Donut({ + element: "donutChartId", + data: data, + colors: ["chartreuse"], + resize: false +}); + +let barChart = Morris.Bar({ + element: "barChartId", + data: data, + xkey: "label", + ykeys: ["value"], + labels: ["labels"], + hideHover: "auto", + axes: false, + grid: true, + gridTextColor: "bisque", + gridTextSize: 42, + gridTextFamily: "comic sans", + gridTextWeight: "bold", + barColors: ["aquamarine"], + stacked: false, + hoverCallback: (index, options, content, row) => index + " " + content +}); + +let lineChart = Morris.Line({ + element: "lineChartId", + data: data, + xkey: "label", + ykeys: ["value"], + labels: ["labels"], + lineColors: ["bisque"], + lineWidth: 42, + pointSize: 42, + pointFillColors: ["bisque"], + pointStrokeColors: ["bisque"], + ymax: "auto 15", + ymin: "auto 10", + smooth: false, + hoverCallback: (index, options, content, row) => index + " " + content, + parseTime: false, + postUnits: "%", + preUnits: "£", + dateFormat: (timestamp) => timestamp.toString(), + xLabels: "30min", + xLabelFormat: (date) => date.toString(), + xLabelAngle: 42, + yLabelFormat: (val) => val.toString(), + goals: [42], + goalStrokeWidth: 42, + goalLineColors: ["bisque"], + events: ["bisque"], + eventStrokeWidth: 42, + eventLineColors: ["bisque"], + continuousLine: false, + axes: false, + grid: false, + gridTextColor: "bisque", + gridTextSize: 42, + gridTextFamily: "comic sans", + gridTextWeight: "bold", + fillOpacity: 42 +}); + +let areaChart = Morris.Area({ + element: "areaChartId", + data: data, + xkey: "label", + ykeys: ["value"], + labels: ["labels"], + behaveLikeLine: false +}); diff --git a/morris.js/morris.js.d.ts b/morris.js/morris.js.d.ts new file mode 100644 index 0000000000..79598ee5c3 --- /dev/null +++ b/morris.js/morris.js.d.ts @@ -0,0 +1,146 @@ +// Type definitions for morris.js 0.5.1 +// Project: http://morrisjs.github.io/morris.js/ +// Definitions by: Matthieu Mourisson +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace morris { + type AutoAlways = "auto" | "always"; + + type Interval = "decade" | "year" | "month" | "week" | "day" | "hour" | "30min" | "15min" | "10min" | "5min" | "minute" | "30sec" | "15sec" | "10sec" | "5sec" | "second"; + + interface IChartOptions { + /** The ID of (or a reference to) the element into which to insert the graph. */ + element: any; + /** Set to true to enable automatic resizing when the containing element resizes. (default: false). */ + resize?: boolean; + } + + interface IGridChartOptions extends IChartOptions { + /** The data to plot. This is an array of objects, containing x and y attributes as described by the xkey and ykeys options. */ + data: any[]; + /** A string containing the name of the attribute that contains X labels. */ + xkey: string; + /** A list of strings containing names of attributes that contain Y values (one for each series of data to be plotted). */ + ykeys: string[]; + /** A list of strings containing labels for the data series to be plotted (corresponding to the values in the ykeys option). */ + labels: string[]; + /** Set the visibility of the hover legend (see documentation). */ + hideHover?: boolean | AutoAlways; + /** Set to false to disable drawing the x and y axes. */ + axes?: boolean; + /** Set to false to disable drawing the horizontal grid lines. */ + grid?: boolean; + /** Set the color of the axis labels (default: #888). */ + gridTextColor?: string; + /** Set the point size of the axis labels (default: 12). */ + gridTextSize?: number; + /** Set the font family of the axis labels (default: sans-serif). */ + gridTextFamily?: string; + /** Set the font weight of the axis labels (default: normal). */ + gridTextWeight?: string; + } + + interface ILineOptions extends IGridChartOptions { + /** Array containing colors for the series lines/points. */ + lineColors?: string[]; + /** Width of the series lines, in pixels. */ + lineWidth?: number; + /** Diameter of the series points, in pixels. */ + pointSize?: number; + /** Colors for the series points. By default uses the same values as lineColors */ + pointFillColors?: string[]; + /** Colors for the outlines of the series points. (#ffffff by default). */ + pointStrokeColors?: string[]; + /** Max. bound for Y-values. Alternatively, set this to 'auto' to compute automatically, or 'auto [num]' to automatically compute and ensure that the max y-value is at least [num]. */ + ymax?: number | string; + /** Min. bound for Y-values. Alternatively, set this to 'auto' to compute automatically, or 'auto [num]' to automatically compute and ensure that the min y-value is at most [num]. */ + ymin?: number | string; + /** Set to false to disable line smoothing. */ + smooth?: boolean; + /** Provide a function on this option to generate custom hover legends. */ + hoverCallback?: (index: number, options: ILineOptions, content: string, row: any) => string; + /** Set to false to skip time/date parsing for X values, instead treating them as an equally-spaced series. */ + parseTime?: boolean; + /** Set to a string value (eg: '%') to add a label suffix all y-labels. */ + postUnits?: string; + /** Set to a string value (eg: '$') to add a label prefix all y-labels. */ + preUnits?: string; + /** A function that accepts millisecond timestamps and formats them for display as chart labels. */ + dateFormat?: (timestamp: number) => string; + /** Sets the x axis labelling interval. By default the interval will be automatically computed. */ + xLabels?: Interval; + /** A function that accepts Date objects and formats them for display as x-axis labels. Overrides the default formatter chosen by the automatic labeller or the xLabels option. */ + xLabelFormat?: (date: Date) => string; + /** The angle in degrees from horizontal to draw x-axis labels. */ + xLabelAngle?: number; + /** A function that accepts y-values and formats them for display as y-axis labels. */ + yLabelFormat?: (val: any) => string; + /** A list of y-values to draw as horizontal 'goal' lines on the chart. */ + goals?: number[]; + /** Width, in pixels, of the goal lines. */ + goalStrokeWidth?: number; + /** Array of color values to use for the goal line colors. If you list fewer colors here than you have lines in goals, then the values will be cycled. */ + goalLineColors?: string[]; + /** A list of x-values to draw as vertical 'event' lines on the chart. */ + events?: string[]; + /** Width, in pixels, of the event lines. */ + eventStrokeWidth?: number; + /** Array of color values to use for the event line colors. If you list fewer colors here than you have lines in events, then the values will be cycled. */ + eventLineColors?: string[]; + /** Define how null and undefined values are handled (see documentation). */ + continuousLine?: boolean; + /** Change the opacity of the area fill colour. Accepts values between 0.0 (for completely transparent) and 1.0 (for completely opaque). */ + fillOpacity?: number; + } + + interface IAreaOptions extends ILineOptions { + /** Set to true to overlay the areas on top of each other instead of stacking them. */ + behaveLikeLine?: boolean; + } + + interface IBarOptions extends IGridChartOptions { + /** Array containing colors for the series bars. */ + barColors?: string[]; + /** Set to true to draw bars stacked vertically. */ + stacked?: boolean; + /** Provide a function on this option to generate custom hover legends. */ + hoverCallback?: (index: number, options: IBarOptions, content: string, row: any) => string; + } + + interface IDonutData { + /** Label of the segment of the donut chart.*/ + label: string; + /** Size of the segment of the donut chart.*/ + value: number; + } + + interface IDonutOptions extends IChartOptions { + /** The data to plot. */ + data: IDonutData[]; + /** An array of strings containing HTML-style hex colors for each of the donut segments. */ + colors?: string[]; + /** A function that will translate a y-value into a label for the centre of the donut. */ + formatter?: (y: number, data: IDonutData) => string; + } + + class GridChart { + setData(data: any[], redraw?: boolean): void; + } + + class DonutChart { + setData(data: IDonutData[], redraw?: boolean): void; + } + + class MorrisStatic { + /** Create a line chart. */ + Line: (options: ILineOptions) => GridChart; + /** Create an area chart. */ + Area: (options: IAreaOptions) => GridChart; + /** Create a bar chart. */ + Bar: (options: IBarOptions) => GridChart; + /** Create a Donut chart. */ + Donut: (options: IDonutOptions) => DonutChart; + } +} + +declare var Morris: morris.MorrisStatic; From d075e7c29ebbc24c691693a249d8e223d515b851 Mon Sep 17 00:00:00 2001 From: Cyril Schumacher Date: Mon, 9 May 2016 17:25:14 +0200 Subject: [PATCH 017/402] Add definition for "restler". (#9244) --- restler/restler-tests.ts | 46 ++++++++ restler/restler.d.ts | 237 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 283 insertions(+) create mode 100644 restler/restler-tests.ts create mode 100644 restler/restler.d.ts diff --git a/restler/restler-tests.ts b/restler/restler-tests.ts new file mode 100644 index 0000000000..a709fc3375 --- /dev/null +++ b/restler/restler-tests.ts @@ -0,0 +1,46 @@ +/// + +import rest = require("restler"); + +rest.get("http://google.com").on("complete", function(result) { + if (result instanceof Error) { + console.log("Error:", result.message); + this.retry(5000); // try again after 5 sec + } else { + console.log(result); + } +}); + +rest.get("http://twaud.io/api/v1/users/danwrong.json").on("complete", function(data) { + console.log(data[0].message); // auto convert to object +}); + +rest.get("http://twaud.io/api/v1/users/danwrong.xml").on("complete", function(data) { + console.log(data[0].sounds[0].sound[0].message); // auto convert to object +}); + +rest.get("http://someslowdomain.com", { timeout: 10000 }).on("timeout", function(ms) { + console.log("did not return within " + ms + " ms"); +}).on("complete", function(data, response) { + console.log("did not time out"); +}); + +rest.post("http://user:pass@service.com/action", { + data: { id: 334 }, +}).on("complete", function(data, response) { + if (response.statusCode == 201) { + // you can get at the raw response like this... + } +}); + +// post JSON +var jsonData = { id: 334 }; +rest.postJson("http://example.com/action", jsonData).on("complete", function(data, response) { + // handle response +}); + +// put JSON +var jsonData = { id: 334 }; +rest.putJson("http://example.com/action", jsonData).on("complete", function(data, response) { + // handle response +}); diff --git a/restler/restler.d.ts b/restler/restler.d.ts new file mode 100644 index 0000000000..b504a4e75d --- /dev/null +++ b/restler/restler.d.ts @@ -0,0 +1,237 @@ +// Type definitions for restler 3.1.0 +// Project: https://github.com/danwrong/restler +// Definitions by: Cyril Schumacher +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "restler" { + import * as http from "http"; + + /** + * Interface for resler class. + * @interface + */ + interface RestlerStatic { + /** + * Create a DELETE request. + * @param {string} url A url address. + * @param {RestlerOptions} options Options. + * @return {RestlerResult} Result. + */ + del(url: string, options?: Object): RestlerResult; + + /** + * Create a GET request. + * @param {string} url A url address. + * @param {RestlerOptions} options Options. + * @return {RestlerResult} Result. + */ + get(url: string, options?: RestlerOptions): RestlerResult; + + /** + * Create a HEAD request. + * @param {string} url A url address. + * @param {RestlerOptions} options Options. + * @return {RestlerResult} Result. + */ + head(url: string, options?: RestlerOptions): RestlerResult; + + /** + * Send json data via GET method. + * @param {string} url A url address. + * @param {RestlerOptions} options Options. + * @return {RestlerResult} Result. + */ + json(url: string, options?: RestlerOptions): RestlerResult; + + /** + * Create a PATCH request. + * @param {string} url A url address. + * @param {RestlerOptions} options Options. + * @return {RestlerResult} Result. + */ + patch(url: string, options?: RestlerOptions): RestlerResult; + + /** + * Send json data via PATCH method. + * @param {string} url A url address. + * @param {RestlerOptions} options Options. + * @return {RestlerResult} Result. + */ + patchJson(url: string, options?: RestlerOptions): RestlerResult; + + /** + * Create a POST request. + * @param {string} url A url address. + * @param {RestlerOptions} options Options. + * @return {RestlerResult} Result. + */ + post(url: string, options?: RestlerOptions): RestlerResult; + + /** + * Send json data via POST method. + * @param {string} url A url address. + * @param {RestlerOptions} options Options. + * @return {RestlerResult} Result. + */ + postJson(url: string, options?: RestlerOptions): RestlerResult; + + /** + * Create a PUT request. + * @param {string} url A url address. + * @param {RestlerOptions} options Options. + * @return {RestlerResult} Result. + */ + put(url: string, options?: RestlerOptions): RestlerResult; + + /** + * Send json data via PUT method. + * @param {string} url A url address. + * @param {RestlerOptions} options Options. + * @return {RestlerResult} Result. + */ + putJson(url: string, options?: RestlerOptions): RestlerResult; + + /** + * Create a PUT request. + * @param {string} url A url address. + * @param {RestlerOptions} options Options. + * @return {RestlerResult} Result. + */ + service(url: string, options?: RestlerOptions): RestlerResult; + } + + /** + * Interface for the header. + * @interface + */ + interface RestlerOptionsHeader { + [headerName: string]: string; + } + + /** + * Interface for restler options. + * @interface + */ + interface RestlerOptions { + /** + * OAuth Bearer Token. + * @type {string} + */ + accessToken?: string; + + /** + * HTTP Agent instance to use. If not defined globalAgent will be used. If false opts out of connection pooling with an Agent, defaults request to Connection: close. + * @type {any} + */ + agent?: any; + + /** + * A http.Client instance if you want to reuse or implement some kind of connection pooling. + * @type {any} + */ + client?: any; + + /** + * Data to be added to the body of the request. + * @type {any} + */ + data?: any; + + /** + * Encoding of the response body + * @type {string} + */ + decoding?: string; + + /** + * Encoding of the request body. + * @type {string} + */ + encoding?: string; + + /** + * If set will recursively follow redirects. + * @type {boolean} + */ + followRedirects?: boolean; + + /** + * A hash of HTTP headers to be sent. + * @type {RestlerOptionsHeader} + */ + headers?: RestlerOptionsHeader; + + /** + * Request method + * @type {string} + */ + method?: string; + + /** + * If set the data passed will be formatted as multipart/form-encoded. + * @type {boolean} + */ + multipart?: boolean; + + /** + * A function that will be called on the returned data. Use any of predefined restler.parsers. + * @type {any} + */ + parser?: any; + + /** + * Basic auth password. + * @type {string} + */ + password?: string; + + /** + * Query string variables as a javascript object, will override the querystring in the URL. + * @type {any} + */ + query?: any; + + /** + * If true, the server certificate is verified against the list of supplied CAs. + * An 'error' event is emitted if verification fails. Verification happens at the connection level, before the HTTP request is sent. + * @type {boolean} + */ + rejectUnauthorized?: boolean; + + /** + * Emit the timeout event when the response does not return within the said value (in ms). + * @type {number} + */ + timeout?: number; + + /** + * Basic auth username. + * @type {string} + */ + username?: string; + + /** + * Options for xml2js. + * @type {any} + */ + xml2js?: any; + } + + /** + * Interface for restler result. + * @interface + */ + interface RestlerResult { + /** + * Adds the listener function to the end of the listeners array for the event named eventName. + * @param {string} eventName The name of the event. + * @param {Function} listener The callback function + */ + on(eventName: string, listener: (data?: any, response?: http.ServerResponse) => void): RestlerResult; + } + + let restler: RestlerStatic; + export = restler; +} From 6711754cf0bac2db7eb2273ee30125b2f6b7f3e1 Mon Sep 17 00:00:00 2001 From: Evan Hahn Date: Mon, 9 May 2016 08:28:14 -0700 Subject: [PATCH 018/402] Add Evan Hahn as a contributor to the Helmet module (#9248) This is after contributing the following commits: - 329055d0c67349f7588a18880f71268934c9a461 - b20485f5987087a29d68f5537bcf10007930d8e9 - db57ec3afd5cd3ee559835d0453cc96f44db06ca - 5c80bce0dd1e1b7f3f5863e2bf8742b3aca05997 - 70262bcb3e9d8b990d6f8b1d783ce66158cea760 --- CONTRIBUTORS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 6140babecd..4317128869 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -695,7 +695,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](heap/heap.d.ts) [heap](https://github.com/qiao/heap.js) by [Ryan McNamara](https://github.com/ryan10132) * [:link:](heatmap.js/heatmap.d.ts) [heatmap.js](https://github.com/pa7/heatmap.js) by [Yang Guan](https://github.com/lookuptable) * [:link:](hellojs/hellojs.d.ts) [hello.js](http://adodson.com/hello.js) by [Pavel Zika](https://github.com/PavelPZ) -* [:link:](helmet/helmet.d.ts) [helmet](https://github.com/helmetjs/helmet) by [Cyril Schumacher](https://github.com/cyrilschumacher) +* [:link:](helmet/helmet.d.ts) [helmet](https://github.com/helmetjs/helmet) by [Cyril Schumacher](https://github.com/cyrilschumacher), [Evan Hahn](https://github.com/EvanHahn) * [:link:](highcharts/highcharts.d.ts) [Highcharts](http://www.highcharts.com) by [Damiano Gambarotto](http://github.com/damianog), [Dan Lewi Harkestad](http://github.com/baltie) * [:link:](highcharts-ng/highcharts-ng.d.ts) [highcharts-ng](https://github.com/pablojim/highcharts-ng) by [Scott Hatcher](https://github.com/scatcher) * [:link:](highland/highland.d.ts) [Highland](http://highlandjs.org) by [Bart van der Schoor](https://github.com/Bartvds) From 3d51112b02e540677f95a1bb78d2f28e517ed515 Mon Sep 17 00:00:00 2001 From: Miroshin Stepan Date: Mon, 9 May 2016 19:33:44 +0400 Subject: [PATCH 019/402] xadesjs (#9256) * xadesjs beta * Add test & set version * Fix def errors * Change Promise to PromiseType * Fix test error --- xadesjs/xadesjs-tests.ts | 47 ++ xadesjs/xadesjs.d.ts | 1085 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 1132 insertions(+) create mode 100644 xadesjs/xadesjs-tests.ts create mode 100644 xadesjs/xadesjs.d.ts diff --git a/xadesjs/xadesjs-tests.ts b/xadesjs/xadesjs-tests.ts new file mode 100644 index 0000000000..e36f903945 --- /dev/null +++ b/xadesjs/xadesjs-tests.ts @@ -0,0 +1,47 @@ +/// + +let xmlString = ""; +let xmlDoc = new DOMParser().parseFromString(xmlString, "application/xml"); +let signedXml = new xadesjs.SignedXml(xmlDoc); + +let alg = { + name: "ECDSA", + namedCurve: "P-256" +}; +xadesjs.Application.crypto.subtle.generateKey( + alg, + false, + ["sign", "verify"] +) + .then((keys: CryptoKeyPair) => { + signedXml.SigningKey = keys.privateKey; + + // Add the key to the SignedXml document. + // Create a reference to be signed. + let reference = new xadesjs.Reference(); + reference.Uri = ""; + // Add an enveloped transformation to the reference. + reference.AddTransform(new xadesjs.XmlDsigEnvelopedSignatureTransform()); + // Add the reference to the SignedXml object. + signedXml.AddReference(reference); + // Set prefix for Signature namespace + signedXml.Prefix = "ds"; + + // Compute the signature. + return signedXml.ComputeSignature({ name: "ECDSA", hash: { name: "SHA-256" } } as any); + }) + .then(function () { + // Append signature + let xmlDigitalSignature = signedXml.GetXml(); + xmlDoc.documentElement.appendChild(xmlDigitalSignature); + + // Serialize XML document + let signedDocument = new XMLSerializer().serializeToString(xmlDoc); + return Promise.resolve(signedDocument); + }) + .then((doc: string) => { + console.log("Signed document:", doc); + }) + .catch((e: any) => { + console.error("Error", e); + }); \ No newline at end of file diff --git a/xadesjs/xadesjs.d.ts b/xadesjs/xadesjs.d.ts new file mode 100644 index 0000000000..cad137db05 --- /dev/null +++ b/xadesjs/xadesjs.d.ts @@ -0,0 +1,1085 @@ +// Type definitions for xadesjs v1.0.0 +// Project: https://github.com/PeculiarVentures/xadesjs +// Definitions by: Stepan Miroshin +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/** + * A pure Javascript implementation of XMLDSIG and XAdES based on Web Crypto https://xadesjs.com + * v1.0.0 + */ + +declare namespace xadesjs { + + type PromiseType = any; + + const APPLICATION_XML: string; + + class XmlError extends Error { + stack: any; + constructor(code: XE, ...args: any[]); + } + + enum XE { + NONE = 0, + NULL_REFERENCE = 1, + METHOD_NOT_IMPLEMENTED = 2, + METHOD_NOT_SUPPORTED = 3, + PARAM_REQUIRED = 4, + CONVERTER_UNSUPPORTED = 5, + ELEMENT_MALFORMED = 6, + CRYPTOGRAPHIC = 7, + CRYPTOGRAPHIC_NO_MODULE = 8, + CRYPTOGRAPHIC_UNKNOWN_TRANSFORM = 9, + ALGORITHM_NOT_SUPPORTED = 10, + ALGORITHM_WRONG_NAME = 11, + XML_EXCEPTION = 12, + } + + interface CryptoEx extends Crypto { + name: string; + } + + class Application { + /** + * Sets crypto engine for the current Application + * @param {string} name + * @param {Crypto} crypto + * @returns void + */ + static setEngine(name: string, crypto: Crypto): void; + /** + * Gets the crypto module from the Application + */ + static crypto: CryptoEx; + static isNodePlugin(): boolean; + } + + enum XmlNodeType { + None = 0, + Element = 1, + Attribute = 2, + Text = 3, + CDATA = 4, + EntityReference = 5, + Entity = 6, + ProcessingInstruction = 7, + Comment = 8, + Document = 9, + DocumentType = 10, + DocumentFragment = 11, + Notation = 12, + Whitespace = 13, + SignificantWhitespace = 14, + EndElement = 15, + EndEntity = 16, + XmlDeclaration = 17, + } + + interface IXmlSerializable { + Prefix: string; + /** + * Writes object to XML node + * @returns Node + */ + GetXml(): Node; + /** + * Reads XML from string + * @param {Node} node + * @returns void + */ + LoadXml(node: Node): void; + } + + abstract class XmlObject implements IXmlSerializable { + protected m_prefix: string; + Prefix: string; + protected GetPrefix(): string; + GetXml(): Node; + GetXml(document: Document): Node; + LoadXml(node: Node): void; + toString(): string; + protected getAttribute(xel: Element, attribute: string): string; + } + + const DEFAULT_ROOT_NAME: string; + function IsEqualsEmptyStrings(s1: string, s2: string): boolean; + /** + * Creates new instance of XmlDocument with given name of root element + * @param {string} root Name of root element + * @param {string} namespaceUri + * @param {string} prefix + * @returns Document + */ + function CreateDocument(root?: string, namespaceUri?: string, prefix?: string): Document; + /** + * Returns signle Node from given Node + * @param {Node} node + * @param {string} path + * @returns Node + */ + function SelectSingleNode(node: Node, path: string): Node; + + function findAttr(node: Node, localName: string, nameSpace?: string): Attr; + function findFirst(doc: Node, xpath: string): Node; + function findChilds(node: Node, localName: string, nameSpace?: string): Node[]; + interface IAssocArray { + [index: string]: string; + } + function encodeSpecialCharactersInAttribute(attributeValue: string): string; + function encodeSpecialCharactersInText(text: string): string; + function SelectNamespaces(node: Element): Node[]; + + class Convert { + static ToBase64UrlString(text: string): string; + static FromBase64UrlString(base64UrlText: string): string; + static ToBase64String(text: string): string; + static FromBase64String(base64Text: string): string; + static Base64UrlToBase64(base64url: string): string; + static Base64ToBase64Url(base64: string): string; + static ToBufferUtf8String(text: string): Uint8Array; + static FromBufferUtf8String(buffer: Uint8Array): string; + static ToBufferString(text: string): Uint8Array; + static FromBufferString(buffer: ArrayBuffer): string; + static FromBufferString(buffer: Uint8Array): string; + } + + interface IAlgorithm { + algorithm: Algorithm; + xmlNamespace: string; + getAlgorithmName(): string; + } + interface IHashAlgorithm extends IAlgorithm { + getHash(xml: string): PromiseType; + } + interface IHashAlgorithmConstructable { + new (): IHashAlgorithm; + } + abstract class XmlAlgorithm implements IAlgorithm { + algorithm: Algorithm; + xmlNamespace: string; + getAlgorithmName(): string; + } + abstract class HashAlgorithm extends XmlAlgorithm implements IHashAlgorithm { + getHash(xml: string): PromiseType; + } + interface ISignatureAlgorithm extends IAlgorithm { + getSignature(signedInfo: string, signingKey: CryptoKey, algorithm: Algorithm): PromiseType; + verifySignature(signedInfo: string, key: CryptoKey, signatureValue: string, algorithm?: Algorithm): PromiseType; + } + interface ISignatureAlgorithmConstructable { + new (): ISignatureAlgorithm; + } + abstract class SignatureAlgorithm extends XmlAlgorithm implements ISignatureAlgorithm { + /** + * Sign the given string using the given key + */ + getSignature(signedInfo: string, signingKey: CryptoKey, algorithm: Algorithm): PromiseType; + /** + * Verify the given signature of the given string using key + */ + verifySignature(signedInfo: string, key: CryptoKey, signatureValue: string, algorithm?: Algorithm): PromiseType; + } + + const SHA1: string; + const SHA224: string; + const SHA256: string; + const SHA384: string; + const SHA512: string; + const SHA1_NAMESPACE: string; + const SHA224_NAMESPACE: string; + const SHA256_NAMESPACE: string; + const SHA384_NAMESPACE: string; + const SHA512_NAMESPACE: string; + class Sha1 extends HashAlgorithm { + algorithm: { + name: string; + }; + xmlNamespace: string; + } + class Sha224 extends HashAlgorithm { + algorithm: { + name: string; + }; + xmlNamespace: string; + } + class Sha256 extends HashAlgorithm { + algorithm: { + name: string; + }; + xmlNamespace: string; + } + class Sha384 extends HashAlgorithm { + algorithm: { + name: string; + }; + xmlNamespace: string; + } + class Sha512 extends HashAlgorithm { + algorithm: { + name: string; + }; + xmlNamespace: string; + } + + // RSA PKCS1 + + const RSA_PKCS1: string; + const RSA_PKCS1_SHA1_NAMESPACE: string; + const RSA_PKCS1_SHA224_NAMESPACE: string; + const RSA_PKCS1_SHA256_NAMESPACE: string; + const RSA_PKCS1_SHA384_NAMESPACE: string; + const RSA_PKCS1_SHA512_NAMESPACE: string; + + class RsaPkcs1Sha1 extends SignatureAlgorithm { + algorithm: any; + xmlNamespace: string; + } + class RsaPkcs1Sha224 extends SignatureAlgorithm { + algorithm: any; + xmlNamespace: string; + } + class RsaPkcs1Sha256 extends SignatureAlgorithm { + algorithm: any; + xmlNamespace: string; + } + class RsaPkcs1Sha384 extends SignatureAlgorithm { + algorithm: any; + xmlNamespace: string; + } + class RsaPkcs1Sha512 extends SignatureAlgorithm { + algorithm: any; + xmlNamespace: string; + } + + // RSA PSS + + const RSA_PSS: string; + const RSA_PSS_WITH_PARAMS_NAMESPACE: string; + const RSA_PSS_WITH_PARAMS_MGF1_NAMESPACE: string; + + class RsaPssSha1 extends SignatureAlgorithm { + algorithm: any; + xmlNamespace: string; + } + class RsaPssSha224 extends SignatureAlgorithm { + algorithm: any; + xmlNamespace: string; + } + class RsaPssSha256 extends SignatureAlgorithm { + algorithm: any; + xmlNamespace: string; + } + class RsaPssSha384 extends SignatureAlgorithm { + algorithm: any; + xmlNamespace: string; + } + class RsaPssSha512 extends SignatureAlgorithm { + algorithm: any; + xmlNamespace: string; + } + class PssAlgorithmParams extends XmlObject { + private m_digest_method; + private m_salt_length; + private m_mgf; + private element; + dsPrefix: string; + DigestMethod: string; + SaltLength: number; + MGF: string; + GetXml(): Element; + LoadXml(value: Element): void; + } + + // HMAC + + const HMAC_ALGORITHM: string; + const HMAC_SHA1_NAMESPACE: string; + const HMAC_SHA256_NAMESPACE: string; + const HMAC_SHA384_NAMESPACE: string; + const HMAC_SHA512_NAMESPACE: string; + + class HmacSha1 extends SignatureAlgorithm { + algorithm: any; + xmlNamespace: string; + } + class HmacSha256 extends SignatureAlgorithm { + algorithm: any; + xmlNamespace: string; + } + class HmacSha384 extends SignatureAlgorithm { + algorithm: any; + xmlNamespace: string; + } + class HmacSha512 extends SignatureAlgorithm { + algorithm: any; + xmlNamespace: string; + } + + // ECDSA + + const ECDSA_SIGN_ALGORITHM: string; + const ECDSA_SHA1_NAMESPACE: string; + const ECDSA_SHA224_NAMESPACE: string; + const ECDSA_SHA256_NAMESPACE: string; + const ECDSA_SHA384_NAMESPACE: string; + const ECDSA_SHA512_NAMESPACE: string; + class EcdsaSha1 extends SignatureAlgorithm { + algorithm: any; + xmlNamespace: string; + } + class EcdsaSha224 extends SignatureAlgorithm { + algorithm: any; + xmlNamespace: string; + } + class EcdsaSha256 extends SignatureAlgorithm { + algorithm: any; + xmlNamespace: string; + } + class EcdsaSha384 extends SignatureAlgorithm { + algorithm: any; + xmlNamespace: string; + } + class EcdsaSha512 extends SignatureAlgorithm { + algorithm: any; + xmlNamespace: string; + } + + /** + * Represents an element. + */ + class X509Certificate { + protected raw: Uint8Array; + protected cert_simpl: any; + protected publicKey: CryptoKey; + constructor(rawData?: Uint8Array); + /** + * Loads X509Certificate from DER data + * @param {Uint8Array} rawData + */ + protected LoadFromRawData(rawData: Uint8Array): void; + /** + * Gets the public key from the X509Certificate + */ + PublicKey: CryptoKey; + /** + * Returns DER raw of X509Certificate + */ + GetRawCertData(): Uint8Array; + /** + * Returns public key from X509Certificate + * @param {Algorithm} algorithm + * @returns PromiseType + */ + exportKey(algorithm: Algorithm): PromiseType; + } + + enum X509IncludeOption { + None = 0, + EndCertOnly = 1, + ExcludeRoot = 2, + WholeChain = 3, + } + interface X509IssuerSerial { + issuerName: string; + serialNumber: string; + } + /** + * Represents an subelement of an XMLDSIG or XML Encryption element. + */ + class KeyInfoX509Data extends XmlObject implements KeyInfoClause { + + constructor(); + constructor(rgbCert: Uint8Array); + constructor(cert: X509Certificate); + /** + * Gets public key of the X509Data + */ + Key: CryptoKey; + importKey(key: CryptoKey): PromiseType; + /** + * Exports key from X509Data object + * @param {Algorithm} alg + * @returns PromiseType + */ + exportKey(alg: Algorithm): PromiseType; + /** + * Gets a list of the X.509v3 certificates contained in the KeyInfoX509Data object. + */ + Certificates: X509Certificate[]; + /** + * Gets or sets the Certificate Revocation List (CRL) contained within the KeyInfoX509Data object. + */ + CRL: Uint8Array; + /** + * Gets a list of X509IssuerSerial structures that represent an issuer name and serial number pair. + */ + IssuerSerials: X509IssuerSerial[]; + /** + * Gets a list of the subject key identifiers (SKIs) contained in the KeyInfoX509Data object. + */ + SubjectKeyIds: Uint8Array[]; + /** + * Gets a list of the subject names of the entities contained in the KeyInfoX509Data object. + */ + SubjectNames: string[]; + /** + * Adds the specified X.509v3 certificate to the KeyInfoX509Data. + * @param {X509Certificate} certificate + * @returns void + */ + AddCertificate(certificate: X509Certificate): void; + /** + * Adds the specified issuer name and serial number pair to the KeyInfoX509Data object. + * @param {string} issuerName + * @param {string} serialNumber + * @returns void + */ + AddIssuerSerial(issuerName: string, serialNumber: string): void; + /** + * Adds the specified subject key identifier (SKI) to the KeyInfoX509Data object. + * @param {string | Uint8Array} subjectKeyId + * @returns void + */ + AddSubjectKeyId(subjectKeyId: string): void; + AddSubjectKeyId(subjectKeyId: Uint8Array): void; + /** + * Adds the subject name of the entity that was issued an X.509v3 certificate to the KeyInfoX509Data object. + * @param {string} subjectName + * @returns void + */ + AddSubjectName(subjectName: string): void; + /** + * Returns an XML representation of the KeyInfoX509Data object. + * @returns Element + */ + GetXml(): Element; + /** + * Parses the input XmlElement object and configures the internal state of the KeyInfoX509Data object to match. + * @param {Element} element + * @returns void + */ + LoadXml(element: Element): void; + } + + interface IJwkRsa { + alg: string; + kty: string; + e: string; + n: string; + ext: boolean; + } + /** + * Represents the element of an XML signature. + */ + class RsaKeyValue extends XmlObject implements KeyInfoClause { + /** + * Gets or sets the instance of RSA that holds the public key. + */ + Key: CryptoKey; + /** + * Gets the algorithm of the public key + */ + Algorithm: ISignatureAlgorithm; + /** + * Gets the Modulus of the public key + */ + Modulus: Uint8Array; + /** + * Gets the Exponent of the public key + */ + Exponent: Uint8Array; + constructor(); + /** + * Imports key to the RSAKeyValue object + * @param {CryptoKey} key + * @returns PromiseType + */ + importKey(key: CryptoKey): PromiseType; + /** + * Exports key from the RSAKeyValue object + * @param {Algorithm} alg + * @returns PromiseType + */ + exportKey(alg: Algorithm): PromiseType; + /** + * Returns the XML representation of the RSA key clause. + * @returns Element + */ + GetXml(): Element; + /** + * Loads an RSA key clause from an XML element. + * @param {Element} element + * @returns void + */ + LoadXml(element: Element): void; + } + + type NamedCurve = "P-256" | "P-384" | "P-521"; + + interface IJwkEcdsa { + crv: NamedCurve; + kty: "EC"; + x: string; + y: string; + ext: boolean; + } + + /** + * Represents the element of an XML signature. + */ + class EcdsaKeyValue extends XmlObject implements KeyInfoClause { + /** + * Gets or sets the instance of ECDSA that holds the public key. + */ + Key: CryptoKey; + /** + * Gets the algorithm of the public key + */ + Algorithm: ISignatureAlgorithm; + /** + * Gets the X point value of then public key + */ + X: Uint8Array; + /** + * Gets the Y point value of then public key + */ + Y: Uint8Array; + /** + * Gets the NamedCurve value of then public key + */ + NamedCurve: NamedCurve; + constructor(); + /** + * Imports key to the ECKeyValue object + * @param {CryptoKey} key + * @returns PromiseType + */ + importKey(key: CryptoKey): PromiseType; + /** + * Exports key from the ECKeyValue object + * @param {Algorithm} alg + * @returns PromiseType + */ + exportKey(alg: Algorithm): PromiseType; + /** + * Returns the XML representation of the ECDSA key clause. + * @returns Element + */ + GetXml(): Element; + /** + * Loads an ECDSA key clause from an XML element. + * @param {Element} element + * @returns void + */ + LoadXml(element: Element): void; + } + + type XmlNamespace = { + prefix: string; + namespace: string; + }; + + enum XmlCanonicalizerState { + BeforeDocElement = 0, + InsideDocElement = 1, + AfterDocElement = 2, + } + + class XmlCanonicalizer { + constructor(withComments: boolean, excC14N: boolean, propagatedNamespaces?: XmlNamespace[]); + InclusiveNamespacesPrefixList: string; + Canonicalize(node: Node): string; + } + + interface Transform extends IXmlSerializable { + Algorithm: string; + LoadInnerXml(node: Node): void; + GetInnerXml(): Node; + GetOutput(): string; + } + + interface ICanonicalizationAlgorithmConstructable { + new (): Transform; + } + /** + * Represents the abstract base class from which all elements + * that can be used in an XML digital signature derive. + */ + abstract class Transform extends XmlObject implements Transform { + protected innerXml: Node; + LoadXml(value: Node): void; + /** + * Returns the XML representation of the current Transform object. + * @returns Element + */ + GetXml(): Element; + } + + /** + * Represents the enveloped signature transform for an XML digital signature as defined by the W3C. + */ + class XmlDsigEnvelopedSignatureTransform extends Transform { + Algorithm: string; + /** + * Returns the output of the current XmlDsigEnvelopedSignatureTransform object. + * @returns string + */ + GetOutput(): string; + } + + /** + * Represents the C14N XML canonicalization transform for a digital signature + * as defined by the World Wide Web Consortium (W3C), without comments. + */ + class XmlDsigC14NTransform extends Transform { + protected xmlCanonicalizer: XmlCanonicalizer; + Algorithm: string; + /** + * Returns the output of the current XmlDsigC14NTransform object. + * @returns string + */ + GetOutput(): string; + } + /** + * Represents the C14N XML canonicalization transform for a digital signature + * as defined by the World Wide Web Consortium (W3C), with comments. + */ + class XmlDsigC14NWithCommentsTransform extends XmlDsigC14NTransform { + Algorithm: string; + protected xmlCanonicalizer: XmlCanonicalizer; + } + + /** + * Represents the exclusive C14N XML canonicalization transform for a digital signature + * as defined by the World Wide Web Consortium (W3C), without comments. + */ + class XmlDsigExcC14NTransform extends Transform { + protected xmlCanonicalizer: XmlCanonicalizer; + Algorithm: string; + /** + * Gets or sets a string that contains namespace prefixes to canonicalize + * using the standard canonicalization algorithm. + */ + InclusiveNamespacesPrefixList: string; + /** + * Returns the output of the current XmlDsigExcC14NTransform object + */ + GetOutput(): string; + } + /** + * Represents the exclusive C14N XML canonicalization transform for a digital signature + * as defined by the World Wide Web Consortium (W3C), with comments. + */ + class XmlDsigExcC14NWithCommentsTransform extends XmlDsigExcC14NTransform { + Algorithm: string; + protected xmlCanonicalizer: XmlCanonicalizer; + } + + class CryptoConfig { + static CreateFromName(name: string): Transform; + static CreateSignatureAlgorithm(namespace: string): SignatureAlgorithm; + static CreateHashAlgorithm(namespace: string): HashAlgorithm; + } + + /** + * Represents the object element of an XML signature that holds data to be signed. + */ + class DataObject extends XmlObject { + constructor(); + constructor(id?: string, mimeType?: string, encoding?: string, data?: Element); + /** + * Gets or sets the data value of the current DataObject object. + */ + Data: NodeList; + /** + * Gets or sets the encoding of the current DataObject object. + */ + Encoding: string; + /** + * Gets or sets the identification of the current DataObject object. + */ + Id: string; + /** + * Gets or sets the MIME type of the current DataObject object. + */ + MimeType: string; + /** + * Returns the XML representation of the DataObject object. + * @returns Element + */ + GetXml(): Element; + /** + * Loads a DataObject state from an XML element. + * @param {Element} value + * @returns void + */ + LoadXml(value: Element): void; + } + + /** + * Represents the element of an XML signature. + */ + class Reference extends XmlObject { + + constructor(p?: string); + /** + * Gets or sets the digest method Uniform Resource Identifier (URI) of the current + */ + DigestMethod: string; + /** + * Gets or sets the digest value of the current Reference. + */ + DigestValue: ArrayBuffer; + /** + * Gets or sets the ID of the current Reference. + */ + Id: string; + /** + * Gets the transform chain of the current Reference. + */ + TransformChain: Transform[]; + /** + * Gets or sets the type of the object being signed. + */ + Type: string; + /** + * Gets or sets the Uri of the current Reference. + */ + Uri: string; + /** + * Adds a Transform object to the list of transforms to be performed + * on the data before passing it to the digest algorithm. + * @param {Transform} transform The transform to be added to the list of transforms. + * @returns void + */ + AddTransform(transform: Transform): void; + /** + * Returns the XML representation of the Reference. + * @returns Element + */ + GetXml(): Element; + /** + * Loads a Reference state from an XML element. + * @param {Element} value + */ + LoadXml(value: Element): void; + } + + /** + * Represents an XML digital signature or XML encryption element. + */ + class KeyInfo extends XmlObject { + constructor(); + /** + * Gets the number of KeyInfoClause objects contained in the KeyInfo object. + */ + length: number; + /** + * Gets or sets the key information identity. + */ + Id: string; + /** + * Returns an enumerator of the KeyInfoClause objects in the KeyInfo object. + * @param {any} requestedObjectType? + */ + GetEnumerator(): Array; + GetEnumerator(requestedObjectType: any): Array; + /** + * Returns an enumerator of the KeyInfoClause objects in the KeyInfo object. + * @param {KeyInfoClause} clause The KeyInfoClause to add to the KeyInfo object. + * @returns void + */ + AddClause(clause: KeyInfoClause): void; + /** + * Returns the XML representation of the KeyInfo object. + * @returns Node + */ + GetXml(): Node; + /** + * Loads a KeyInfo state from an XML element. + * @param {Element} value + * @returns void + */ + LoadXml(value: Element): void; + } + interface KeyInfoClause extends IXmlSerializable { + Key: CryptoKey; + importKey(key: CryptoKey): PromiseType; + exportKey(alg: Algorithm): PromiseType; + } + + /** + * Represents the element of an XML signature. + */ + class Signature extends XmlObject { + + constructor(); + /** + * Gets or sets the ID of the current Signature. + */ + Id: string; + /** + * Gets or sets the KeyInfo of the current Signature. + */ + KeyInfo: KeyInfo; + /** + * Gets or sets a list of objects to be signed. + */ + ObjectList: Array; + /** + * Gets or sets the value of the digital signature. + */ + SignatureValue: Uint8Array; + /** + * Gets or sets the SignedInfo of the current Signature. + */ + SignedInfo: SignedInfo; + /** + * Adds a DataObject to the list of objects to be signed. + * @param {DataObject} dataObject The DataObject to be added to the list of objects to be signed. + * @returns void + */ + AddObject(dataObject: DataObject): void; + /** + * Returns the XML representation of the Signature. + * @returns Element + */ + GetXml(): Element; + /** + * Loads a Signature state from an XML element. + * @param {Element} value + * @returns void + */ + LoadXml(value: Element): void; + } + const XmlSignature: { + ElementNames: { + CanonicalizationMethod: string; + DigestMethod: string; + DigestValue: string; + DSAKeyValue: string; + EncryptedKey: string; + HMACOutputLength: string; + RSAPSSParams: string; + MaskGenerationFunction: string; + SaltLength: string; + KeyInfo: string; + KeyName: string; + KeyValue: string; + Modulus: string; + Exponent: string; + Manifest: string; + Object: string; + Reference: string; + RetrievalMethod: string; + RSAKeyValue: string; + ECKeyValue: string; + NamedCurve: string; + PublicKey: string; + Signature: string; + SignatureMethod: string; + SignatureValue: string; + SignedInfo: string; + Transform: string; + Transforms: string; + X509Data: string; + X509IssuerSerial: string; + X509IssuerName: string; + X509SerialNumber: string; + X509SKI: string; + X509SubjectName: string; + X509Certificate: string; + X509CRL: string; + }; + AttributeNames: { + Algorithm: string; + Encoding: string; + Id: string; + MimeType: string; + Type: string; + URI: string; + }; + AlgorithmNamespaces: { + XmlDsigBase64Transform: string; + XmlDsigC14NTransform: string; + XmlDsigC14NWithCommentsTransform: string; + XmlDsigEnvelopedSignatureTransform: string; + XmlDsigXPathTransform: string; + XmlDsigXsltTransform: string; + XmlDsigExcC14NTransform: string; + XmlDsigExcC14NWithCommentsTransform: string; + XmlDecryptionTransform: string; + XmlLicenseTransform: string; + }; + Uri: { + Manifest: string; + }; + NamespaceURI: string; + NamespaceURIMore: string; + NamespaceURIPss: string; + Prefix: string; + GetChildElement: (xel: Node, element: string, ns: string) => Element; + GetAttributeFromElement: (xel: Element, attribute: string, element: string) => string; + GetChildElements: (xel: Element, element: string) => Element[]; + }; + + /** + * The SignedInfo class represents the element + * of an XML signature defined by the XML digital signature specification + */ + class SignedInfo extends XmlObject { + + constructor(signedXml?: SignedXml); + /** + * Gets or sets the canonicalization algorithm that is used before signing + * for the current SignedInfo object. + */ + CanonicalizationMethod: string; + /** + * Gets a Transform object used for canonicalization. + * @returns Transform + */ + CanonicalizationMethodObject: Transform; + /** + * Gets the number of references in the current SignedInfo object. + */ + Count: number; + /** + * Gets or sets the ID of the current SignedInfo object. + */ + Id: string; + /** + * Gets a value that indicates whether the collection is read-only. + * @returns boolean + */ + IsReadOnly: boolean; + /** + * Gets a value that indicates whether the collection is synchronized. + * @returns boolean + */ + IsSynchronized: boolean; + /** + * Gets a list of the Reference objects of the current SignedInfo object. + */ + References: Reference[]; + /** + * Gets or sets the length of the signature for the current SignedInfo object. + */ + SignatureLength: string; + /** + * Gets or sets the name of the algorithm used for signature generation + * and validation for the current SignedInfo object. + */ + SignatureMethod: string; + SignatureParams: XmlObject; + /** + * Gets an object to use for synchronization. + */ + SyncRoot: any; + /** + * Adds a Reference object to the list of references to digest and sign. + * @param {Reference} reference The reference to add to the list of references. + * @returns void + */ + AddReference(reference: Reference): void; + /** + * Copies the elements of this instance into an Array object, starting at a specified index in the array. + * @param {any[]} array + * @param {number} index + * @returns void + */ + CopyTo(array: any[], index: number): void; + /** + * Returns the XML representation of the SignedInfo object. + * @returns Node + */ + GetXml(): Node; + /** + * Loads a SignedInfo state from an XML element. + * @param {Element} value + * @returns void + */ + LoadXml(value: Element): void; + } + + /** + * Provides a wrapper on a core XML signature object to facilitate creating XML signatures. + */ + class SignedXml extends XmlObject { + /** + * Gets or sets the KeyInfo object of the current SignedXml object. + */ + KeyInfo: KeyInfo; + /** + * Gets the Signature object of the current SignedXml object. + */ + Signature: Signature; + /** + * Gets or sets the prefix for the current SignedXml object. + */ + Prefix: string; + /** + * Gets the length of the signature for the current SignedXml object. + */ + SignatureLength: number; + SignatureMethod: string; + /** + * Gets the signature value of the current SignedXml object. + */ + SignatureValue: ArrayBuffer; + /** + * Gets the CanonicalizationMethod of the current SignedXml object. + */ + CanonicalizationMethod: string; + /** + * Gets the SignedInfo object of the current SignedXml object. + */ + SignedInfo: SignedInfo; + /** + * Gets or sets the asymmetric algorithm key used for signing a SignedXml object. + */ + SigningKey: CryptoKey; + /** + * Gets or sets the name of the installed key to be used for signing the SignedXml object. + */ + SigningKeyName: string; + /** + * @param {string} idMode. Value of "wssecurity" will create/validate id's with the ws-security namespace + */ + constructor(); + constructor(node: Document); + constructor(node: Element); + /** + * Adds a Reference object to the SignedXml object that describes a digest method, + * digest value, and transform to use for creating an XML digital signature. + * @param {Reference} reference The Reference object that describes a digest method, digest value, + * and transform to use for creating an XML digital signature. + * @returns void + */ + AddReference(reference: Reference): void; + /** + * Computes an XML digital signature using the specified algorithm. + * @param {Algorithm} algorithm Specified WebCrypto Algoriithm + * @returns PromiseType + */ + ComputeSignature(algorithm: Algorithm): PromiseType; + /** + * Determines whether the SignedXml.Signature property verifies using the public key in the signature. + * @returns PromiseType + */ + CheckSignature(): PromiseType; + CheckSignature(key: CryptoKey): PromiseType; + CheckSignature(cert: X509Certificate): PromiseType; + /** + * Loads a SignedXml state from an XML element. + * @param {Element} value The XML element to load the SignedXml state from. + * @returns void + */ + LoadXml(value: Element): void; + /** + * Returns the XML representation of a SignedXml object. + * @returns Element + */ + GetXml(): Element; + } +} From bc5a137b59ab3f5bc620710bb383f0323cc851cd Mon Sep 17 00:00:00 2001 From: Emanuel Henrique do Prado Date: Mon, 9 May 2016 12:35:20 -0300 Subject: [PATCH 020/402] Added type definition for Knex.Migration (#9227) * Added type definition for Knex.Migration Signed-off-by: Emanuel Henrique do Prado * Corrected Knex test according documentation (http://knexjs.org/#Migrations-currentVersion) * Change name Migration to Migrator, according the original source --- knex/knex-tests.ts | 4 ++-- knex/knex.d.ts | 20 ++++++++++++++------ 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/knex/knex-tests.ts b/knex/knex-tests.ts index e983ec1084..1d4961d9ea 100644 --- a/knex/knex-tests.ts +++ b/knex/knex-tests.ts @@ -594,8 +594,8 @@ knex.migrate.latest(); knex.migrate.rollback(config); knex.migrate.rollback(); -knex.migrate.currentversion(config); -knex.migrate.currentversion(); +knex.migrate.currentVersion(config); +knex.migrate.currentVersion(); knex.seed.make(name, config); knex.seed.make(name); diff --git a/knex/knex.d.ts b/knex/knex.d.ts index 5aa1a46d18..47a5e6ad72 100644 --- a/knex/knex.d.ts +++ b/knex/knex.d.ts @@ -28,7 +28,7 @@ declare module "knex" { schema: Knex.SchemaBuilder; client: any; - migrate: any; + migrate: Knex.Migrator; seed: any; fn: any; } @@ -370,15 +370,15 @@ declare module "knex" { nullable(): ColumnBuilder; comment(value: string): ColumnBuilder; } - + interface ForeignConstraintBuilder { references(columnName: string): ReferencingColumnBuilder; } - + interface MultikeyForeignConstraintBuilder { references(columnNames: string[]): ReferencingColumnBuilder; } - + interface PostgreSqlColumnBuilder extends ColumnBuilder { index(indexName?: string, indexType?: string): ColumnBuilder; } @@ -413,7 +413,7 @@ declare module "knex" { connection?: string|ConnectionConfig|MariaSqlConnectionConfig| Sqlite3ConnectionConfig|SocketConnectionConfig; pool?: PoolConfig; - migrations?: MigrationConfig; + migrations?: MigratorConfig; } interface ConnectionConfig { @@ -487,12 +487,20 @@ declare module "knex" { log?: boolean; } - interface MigrationConfig { + interface MigratorConfig { database?: string; directory?: string; extension?: string; tableName?: string; } + + interface Migrator { + make(name:string, config?: MigratorConfig):Promise; + latest(config?: MigratorConfig):Promise; + rollback(config?: MigratorConfig):Promise; + status(config?: MigratorConfig):Promise; + currentVersion(config?: MigratorConfig):Promise; + } } export = Knex; From 802e89cae7966d4c621d1c21112fa5f2d6de7745 Mon Sep 17 00:00:00 2001 From: neilculver Date: Mon, 9 May 2016 16:36:07 +0100 Subject: [PATCH 021/402] type definitions for db.js (#9260) * started work on a db.js typings * added support for dynamic object stores keys * started creating definitions for fluent query API * Further work on db.js typings * Continued work on db.js typings * Further work on db.js typings * Fixed db.js typings for noImplicitAny TS option * removed ref to es6 promises. * remove tscofig.json --- db.js/db.js-tests.ts | 259 +++++++++++++++++++++++++++++++++++++++++++ db.js/db.js.d.ts | 154 +++++++++++++++++++++++++ 2 files changed, 413 insertions(+) create mode 100644 db.js/db.js-tests.ts create mode 100644 db.js/db.js.d.ts diff --git a/db.js/db.js-tests.ts b/db.js/db.js-tests.ts new file mode 100644 index 0000000000..e2aacb27f0 --- /dev/null +++ b/db.js/db.js-tests.ts @@ -0,0 +1,259 @@ +// Test file for db.js Definition file +/// + +/* Type for use in tests */ + +interface Person { + firstName: string; + lastName: string; + answer: number; + group?: string; +} + +/* Opening/creating a database and connection */ + +var server: DbJs.Server; + +db.open({ + server: 'my-app', + version: 1, + schema: { + people: { + key: { keyPath: 'id', autoIncrement: true }, + indexes: { + firstName: {}, + answer: { unique: true } + } + } + } +}).then(function (s: DbJs.Server) { + server = s; +}); + +var typedStore: DbJs.TypedObjectStoreServer = server['people']; + +/* Basic server operations */ + +var idb = server.getIndexedDB(); +server.close(); + +/* General server/store methods */ + +// Adding items +server.add('people', { + firstName: 'Aaron', + lastName: 'Powell', + answer: 42 +}).then(function (item) { }); + +typedStore.add({ + firstName: 'Aaron', + lastName: 'Powell', + answer: 42 +}).then(function (item) { }); + +// Updating +server.update('people', { + firstName: 'Aaron', + lastName: 'Powell', + answer: 42 +}).then(function (item) { }); + +typedStore.update({ + firstName: 'Aaron', + lastName: 'Powell', + answer: 42 +}).then(function (item) { }); + +// Removing +server.remove('people', 1).then(function (key) { }); +typedStore.remove(1).then(function (key) { }); + +// Clearing +server.clear('people').then(function() { }); +typedStore.clear().then(function() { }); + +// Fetching + +// Getting a single object by key +server.get('people', 5).then(function (results) { }); +typedStore.get(5).then(function (results) { }); + +// Getting a single object by key range + +// With a MongoDB-style range: + +server.get('people', {gte: 1, lt: 3}) + .then(function (results) { }); +typedStore.get({gte: 1, lt: 3}) + .then(function (results) { }); + +// With an IDBKeyRange : + +server.get('people', IDBKeyRange.bound(1, 3, false, true)) + .then(function (results) { }); +typedStore.get(IDBKeyRange.bound(1, 3, false, true)) + .then(function (results) { }); + +// Querying + +// Querying all objects +server.query('people') + .all() + .execute() + .then(function (results) { }); + +typedStore.query() + .all() + .execute() + .then(function (results) { }); + +// Querying using indexes +server.query('people', 'specialProperty') + .all() + .execute() + .then(function (results) { }); + + typedStore.query('specialProperty') + .all() + .execute() + .then(function (results) { }); + +// Filter with property and value +server.query('people') + .filter('firstName', 'Aaron') + .execute() + .then(function (results) { }); + +// Filter with function +server.query('people') + .filter(function(person: any) { return person.group === 'hipster'; }) + .execute() + .then(function (results) { }); + +typedStore.query('people') + .filter(function(person) { return person.group === 'hipster'; }) + .execute() + .then(function (results) { }); + +// Querying with ranges +server.query('people', 'firstName') + .only('Aaron') + .then(function (results) { }); + +server.query('people', 'answer') + .bound(30, 50) + .then(function (results) { }); + +server.query('people', 'firstName') + .range({ eq: 'Aaron' }) + .then(function (results) { }); + +server.query('people', 'answer') + .range({ gte: 30, lte: 50 }) + .then(function (results) { }); + +// Querying for distinct values + server.query('people', 'firstName') + .only('Aaron') + .distinct() + .execute() + .then(function (data) { }); + +// Limiting cursor range +server.query('people', 'firstName') + .all() + .limit(1, 3) + .execute() + .then(function (data) { }); + +// Cursor direction (desc) +server.query('people') + .all() + .desc() + .execute() + .then(function (results) { }); + +// Keys +server.query('people', 'firstName') + .only('Aaron') + .keys() + .execute() + .then(function (results) { }); + +// Mapping +server.query('people', 'age') + .lowerBound(30) + .map(function (value) { + return { + fullName: value.firstName + ' ' + value.lastName, + raw: value + }; + }) + .execute() + .then(function (data) { }); + +// Counting +server.query('people', 'firstName') + .only('Aaron') + .count() + .execute() + .then(function (results) { }); + +// With no arguments (count all items) +server.count().then(function (ct) { }); + +// With a key +server.count('myKey').then(function (ct) { }); + +// With a MongoDB-style range +server.count({gte: 1, lt: 3}).then(function (ct) { }); + +// With an IDBKeyRange range +server.count(IDBKeyRange.bound(1, 3, false, true)).then(function (ct) { }); + +// Atomic updates +server.query('users', 'last_mod') + .lowerBound(new Date().getTime() - 10000) + .modify({ last_mod: new Date().getTime() }) + .execute() + .then(function(results) { }); + +server.query('users', 'changed') + .only(true) + .modify({ changed: false }) + .execute() + .then(function () { }); + +server.query('users', 'name') + .lowerBound('marcy') + .modify({ views: function(profile: any) { return profile.views + 1; } }) + .execute() + .then(function () { }); + +/* Other server methods */ + +// Closing connection +server.close(); + +// Retrieving the indexedDB.open result object in use +var storeNames = server.getIndexedDB().objectStoreNames; + +// Server event handlers + +server.addEventListener('abort', function (e: Event) { }); +server.addEventListener('error', function (err: Event) { }); +server.addEventListener('versionchange', function (e: Event) { }); + +server + .abort(function (e) { }) + .error(function (err) { }) + .versionchange(function (e) { }); + +// Deleting a database +db.delete('dbName').then(function () { }, function (err: Error) { }); +db.delete('dbName').catch(function (err) { }).then(function (ev) { }); + +// Comparing two keys + +db.cmp('key1', 'key2'); diff --git a/db.js/db.js.d.ts b/db.js/db.js.d.ts new file mode 100644 index 0000000000..83e21fa529 --- /dev/null +++ b/db.js/db.js.d.ts @@ -0,0 +1,154 @@ +// Type definitions for db.js v0.14.0 +// Project: https://github.com/aaronpowell/db.js/ +// Definitions by: Chris Wrench +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module DbJs { + interface ErrorListener { + (err: Error): void; + } + + interface OpenOptions { + server: string; + version: number; + schema?: any; + } + + interface DbJsStatic { + open(options: OpenOptions): Promise; + delete(dbName: string): Promise; + cmp(key1: any, key2: any): number; + } + + // Query API + + interface ExecutableQuery { + execute(): Promise; + } + + interface CountableQuery { + count(): ExecutableQuery; + } + + interface KeysQuery extends DescableQuery, ExecutableQuery, FilterableQuery, DistinctableQuery, MappableQuery { + } + + interface KeyableQuery { + keys(): KeysQuery; + } + + interface FilterQuery extends KeyableQuery, ExecutableQuery, FilterableQuery, DescableQuery, DistinctableQuery, ModifiableQuery, LimitableQuery, MappableQuery { + } + + interface FilterableQuery { + filter(index: string, value: TValue): FilterQuery; + filter(filter: (value: T) => boolean): FilterQuery; + } + + interface DescQuery extends KeyableQuery, CountableQuery, ExecutableQuery, FilterableQuery, DescableQuery, ModifiableQuery, MappableQuery { + } + + interface DescableQuery { + desc(): DescQuery; + } + + interface DistinctQuery extends KeyableQuery, ExecutableQuery, FilterableQuery, DescableQuery, ModifiableQuery, MappableQuery, CountableQuery { + } + + interface DistinctableQuery { + distinct(filter?: (value: T) => boolean): DistinctQuery; + } + + interface ModifiableQuery { + modify(filter: (value: T) => boolean): ExecutableQuery; + modify(modifyObj: any): ExecutableQuery; + } + + interface LimitableQuery { + limit(n: any, m: any): ExecutableQuery; + } + + interface MappableQuery { + map(fn: (value: T) => TMap): Query; + } + + interface Query extends Promise, KeyableQuery, ExecutableQuery, FilterableQuery, DescableQuery, DistinctableQuery, ModifiableQuery, LimitableQuery, MappableQuery, CountableQuery { + } + + interface IndexQuery extends Query { + only(...args: any[]): Query; + bound(lowerBound: any, upperBound: any): Query; + upperBound(upperBound: any): Query; + lowerBound(lowerBound: any): Query; + range(opts: any): Query; + all(): Query; + } + + interface KeyValuePair { + key: TKey; + item: TValue; + } + + interface BaseServer { + getIndexedDB(): IDBDatabase; + close(): void; + } + + interface IndexAccessibleServer { + [store: string]: TypedObjectStoreServer; + } + + interface ObjectStoreServer { + add(table: string, entity: T): Promise; + add(table: string, ...entities: T[]): Promise; + add(table: string, entity: KeyValuePair): Promise>; + add(table: string, ...entities: KeyValuePair[]): Promise[]>; + update(table: string, entity: T): Promise; + update(table: string, ...entities: T[]): Promise; + update(table: string, entity: KeyValuePair): Promise>; + update(table: string, ...entities: KeyValuePair[]): Promise[]>; + remove(table: string, key: TKey): Promise; + remove(table: string, ...keys: TKey[]): Promise; + clear(table: string): Promise; + get(table: string, key: any): Promise; + query(table: string): IndexQuery; + query(table: string, index: string): IndexQuery; + count(): Promise; + count(keyOrRange: any): Promise; + count(table: string, key: any): Promise; + addEventListener(type: 'abort', listener: (ev: Event) => any): void; + addEventListener(type: 'versionchange', listener: (ev: Event) => any): void; + addEventListener(type: 'error', listener: (err: Error) => any): void; + addEventListener(type: string, listener: EventListener | ErrorListener): void; + abort(listener: (ev: Event) => any): ObjectStoreServer; + versionchange(listener: (ev: Event) => any): ObjectStoreServer; + error(listener: (ev: Error) => any): ObjectStoreServer; + } + + interface TypedObjectStoreServer { + add(entity: T): Promise; + add(...entities: T[]): Promise; + add(entity: KeyValuePair): Promise>; + add(...entities: KeyValuePair[]): Promise[]>; + update(entity: T): Promise; + update(...entities: T[]): Promise; + update(entity: KeyValuePair): Promise>; + update(...entities: KeyValuePair[]): Promise[]>; + remove(key: TKey): Promise; + remove(...keys: TKey[]): Promise; + clear(): Promise; + get(key: any): Promise; + query(): IndexQuery; + query(index: string): IndexQuery; + count(key: any): Promise; + } + + type Server = DbJs.IndexAccessibleServer & DbJs.ObjectStoreServer & DbJs.BaseServer; +} + +declare module "db" { + var db: DbJs.DbJsStatic; + export = db; +} + +declare var db: DbJs.DbJsStatic; From 6d0e826824da52204c1c93f92cecbc961ac84fa9 Mon Sep 17 00:00:00 2001 From: Masahiro Wakame Date: Tue, 10 May 2016 00:45:15 +0900 Subject: [PATCH 022/402] update node.d.ts, remove typing notes (#9259) --- node/node.d.ts | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/node/node.d.ts b/node/node.d.ts index bc6e25c9d5..a9d4709a91 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -1192,7 +1192,7 @@ declare module "url" { host?: string; pathname?: string; search?: string; - query?: any; // string | Object + query?: string | any; slashes?: boolean; hash?: string; path?: string; @@ -1814,13 +1814,13 @@ declare module "tls" { host?: string; port?: number; socket?: net.Socket; - pfx?: any; //string | Buffer - key?: any; //string | Buffer + pfx?: string | Buffer + key?: string | Buffer passphrase?: string; - cert?: any; //string | Buffer - ca?: any; //Array of string | Buffer + cert?: string | Buffer + ca?: (string | Buffer)[]; rejectUnauthorized?: boolean; - NPNProtocols?: any; //Array of string | Buffer + NPNProtocols?: (string | Buffer)[]; servername?: string; } @@ -1859,12 +1859,12 @@ declare module "tls" { } export interface SecureContextOptions { - pfx?: any; //string | buffer - key?: any; //string | buffer + pfx?: string | Buffer; + key?: string | Buffer; passphrase?: string; - cert?: any; // string | buffer - ca?: any; // string | buffer - crl?: any; // string | string[] + cert?: string | Buffer; + ca?: string | Buffer; + crl?: string | string[] ciphers?: string; honorCipherOrder?: boolean; } @@ -1887,8 +1887,8 @@ declare module "crypto" { key: string; passphrase: string; cert: string; - ca: any; //string | string array - crl: any; //string | string array + ca: string | string[]; + crl: string | string[]; ciphers: string; } export interface Credentials { context?: any; } From 7c6411053f6ead18f7f096ef6fbfde352e55faa1 Mon Sep 17 00:00:00 2001 From: Stuart Moore Date: Mon, 9 May 2016 16:49:30 +0100 Subject: [PATCH 023/402] Fix JQueryUi zindex() function to return a number, not a JQuery. Relevant documentation: https://api.jqueryui.com/zIndex/ --- jqueryui/jqueryui.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jqueryui/jqueryui.d.ts b/jqueryui/jqueryui.d.ts index 63a1591a21..c8167956ea 100644 --- a/jqueryui/jqueryui.d.ts +++ b/jqueryui/jqueryui.d.ts @@ -1794,7 +1794,7 @@ interface JQuery { uniqueId(): JQuery; removeUniqueId(): JQuery; scrollParent(): JQuery; - zIndex(): JQuery; + zIndex(): number; zIndex(zIndex: number): JQuery; widget: JQueryUI.Widget; From 384a53f595cdba08d1398902e53c6901700ec459 Mon Sep 17 00:00:00 2001 From: Moes Date: Tue, 10 May 2016 11:04:35 +1000 Subject: [PATCH 024/402] update toastr.d.ts add clearOptions to force clearing a toast, ignoring focus --- toastr/toastr.d.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/toastr/toastr.d.ts b/toastr/toastr.d.ts index edf65d4073..e921bfbd7b 100644 --- a/toastr/toastr.d.ts +++ b/toastr/toastr.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Toastr 2.0.1 +// Type definitions for Toastr 2.1.1 // Project: https://github.com/CodeSeven/toastr // Definitions by: Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -174,6 +174,13 @@ interface Toastr { * @param toast Toast to clear */ (toast: JQuery): void; + /** + * Clear specific toast + * + * @param toast Toast to clear + * @param clearOptions force clearing a toast, ignoring focus + */ + (toast: JQuery, clearOptions: { force: boolean }): void; }; /** * Create an error toast From 0a27eaa06fe1fcf71aabd8883147c487b542369f Mon Sep 17 00:00:00 2001 From: kodeo Date: Tue, 10 May 2016 11:37:53 +0100 Subject: [PATCH 025/402] Add addMethod overload in support of message as a function --- jquery.validation/jquery.validation.d.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/jquery.validation/jquery.validation.d.ts b/jquery.validation/jquery.validation.d.ts index 7527652e80..e3d35bb0d1 100644 --- a/jquery.validation/jquery.validation.d.ts +++ b/jquery.validation/jquery.validation.d.ts @@ -188,6 +188,14 @@ declare namespace JQueryValidation * @param method The actual method implementation, returning true if an element is valid. First argument: Current value. Second argument: Validated element. Third argument: Parameters. */ addMethod(name: string, method: (value: any, element: HTMLElement, params: any) => boolean, message?: string): void; + /** + * Add a custom validation method. It must consist of a name (must be a legal javascript identifier), a predicate function and a message generating function. + * + * @param name The name of the method used to identify it and referencing it; this must be a valid JavaScript identifier + * @param method The actual method implementation, returning true if an element is valid. First argument: Current value. Second argument: Validated element. Third argument: Parameters. + * @param message Message generator. First argument: Parameters. Second argument: Validated element. + */ + addMethod(name: string, method: (value: any, element: HTMLElement, params: any) => boolean, message?: (params: any, element: HTMLElement) => string): void; /** * Replaces {n} placeholders with arguments. * From 1e05cdb61833631b78c7bc5c518811ef61669595 Mon Sep 17 00:00:00 2001 From: Richard Hepburn Date: Tue, 10 May 2016 12:09:31 -0400 Subject: [PATCH 026/402] Update isBetween method to support inclusivity (#9267) Updated the isBetween method declaration to support the inclusivity parameter introduced in MomentJS 2.13.0 --- moment/moment-node.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/moment/moment-node.d.ts b/moment/moment-node.d.ts index d0880ef1f9..f054e52cda 100644 --- a/moment/moment-node.d.ts +++ b/moment/moment-node.d.ts @@ -307,7 +307,7 @@ declare namespace moment { isAfter(b: MomentComparable, granularity?: string): boolean; isSame(b: MomentComparable, granularity?: string): boolean; - isBetween(a: MomentComparable, b: MomentComparable, granularity?: string): boolean; + isBetween(a: MomentComparable, b: MomentComparable, granularity?: string, inclusivity?: string): boolean; /** * @since 2.10.7+ From c2bdcedfd5a7386a7bbdc3d0c9b9baf1d82ba5f3 Mon Sep 17 00:00:00 2001 From: Geoffrey Goh Date: Tue, 10 May 2016 16:04:24 -0700 Subject: [PATCH 027/402] Update cordova.d.ts --- cordova/cordova.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cordova/cordova.d.ts b/cordova/cordova.d.ts index 299e2da4d9..7de1e8b0c1 100644 --- a/cordova/cordova.d.ts +++ b/cordova/cordova.d.ts @@ -35,7 +35,7 @@ interface Cordova { * @param action The action name to call on the native side (generally corresponds to the native class method). * @param args An array of arguments to pass into the native environment. */ - exec(success: () => any, fail: () => any, service: string, action: string, args?: string[]): void; + exec(success: () => any, fail: () => any, service: string, action: string, args?: (string | number | boolean)[]): void; /** Gets the operating system name. */ platformId: string; /** Gets Cordova framework version */ From 844831b968857a9dc2f44e0698ff282863c5c238 Mon Sep 17 00:00:00 2001 From: Geoffrey Goh Date: Tue, 10 May 2016 16:49:18 -0700 Subject: [PATCH 028/402] Update cordova.d.ts --- cordova/cordova.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cordova/cordova.d.ts b/cordova/cordova.d.ts index 7de1e8b0c1..24adab6928 100644 --- a/cordova/cordova.d.ts +++ b/cordova/cordova.d.ts @@ -35,7 +35,7 @@ interface Cordova { * @param action The action name to call on the native side (generally corresponds to the native class method). * @param args An array of arguments to pass into the native environment. */ - exec(success: () => any, fail: () => any, service: string, action: string, args?: (string | number | boolean)[]): void; + exec(success: () => any, fail: () => any, service: string, action: string, args?: any[]): void; /** Gets the operating system name. */ platformId: string; /** Gets Cordova framework version */ From e39766617019f476737a294150e880a36224a5b4 Mon Sep 17 00:00:00 2001 From: Moes Date: Wed, 11 May 2016 13:29:25 +1000 Subject: [PATCH 029/402] Update jquery.pnotify.d.ts to v3.0.0 Update jquery.pnotify.d.ts to v3.0.0 --- jquery.pnotify/jquery.pnotify.d.ts | 128 +++++++++++++++++++++++++++-- 1 file changed, 119 insertions(+), 9 deletions(-) diff --git a/jquery.pnotify/jquery.pnotify.d.ts b/jquery.pnotify/jquery.pnotify.d.ts index edb7e2468c..cdccb6fbd5 100644 --- a/jquery.pnotify/jquery.pnotify.d.ts +++ b/jquery.pnotify/jquery.pnotify.d.ts @@ -1,4 +1,4 @@ -// Type definitions for jquery.pnotify 2.x +// Type definitions for jquery.pnotify 3.x // Project: https://github.com/sciactive/pnotify // Definitions by: David Sichau // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -24,11 +24,98 @@ interface PNotifyLabel { stick?: string; } + +interface IPNotifyconfirmButton { + text: string; + addClass: string; + /** + * Whether to trigger this button when the user hits enter in a single line prompt. + */ + promptTrigger: boolean; + click: (notice: PNotify, value: any) => void +} + +interface PNotifyconfirm { + /** + * Make a confirmation box. + */ + confirm: boolean; + + /** + * Make a prompt. + */ + prompt: boolean; + /** + * Classes to add to the input element of the prompt. + */ + prompt_class: string + + /** + * The default value of the prompt. + */ + prompt_default: string + + /** + * Whether the prompt should accept multiple lines of text. + */ + prompt_multi_line: boolean; + + /** + * Where to align the buttons. (right, center, left, justify) + */ + align: string; + + /** + * The buttons to display, and their callbacks. + */ + buttons: IPNotifyconfirmButton[]; + +} + +interface IPNotifyButtons { + /** + * Provide a button for the user to manually close the notice. + */ + closer: boolean; + /** + * Only show the closer button on hover. + */ + closer_hover: boolean; + /** + * Provide a button for the user to manually stick the notice. + */ + sticker: boolean; + /** + * Only show the sticker button on hover. + */ + sticker_hover: boolean; + /** + * Show the buttons even when the nonblock module is in use. + */ + show_on_nonblock: boolean; + /** + * The various displayed text, helps facilitating internationalization. + */ + labels: { + close: string; + stick: string; + unstick: string; + }; + /** + * The classes to use for button icons. Leave them null to use the classes from the styling you're using. + */ + classes: { + closer: string; + pin_up: string; + pin_down: string; + }; +} + interface PNotifyOptions { /** * The notice's title. Either boolean false or string */ - title?: any; + title?: string | boolean; /** * Whether to escape the content of the title. (Not allow HTML.) */ @@ -36,15 +123,15 @@ interface PNotifyOptions { /** * The notice's text. Either boolean false or string */ - text?: any; + text?: string | boolean; /** * Whether to escape the content of the text. (Not allow HTML.) */ text_escape?: boolean; /** - * What styling classes to use. (Can be either jqueryui or bootstrap.) + * What styling classes to use. (Can be either "brighttheme", "jqueryui", "bootstrap2", "bootstrap3", or "fontawesome".) */ - styling?: string; + styling?: "brighttheme" | "jqueryui" | "bootstrap2" | "bootstrap3" | "fontawesome"; /** * Additional classes to be added to the notice. (For custom styling.) */ @@ -89,7 +176,7 @@ interface PNotifyOptions { /** * Type of the notice. "notice", "info", "success", or "error". */ - type?: string; + type?: "notice" | "info" | "success" | "error"; /** * Set icon to true to use the default icon for the selected style/type, false for no icon, or a string for your own icon class. */ @@ -166,15 +253,38 @@ interface PNotifyOptions { } interface PNotify { - elem: JQuery; - + + /** + * The state can be "initializing", "opening", "open", "closing", and "closed" + */ + + state: "initializing" | "opening" | "open" | "closing" | "closed"; + + /** + * This function is for updating the notice. + */ update(options?: PNotifyOptions): void; + + /** + * Remove the notice. + */ remove(): void; + + /** + * Display the notice. + */ + open(): void; + + /** + * Get the DOM element. + */ + get(): JQuery; + } interface PNotifyConstructor { new (options?: PNotifyOptions): PNotify; - + removeAll(): void; } From c5bcfd3d0832909ff89f69e2c4f6669d0513cf87 Mon Sep 17 00:00:00 2001 From: Moes Date: Wed, 11 May 2016 14:01:51 +1000 Subject: [PATCH 030/402] Update jquery.pnotify.d.ts Add type --- jquery.pnotify/jquery.pnotify.d.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/jquery.pnotify/jquery.pnotify.d.ts b/jquery.pnotify/jquery.pnotify.d.ts index cdccb6fbd5..3fd1d30d99 100644 --- a/jquery.pnotify/jquery.pnotify.d.ts +++ b/jquery.pnotify/jquery.pnotify.d.ts @@ -4,6 +4,9 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// +type NoticeTypeOptions = "notice" | "info" | "success" | "error"; +type StylingOptions = "brighttheme" | "jqueryui" | "bootstrap2" | "bootstrap3" | "fontawesome"; +type StateOptions = "initializing" | "opening" | "open" | "closing" | "closed"; interface PNotifyStack { dir1?: string; @@ -131,7 +134,7 @@ interface PNotifyOptions { /** * What styling classes to use. (Can be either "brighttheme", "jqueryui", "bootstrap2", "bootstrap3", or "fontawesome".) */ - styling?: "brighttheme" | "jqueryui" | "bootstrap2" | "bootstrap3" | "fontawesome"; + styling?: StylingOptions; /** * Additional classes to be added to the notice. (For custom styling.) */ @@ -176,7 +179,7 @@ interface PNotifyOptions { /** * Type of the notice. "notice", "info", "success", or "error". */ - type?: "notice" | "info" | "success" | "error"; + type?: NoticeTypeOptions; /** * Set icon to true to use the default icon for the selected style/type, false for no icon, or a string for your own icon class. */ @@ -257,8 +260,7 @@ interface PNotify { /** * The state can be "initializing", "opening", "open", "closing", and "closed" */ - - state: "initializing" | "opening" | "open" | "closing" | "closed"; + state?: StateOptions; /** * This function is for updating the notice. From 04757e55977be45e0269500435ae4d4c21c8fe67 Mon Sep 17 00:00:00 2001 From: Moes Date: Wed, 11 May 2016 14:06:26 +1000 Subject: [PATCH 031/402] remove type is not supported by travis remove type is not supported by travis --- jquery.pnotify/jquery.pnotify.d.ts | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/jquery.pnotify/jquery.pnotify.d.ts b/jquery.pnotify/jquery.pnotify.d.ts index 3fd1d30d99..6568adf351 100644 --- a/jquery.pnotify/jquery.pnotify.d.ts +++ b/jquery.pnotify/jquery.pnotify.d.ts @@ -4,9 +4,11 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -type NoticeTypeOptions = "notice" | "info" | "success" | "error"; -type StylingOptions = "brighttheme" | "jqueryui" | "bootstrap2" | "bootstrap3" | "fontawesome"; -type StateOptions = "initializing" | "opening" | "open" | "closing" | "closed"; + +// could not pass the Travis Test if enabled +//type NoticeTypeOptions = "notice" | "info" | "success" | "error"; +//type StylingOptions = "brighttheme" | "jqueryui" | "bootstrap2" | "bootstrap3" | "fontawesome"; +//type StateOptions = "initializing" | "opening" | "open" | "closing" | "closed"; interface PNotifyStack { dir1?: string; @@ -134,7 +136,7 @@ interface PNotifyOptions { /** * What styling classes to use. (Can be either "brighttheme", "jqueryui", "bootstrap2", "bootstrap3", or "fontawesome".) */ - styling?: StylingOptions; + styling?: string; /** * Additional classes to be added to the notice. (For custom styling.) */ @@ -179,7 +181,7 @@ interface PNotifyOptions { /** * Type of the notice. "notice", "info", "success", or "error". */ - type?: NoticeTypeOptions; + type?: string; /** * Set icon to true to use the default icon for the selected style/type, false for no icon, or a string for your own icon class. */ @@ -260,7 +262,7 @@ interface PNotify { /** * The state can be "initializing", "opening", "open", "closing", and "closed" */ - state?: StateOptions; + state?: string; /** * This function is for updating the notice. @@ -291,4 +293,3 @@ interface PNotifyConstructor { } declare var PNotify: PNotifyConstructor; - From c3775121b076d76269e8cc26429d3dd2c4ead1c6 Mon Sep 17 00:00:00 2001 From: Moes Date: Wed, 11 May 2016 14:21:25 +1000 Subject: [PATCH 032/402] Update jquery.pnotify.d.ts to v3.0.0 make options optional --- jquery.pnotify/jquery.pnotify.d.ts | 48 +++++++++++++++--------------- 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/jquery.pnotify/jquery.pnotify.d.ts b/jquery.pnotify/jquery.pnotify.d.ts index 6568adf351..26c927cec9 100644 --- a/jquery.pnotify/jquery.pnotify.d.ts +++ b/jquery.pnotify/jquery.pnotify.d.ts @@ -31,12 +31,12 @@ interface PNotifyLabel { interface IPNotifyconfirmButton { - text: string; - addClass: string; + text?: string; + addClass?: string; /** * Whether to trigger this button when the user hits enter in a single line prompt. */ - promptTrigger: boolean; + promptTrigger?: boolean; click: (notice: PNotify, value: any) => void } @@ -44,36 +44,36 @@ interface PNotifyconfirm { /** * Make a confirmation box. */ - confirm: boolean; + confirm?: boolean; /** * Make a prompt. */ - prompt: boolean; + prompt?: boolean; /** * Classes to add to the input element of the prompt. */ - prompt_class: string + prompt_class?: string /** * The default value of the prompt. */ - prompt_default: string + prompt_default?: string /** * Whether the prompt should accept multiple lines of text. */ - prompt_multi_line: boolean; + prompt_multi_line?: boolean; /** * Where to align the buttons. (right, center, left, justify) */ - align: string; + align?: string; /** * The buttons to display, and their callbacks. */ - buttons: IPNotifyconfirmButton[]; + buttons?: IPNotifyconfirmButton[]; } @@ -81,38 +81,38 @@ interface IPNotifyButtons { /** * Provide a button for the user to manually close the notice. */ - closer: boolean; + closer?: boolean; /** * Only show the closer button on hover. */ - closer_hover: boolean; + closer_hover?: boolean; /** * Provide a button for the user to manually stick the notice. */ - sticker: boolean; + sticker?: boolean; /** * Only show the sticker button on hover. */ - sticker_hover: boolean; + sticker_hover?: boolean; /** * Show the buttons even when the nonblock module is in use. */ - show_on_nonblock: boolean; + show_on_nonblock?: boolean; /** * The various displayed text, helps facilitating internationalization. */ - labels: { - close: string; - stick: string; - unstick: string; + labels?: { + close?: string; + stick?: string; + unstick?: string; }; /** * The classes to use for button icons. Leave them null to use the classes from the styling you're using. */ - classes: { - closer: string; - pin_up: string; - pin_down: string; + classes?: { + closer?: string; + pin_up?: string; + pin_down?: string; }; } @@ -150,7 +150,7 @@ interface PNotifyOptions { /** * Create a non-blocking notice. It lets the user click elements underneath it. */ - nonblock: boolean; + nonblock?: boolean; /** * The opacity of the notice (if it's non-blocking) when the mouse is over it. From 8886ae591751e8a8237fa855617745768f0b1bdf Mon Sep 17 00:00:00 2001 From: Chris Long Date: Tue, 10 May 2016 21:33:38 -0700 Subject: [PATCH 033/402] User defined type guards in Moment (#9282) --- moment/moment-node.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/moment/moment-node.d.ts b/moment/moment-node.d.ts index f054e52cda..6e602b2970 100644 --- a/moment/moment-node.d.ts +++ b/moment/moment-node.d.ts @@ -605,10 +605,10 @@ declare namespace moment { invalid(parsingFlags?: Object): Moment; isMoment(): boolean; - isMoment(m: any): boolean; - isDate(m: any): boolean; + isMoment(m: any): m is Moment; + isDate(m: any): m is Date; isDuration(): boolean; - isDuration(d: any): boolean; + isDuration(d: any): d is Duration; /** * @deprecated since version 2.8.0 From b94c65e3f7c613e0b9fa8bca64b541a872bee7fc Mon Sep 17 00:00:00 2001 From: Doug Miller Date: Thu, 12 May 2016 00:04:31 -0400 Subject: [PATCH 034/402] Enzyme mount/unmount methods (#9207) * Added unmount/mount methods * Empty Commit for TravisCi --- enzyme/enzyme-tests.tsx | 14 +++++++++- enzyme/enzyme.d.ts | 62 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+), 1 deletion(-) diff --git a/enzyme/enzyme-tests.tsx b/enzyme/enzyme-tests.tsx index 56767b4ab3..4cc45e9fd4 100644 --- a/enzyme/enzyme-tests.tsx +++ b/enzyme/enzyme-tests.tsx @@ -107,6 +107,10 @@ namespace ShallowWrapperTest { shallowWrapper = shallowWrapper.shallow(); } + function test_unmount() { + shallowWrapper = shallowWrapper.unmount(); + } + function test_render() { var cheerioWrapper: CheerioWrapper = shallowWrapper.render(); } @@ -238,6 +242,14 @@ namespace ReactWrapperTest { stringVal: String, elementWrapper: ReactWrapper + function test_unmount() { + reactWrapper = reactWrapper.unmount(); + } + + function test_mount() { + reactWrapper = reactWrapper.mount(); + } + function test_find() { elementWrapper = reactWrapper.find('.selector'); reactWrapper = reactWrapper.find(MyComponent); @@ -418,7 +430,7 @@ namespace CheerioWrapperTest { objectVal: Object, boolVal: Boolean, stringVal: String, - elementWrapper: ReactWrapper + elementWrapper: CheerioWrapper function test_find() { elementWrapper = cheerioWrapper.find('.selector'); diff --git a/enzyme/enzyme.d.ts b/enzyme/enzyme.d.ts index 9047fbf728..13c00041a5 100644 --- a/enzyme/enzyme.d.ts +++ b/enzyme/enzyme.d.ts @@ -313,6 +313,7 @@ declare module "enzyme" { export interface ShallowWrapper extends CommonWrapper { shallow(): ShallowWrapper; render(): CheerioWrapper; + unmount(): ShallowWrapper; /** * Find every node in the render tree that matches the provided selector. @@ -376,7 +377,68 @@ declare module "enzyme" { } export interface ReactWrapper extends CommonWrapper { + unmount(): ReactWrapper; + mount(): ReactWrapper; + /** + * Find every node in the render tree that matches the provided selector. + * @param selector The selector to match. + */ + find(component: ComponentClass): ReactWrapper; + find(statelessComponent: (props: P2) => JSX.Element): ReactWrapper; + find(selector: string): ReactWrapper; + + /** + * Finds every node in the render tree that returns true for the provided predicate function. + * @param predicate + */ + findWhere(predicate: (wrapper: CommonWrapper) => Boolean): ReactWrapper; + + /** + * Removes nodes in the current wrapper that do not match the provided selector. + * @param selector The selector to match. + */ + filter(component: ComponentClass): ReactWrapper; + filter(statelessComponent: StatelessComponent): ReactWrapper; + filter(selector: string): ReactWrapper; + + /** + * Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector + * can be provided and it will filter the children by this selector. + * @param [selector] + */ + children(component: ComponentClass): ReactWrapper; + children(statelessComponent: StatelessComponent): ReactWrapper; + children(selector: string): ReactWrapper; + children(): ReactWrapper; + + /** + * Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the + * current wrapper. Optionally, a selector can be provided and it will filter the parents by this selector. + * + * Note: can only be called on a wrapper of a single node. + * @param [selector] + */ + parents(component: ComponentClass): ReactWrapper; + parents(statelessComponent: StatelessComponent): ReactWrapper; + parents(selector: string): ReactWrapper; + parents(): ReactWrapper; + + /** + * Returns a wrapper of the first element that matches the selector by traversing up through the current node's + * ancestors in the tree, starting with itself. + * + * Note: can only be called on a wrapper of a single node. + * @param selector + */ + closest(component: ComponentClass): ReactWrapper; + closest(statelessComponent: StatelessComponent): ReactWrapper; + closest(selector: string): ReactWrapper; + + /** + * Returns a wrapper with the direct parent of the node in the current wrapper. + */ + parent(): ReactWrapper; } export interface CheerioWrapper extends CommonWrapper { From 11283aeaabe629e8f6a67d651be726bcd7faa0c3 Mon Sep 17 00:00:00 2001 From: Evan Hahn Date: Wed, 11 May 2016 21:38:42 -0700 Subject: [PATCH 035/402] Add Evan Hahn to list of Helmet contributors (in source file) (#9273) --- helmet/helmet.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/helmet/helmet.d.ts b/helmet/helmet.d.ts index 7154d0b739..6feef0bad8 100644 --- a/helmet/helmet.d.ts +++ b/helmet/helmet.d.ts @@ -1,6 +1,6 @@ // Type definitions for helmet // Project: https://github.com/helmetjs/helmet -// Definitions by: Cyril Schumacher +// Definitions by: Cyril Schumacher , Evan Hahn // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// From 00694cb526241f3e4e484e584b4de8a1824a9469 Mon Sep 17 00:00:00 2001 From: didlich Date: Thu, 12 May 2016 06:39:27 +0200 Subject: [PATCH 036/402] update phonegap-nfc's enabled() signature (#9270) * extend enabled() signature as documented * update phonegap-nfc enabled() signature * fix phonegap-nfc's property name --- phonegap-nfc/phonegap-nfc-tests.ts | 46 +++++++++++++++++++++++++++++- phonegap-nfc/phonegap-nfc.d.ts | 4 +-- 2 files changed, 47 insertions(+), 3 deletions(-) diff --git a/phonegap-nfc/phonegap-nfc-tests.ts b/phonegap-nfc/phonegap-nfc-tests.ts index ddaabebce7..08700fa919 100644 --- a/phonegap-nfc/phonegap-nfc-tests.ts +++ b/phonegap-nfc/phonegap-nfc-tests.ts @@ -3,6 +3,8 @@ import nfc = require('nfc'); import ndef = require('ndef'); import NdefRecord = PhoneGapNfc.NdefRecord; +import NdefTag = PhoneGapNfc.NdefTag; +import NdefTagEvent = PhoneGapNfc.NdefTagEvent; nfc.addTagDiscoveredListener(() => {}); nfc.addTagDiscoveredListener(() => {},() => {}, () => {}); @@ -39,7 +41,7 @@ nfc.erase(); nfc.erase(() => {}, () => {}); nfc.enabled(); -nfc.enabled(() => {}, () => {}); +nfc.enabled((status: String) => {}, (status: String) => {}); nfc.removeTagDiscoveredListener(() => {}); nfc.removeTagDiscoveredListener(() => {},() => {},() => {}); @@ -78,3 +80,45 @@ let obj:any = ndef.decodeTnf(bytes[0]); let tnfByte:number = ndef.encodeTnf(bytes[0],bytes[1],bytes[2],bytes[3],bytes[4],bytes[5]); let tnfString:string = ndef.tnfToString(tnfByte); + +let ndefTag: NdefTag = { + id: [4, 12, 109, 98, 8, 41, -127], + techTypes: ["android.nfc.tech.MifareUltralight", "android.nfc.tech.NfcA", "android.nfc.tech.Ndef"], + type: "NFC Forum Type 2", + date: "1394448136236", + + canMakeReadOnly: true, + isWritable: true, + maxSize: 137, + ndefMessage: records +}; + +let eventTarget: EventTarget = { + addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean) { return; }, + dispatchEvent(evt: Event) { return true; }, + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean) { return; } +} + +let ndefTagEvent: NdefTagEvent = { + bubbles: false, + cancelBubble: false, + cancelable: false, + currentTarget: eventTarget, + defaultPrevented: false, + eventPhase: 2, + isTrusted: true, + returnValue: true, + srcElement: new Element(), + target: eventTarget, + timeStamp: 1394448136236, + type: "ndef", + initEvent(eventTypeArg: string, canBubbleArg: boolean, cancelableArg: boolean) { return; }, + preventDefault() { return; }, + stopImmediatePropagation() { return; }, + stopPropagation() { return; }, + AT_TARGET: 0, + BUBBLING_PHASE: 0, + CAPTURING_PHASE: 0, + + tag: ndefTag +}; diff --git a/phonegap-nfc/phonegap-nfc.d.ts b/phonegap-nfc/phonegap-nfc.d.ts index 849e2527cc..ff980eea33 100644 --- a/phonegap-nfc/phonegap-nfc.d.ts +++ b/phonegap-nfc/phonegap-nfc.d.ts @@ -49,7 +49,7 @@ declare namespace PhoneGapNfc { canMakeReadOnly:boolean; isWritable:boolean; maxSize:number; - records:Array; + ndefMessage:Array; } interface TagEvent extends Event { @@ -406,7 +406,7 @@ declare namespace PhoneGapNfc { * @param win The callback that is called when NFC is enabled. * @param fail The callback that is called when NFC is disabled or missing. */ - enabled(win?:() => void, fail?:() => void):void; + enabled(win?:(status:String) => void, fail?:(status:String) => void):void; /** * Removes the previously registered event listener added via nfc.addTagDiscoveredListener From 4efcbba3d4d7550df77fe57b73c65fd67bcab9fa Mon Sep 17 00:00:00 2001 From: Daniel Chao Date: Wed, 11 May 2016 21:48:50 -0700 Subject: [PATCH 037/402] Sqs producer (#9279) * add sqs-producer typings * use site url --- sqs-producer/sqs-producer-tests.ts | 52 ++++++++++++++++++++++++++++++ sqs-producer/sqs-producer.d.ts | 51 +++++++++++++++++++++++++++++ 2 files changed, 103 insertions(+) create mode 100644 sqs-producer/sqs-producer-tests.ts create mode 100644 sqs-producer/sqs-producer.d.ts diff --git a/sqs-producer/sqs-producer-tests.ts b/sqs-producer/sqs-producer-tests.ts new file mode 100644 index 0000000000..f224ab11fb --- /dev/null +++ b/sqs-producer/sqs-producer-tests.ts @@ -0,0 +1,52 @@ +// Taken straight from sqs-producer's README.md + +/// + + +import * as Producer from "sqs-producer"; + +var producer = Producer.create({ + queueUrl: 'https://sqs.eu-west-1.amazonaws.com/account-id/queue-name', + region: 'eu-west-1' +}); + +// send messages to the queue +producer.send(['msg1', 'msg2'], function(err) { + if (err) console.log(err); +}); + +// get the current size of the queue +producer.queueSize(function (err, size) { + if (err) console.log(err); + + console.log('There are', size, 'messages on the queue.'); +}); + +// send a message to the queue with a specific ID (by default the body is used as the ID) +producer.send([{ + id: 'id1', + body: 'Hello world' +}], function(err) { + if (err) console.log(err); +}); + +// send a message to the queue with +// - delaySeconds (must be an number contained within 0 and 900) +// - messageAttributes +producer.send([ + { + id: 'id1', + body: 'Hello world with two string attributes: attr1 and attr2', + messageAttributes: { + attr1: { DataType: 'String', StringValue: 'stringValue' }, + attr2: { DataType: 'Binary', BinaryValue: new Buffer('binaryValue') } + } + }, + { + id: 'id2', + body: 'Hello world delayed by 5 seconds', + delaySeconds: 5 + } +], function(err) { + if (err) console.log(err); +}); diff --git a/sqs-producer/sqs-producer.d.ts b/sqs-producer/sqs-producer.d.ts new file mode 100644 index 0000000000..10638f90c5 --- /dev/null +++ b/sqs-producer/sqs-producer.d.ts @@ -0,0 +1,51 @@ +// Type definitions for sqs-producer +// Project: https://github.com/BBC/sqs-producer +// Definitions by: Daniel Chao +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "sqs-producer" { + + import { SQS } from "aws-sdk"; + + module SQSProducer { + + interface ProducerOpts { + queueUrl: string; + region?: string; + batchSize?: number; + sqs?: SQS; + } + + interface ProducerCallback { + (err?: Error, data?: T): any; + } + + interface ProducerMessageAttribute { + DataType: "String"|"Binary"; + StringValue?: string; + BinaryValue?: Buffer; + } + + interface ProducerMessage { + id: string; + body: string; + messageAttributes?: { [key: string]: ProducerMessageAttribute } + delaySeconds?: number; + } + + interface ProducerFactory { + create(opts: ProducerOpts): Producer; + } + + interface Producer { + send(messages: string[], cb: ProducerCallback): void; + send(messages: ProducerMessage[], cb: ProducerCallback): void; + queueSize(cb: ProducerCallback): void; + } + } + + const Producer: SQSProducer.ProducerFactory; + export = Producer; +} From b0684b27a4b565b585538a91e6237e4e9c32327d Mon Sep 17 00:00:00 2001 From: Cristian Traistaru Date: Wed, 11 May 2016 23:57:21 -0500 Subject: [PATCH 038/402] Update listCollections to use filter objects (#9283) --- mongodb/mongodb.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mongodb/mongodb.d.ts b/mongodb/mongodb.d.ts index a08251b8ba..f1a385a238 100644 --- a/mongodb/mongodb.d.ts +++ b/mongodb/mongodb.d.ts @@ -219,7 +219,7 @@ declare module "mongodb" { indexInformation(name: string, options?: { full?: boolean, readPreference?: ReadPreference | string }): Promise; indexInformation(name: string, options: { full?: boolean, readPreference?: ReadPreference | string }, callback: MongoCallback): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#listCollections - listCollections(filter: { name?: string }, options?: { batchSize?: number, readPreference?: ReadPreference | string }): CommandCursor; + listCollections(filter: Object, options?: { batchSize?: number, readPreference?: ReadPreference | string }): CommandCursor; //http://mongodb.github.io/node-mongodb-native/2.1/api/Db.html#logout logout(callback: MongoCallback): void; logout(options?: { dbName?: string }): Promise; From dcafb59ee7e92ca54fb0ea735b52485572c04add Mon Sep 17 00:00:00 2001 From: CageFox Date: Thu, 12 May 2016 07:58:19 +0300 Subject: [PATCH 039/402] Update soap.d.ts (#8709) * soap Server * Fix definitions --- soap/soap-tests.ts | 44 ++++++++++++++++++++++++++++++++++++++++++++ soap/soap.d.ts | 14 +++++++++++--- 2 files changed, 55 insertions(+), 3 deletions(-) diff --git a/soap/soap-tests.ts b/soap/soap-tests.ts index 5229cfcf8e..8010d7285e 100644 --- a/soap/soap-tests.ts +++ b/soap/soap-tests.ts @@ -2,6 +2,8 @@ import * as soap from 'soap'; import * as events from 'events'; +import * as fs from "fs"; +import * as http from "http"; const url = 'http://example.com/wsdl?wsdl'; const wsdlOptions = { name: 'value' }; @@ -21,3 +23,45 @@ soap.createClient(url, wsdlOptions, function(err: any, client: soap.Client) { }); }); +var myService = { + MyService: { + MyPort: { + MyFunction: function(args: any) { + return { + name: args.name + }; + }, + + // This is how to define an asynchronous function. + MyAsyncFunction: function(args: any, callback: any) { + // do some work + callback({ + name: args.name + }); + }, + + // This is how to receive incoming headers + HeadersAwareFunction: function(args: any, cb: any, headers: any) { + return { + name: headers.Token + }; + }, + + // You can also inspect the original `req` + reallyDeatailedFunction: function(args: any, cb: any, headers: any, req: any) { + console.log('SOAP `reallyDeatailedFunction` request from ' + req.connection.remoteAddress); + return { + name: headers.Token + }; + } + } + } + }; + +var xml = fs.readFileSync('myservice.wsdl', 'utf8'), + server = http.createServer(function(request,response) { + response.end("404: Not Found: " + request.url); + }); + +server.listen(8000); +soap.listen(server, '/wsdl', myService, xml); diff --git a/soap/soap.d.ts b/soap/soap.d.ts index 21fcb98514..fa26cbf04c 100644 --- a/soap/soap.d.ts +++ b/soap/soap.d.ts @@ -1,9 +1,9 @@ // Type definitions for soap // Project: https://www.npmjs.com/package/soap -// Definitions by: Nicole Wang +// Definitions by: Nicole Wang , Cage Fox // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module 'soap' { import * as events from 'events'; @@ -18,4 +18,12 @@ declare module 'soap' { } function createClient(wsdlPath: string, options: any, fn: (err: any, client: Client) => void): void; -} \ No newline at end of file + export interface Server extends events.EventEmitter { + addSoapHeader(soapHeader: any, name:any, namespace: any, xmlns: any): any; + changeSoapHeader(index: any, soapHeader: any, name: any, namespace: any, xmlns: any): any; + getSoapHeaders(): any; + clearSoapHeaders(): any; + log(type: any, data: any): any; + } + export function listen(server: any, path: string, service:any, wsdl: string): Server; +} From 1d065982928e04a50c939900f618c03c919e5d5e Mon Sep 17 00:00:00 2001 From: Moes Date: Thu, 12 May 2016 15:20:36 +1000 Subject: [PATCH 040/402] Update jquery.pnotify.d.ts change the return type of update() to return PNotify to enable chaining --- jquery.pnotify/jquery.pnotify.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jquery.pnotify/jquery.pnotify.d.ts b/jquery.pnotify/jquery.pnotify.d.ts index 26c927cec9..c07347c1e8 100644 --- a/jquery.pnotify/jquery.pnotify.d.ts +++ b/jquery.pnotify/jquery.pnotify.d.ts @@ -267,7 +267,7 @@ interface PNotify { /** * This function is for updating the notice. */ - update(options?: PNotifyOptions): void; + update(options?: PNotifyOptions): PNotify; /** * Remove the notice. From 6191520997f6c6c8d7c37f1bc9bf6dfc39e5565a Mon Sep 17 00:00:00 2001 From: CodeAnimal Date: Thu, 12 May 2016 06:34:45 +0100 Subject: [PATCH 041/402] Stripe node 4.6.0 - add subscription methods (#9303) * Add stripe subscription methods Add root subscription methods, in addition to subscription methods that are defined on customer objects. https://stripe.com/docs/api/node#subscriptions * Bump version to stripe-node 4.6.0 --- stripe/stripe-node-tests.ts | 33 ++++++++++ stripe/stripe-node.d.ts | 119 +++++++++++++++++++++++------------- 2 files changed, 110 insertions(+), 42 deletions(-) diff --git a/stripe/stripe-node-tests.ts b/stripe/stripe-node-tests.ts index 0a42d9dbba..960a3abfb8 100644 --- a/stripe/stripe-node-tests.ts +++ b/stripe/stripe-node-tests.ts @@ -941,6 +941,39 @@ stripe.plans.list().then(function (plans) { //#region Subscriptions tests // ################################################################################## +stripe.subscriptions.create({ plan: "platypi-dev", customer: "cus_5rfJKDJkuxzh5Q" }, function(err, subscription) { + // asynchronously called +}); +stripe.subscriptions.create({ plan: "platypi-dev", customer: "cus_5rfJKDJkuxzh5Q" }).then(function(subscription) { + // asynchronously called +}); +stripe.subscriptions.retrieve("sub_8QwCiwZ9tmMSpt", function(err, subscription) { + // asynchronously called +}); +stripe.subscriptions.retrieve("sub_8QwCiwZ9tmMSpt").then(function(subscription) { + // asynchronously called +}); + +stripe.subscriptions.update("sub_8QwCiwZ9tmMSpt", { plan: "platypi" }, function(err, subscription) { + // asynchronously called +}); +stripe.subscriptions.update("sub_8QwCiwZ9tmMSpt", { plan: "platypi" }).then(function(subscription) { + // asynchronously called +}); + +stripe.subscriptions.del("sub_8QwCiwZ9tmMSpt", function(err, subscription) { + // asynchronously called +}); +stripe.subscriptions.del("sub_8QwCiwZ9tmMSpt").then(function(subscription) { + // asynchronously called +}); + +stripe.subscriptions.list({ customer: "cus_5rfJKDJkuxzh5Q", plan: "platypi-dev" }, function(err, subscriptions) { + // asynchronously called +}); +stripe.subscriptions.list({ customer: "cus_5rfJKDJkuxzh5Q", plan: "platypi-dev" }).then(function(subscriptions) { + // asynchronously called +}); //#endregion diff --git a/stripe/stripe-node.d.ts b/stripe/stripe-node.d.ts index 5f0575b53b..202cd5790d 100644 --- a/stripe/stripe-node.d.ts +++ b/stripe/stripe-node.d.ts @@ -1,4 +1,4 @@ -// Type definitions for stripe-node 4.5.0 +// Type definitions for stripe-node 4.6.0 // Project: https://github.com/stripe/stripe-node/ // Definitions by: William Johnston , Peter Harris // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -61,6 +61,7 @@ declare namespace StripeNode { * @deprecated */ recipients: resources.Recipients; + subscriptions: resources.Subscriptions; tokens: resources.Tokens; transfers: resources.Transfers; applicationFees: resources.ApplicationFees; @@ -1250,7 +1251,7 @@ declare namespace StripeNode { subscriptions: ICustomerSubscriptions; } - interface ICustomerSubscriptions extends IList, resources.CustomerSubscriptions {} + interface ICustomerSubscriptions extends IList, resources.CustomerSubscriptions {} interface ICustomerCreationOptions extends IDataOptionsWithMetadata { /** @@ -3999,7 +4000,7 @@ declare namespace StripeNode { } } - namespace customerSubscriptions { + namespace subscriptions { /** * Subscriptions allow you to charge a customer's card on a recurring basis. A subscription ties a customer to * a particular plan you've created: https://stripe.com/docs/api#create_plan @@ -4098,7 +4099,7 @@ declare namespace StripeNode { trial_start: number; } - interface ISubscriptionCreationOptions extends IDataOptionsWithMetadata { + interface ISubscriptionCustCreationOptions extends IDataOptionsWithMetadata { /** * The identifier of the plan to subscribe the customer to. */ @@ -4143,6 +4144,13 @@ declare namespace StripeNode { trial_end?: number; } + interface ISubscriptionCreationOptions extends ISubscriptionCustCreationOptions { + /*** + * The identifier of the customer to subscribe. + */ + customer: string; + } + interface ISubscriptionUpdateOptions extends IDataOptionsWithMetadata { /** * A positive decimal (with at most two decimal places) between 1 and 100. This represents the percentage of the subscription invoice @@ -4206,6 +4214,18 @@ declare namespace StripeNode { */ at_period_end?: boolean; } + + interface ISubscriptionListOptions extends IListOptionsCreated { + /** + * The ID of the customer whose subscriptions will be retrieved + */ + customer?: string; + + /** + * The ID of the plan whose subscriptions will be retrieved + */ + plan?: string; + } } namespace refunds { @@ -5303,8 +5323,8 @@ declare namespace StripeNode { * @param customerId The customer to which the add the subscription. * @param options The options for the new subscription */ - createSubscription(customerId: string, data: customerSubscriptions.ISubscriptionCreationOptions, options: HeaderOptions, response?: IResponseFn): Promise; - createSubscription(customerId: string, data: customerSubscriptions.ISubscriptionCreationOptions, response?: IResponseFn): Promise; + createSubscription(customerId: string, data: subscriptions.ISubscriptionCustCreationOptions, options: HeaderOptions, response?: IResponseFn): Promise; + createSubscription(customerId: string, data: subscriptions.ISubscriptionCustCreationOptions, response?: IResponseFn): Promise; /** * By default, you can see the 10 most recent active subscriptions stored on a customer directly on the customer @@ -5315,8 +5335,8 @@ declare namespace StripeNode { * @param customerId The customer ID for the subscription * @param subscriptionId The ID of the subscription to retrieve */ - retrieveSubscription(customerId: string, subscriptionId: string, options: HeaderOptions, response?: IResponseFn): Promise; - retrieveSubscription(customerId: string, subscriptionId: string, response?: IResponseFn): Promise; + retrieveSubscription(customerId: string, subscriptionId: string, options: HeaderOptions, response?: IResponseFn): Promise; + retrieveSubscription(customerId: string, subscriptionId: string, response?: IResponseFn): Promise; /** * Updates an existing subscription on a customer to match the specified parameters. When changing plans or quantities, @@ -5343,8 +5363,8 @@ declare namespace StripeNode { * @param subscriptionId The ID of the subscription to update. * @param data The fields to update */ - updateSubscription(customerId: string, subscriptionId: string, data: customerSubscriptions.ISubscriptionUpdateOptions, options: HeaderOptions, response?: IResponseFn): Promise; - updateSubscription(customerId: string, subscriptionId: string, data: customerSubscriptions.ISubscriptionUpdateOptions, response?: IResponseFn): Promise; + updateSubscription(customerId: string, subscriptionId: string, data: subscriptions.ISubscriptionUpdateOptions, options: HeaderOptions, response?: IResponseFn): Promise; + updateSubscription(customerId: string, subscriptionId: string, data: subscriptions.ISubscriptionUpdateOptions, response?: IResponseFn): Promise; /** * Cancels a customer's subscription. If you set the at_period_end parameter to true, the subscription will remain active until @@ -5365,9 +5385,9 @@ declare namespace StripeNode { * @param subscriptionId The ID of the subscription to cancel. * @param data Specify when to cancel the subscription */ - cancelSubscription(customerId: string, subscriptionId: string, data: customerSubscriptions.ISubscriptionCancellationOptions, options: HeaderOptions, response?: IResponseFn): Promise; - cancelSubscription(customerId: string, subscriptionId: string, data: customerSubscriptions.ISubscriptionCancellationOptions, response?: IResponseFn): Promise; - cancelSubscription(customerId: string, subscriptionId: string, response?: IResponseFn): Promise; + cancelSubscription(customerId: string, subscriptionId: string, data: subscriptions.ISubscriptionCancellationOptions, options: HeaderOptions, response?: IResponseFn): Promise; + cancelSubscription(customerId: string, subscriptionId: string, data: subscriptions.ISubscriptionCancellationOptions, response?: IResponseFn): Promise; + cancelSubscription(customerId: string, subscriptionId: string, response?: IResponseFn): Promise; /** * You can see a list of the customer's active subscriptions. Note that the 10 most recent active subscriptions are always available @@ -5380,10 +5400,10 @@ declare namespace StripeNode { * @param customerId The ID of the customer whose subscriptions will be retrieved * @param data Filtering options */ - listSubscriptions(customerId: string, data: IListOptions, options: HeaderOptions, response?: IResponseFn>): Promise>; - listSubscriptions(customerId: string, data: IListOptions, response?: IResponseFn>): Promise>; - listSubscriptions(customerId: string, options: HeaderOptions, response?: IResponseFn>): Promise>; - listSubscriptions(customerId: string, response?: IResponseFn>): Promise>; + listSubscriptions(customerId: string, data: IListOptions, options: HeaderOptions, response?: IResponseFn>): Promise>; + listSubscriptions(customerId: string, data: IListOptions, response?: IResponseFn>): Promise>; + listSubscriptions(customerId: string, options: HeaderOptions, response?: IResponseFn>): Promise>; + listSubscriptions(customerId: string, response?: IResponseFn>): Promise>; /** @@ -5410,19 +5430,7 @@ declare namespace StripeNode { deleteSubscriptionDiscount(customerId: string, subscriptionId: string, response?: IResponseFn): Promise;; } - class CustomerSubscriptions extends StripeResource { - /** - * Creates a new subscription on an existing customer. - * - * @returns The newly created subscription object if the call succeeded. If the customer has no card or the - * attempted charge fails, this call throws an error (unless the specified plan is free or has a trial - * period). - * - * @param options The options for the new subscription - */ - create(data: customerSubscriptions.ISubscriptionCreationOptions, options: HeaderOptions, response?: IResponseFn): Promise; - create(data: customerSubscriptions.ISubscriptionCreationOptions, response?: IResponseFn): Promise; - + class SubscriptionsBase extends StripeResource { /** * By default, you can see the 10 most recent active subscriptions stored on a customer directly on the customer * object, but you can also retrieve details about a specific active subscription for a customer. @@ -5431,8 +5439,8 @@ declare namespace StripeNode { * * @param subscriptionId The ID of the subscription to retrieve */ - retrieve(subscriptionId: string, options: HeaderOptions, response?: IResponseFn): Promise; - retrieve(subscriptionId: string, response?: IResponseFn): Promise; + retrieve(subscriptionId: string, options: HeaderOptions, response?: IResponseFn): Promise; + retrieve(subscriptionId: string, response?: IResponseFn): Promise; /** * Updates an existing subscription on a customer to match the specified parameters. When changing plans or quantities, @@ -5458,8 +5466,8 @@ declare namespace StripeNode { * @param subscriptionId The ID of the subscription to update. * @param data The fields to update */ - update(subscriptionId: string, data: customerSubscriptions.ISubscriptionUpdateOptions, options: HeaderOptions, response?: IResponseFn): Promise; - update(subscriptionId: string, data: customerSubscriptions.ISubscriptionUpdateOptions, response?: IResponseFn): Promise; + update(subscriptionId: string, data: subscriptions.ISubscriptionUpdateOptions, options: HeaderOptions, response?: IResponseFn): Promise; + update(subscriptionId: string, data: subscriptions.ISubscriptionUpdateOptions, response?: IResponseFn): Promise; /** * Cancels a customer's subscription. If you set the at_period_end parameter to true, the subscription will remain active until @@ -5479,10 +5487,10 @@ declare namespace StripeNode { * @param subscriptionId The ID of the subscription to cancel. * @param data Specify when to cancel the subscription */ - del(subscriptionId: string, data: customerSubscriptions.ISubscriptionCancellationOptions, options: HeaderOptions, response?: IResponseFn): Promise; - del(subscriptionId: string, data: customerSubscriptions.ISubscriptionCancellationOptions, response?: IResponseFn): Promise; - del(subscriptionId: string, options: HeaderOptions, response?: IResponseFn): Promise; - del(subscriptionId: string, response?: IResponseFn): Promise; + del(subscriptionId: string, data: subscriptions.ISubscriptionCancellationOptions, options: HeaderOptions, response?: IResponseFn): Promise; + del(subscriptionId: string, data: subscriptions.ISubscriptionCancellationOptions, response?: IResponseFn): Promise; + del(subscriptionId: string, options: HeaderOptions, response?: IResponseFn): Promise; + del(subscriptionId: string, response?: IResponseFn): Promise; /** * You can see a list of the customer's active subscriptions. Note that the 10 most recent active subscriptions are always available @@ -5494,10 +5502,10 @@ declare namespace StripeNode { * * @param data Filtering options */ - list(data: IListOptions, options: HeaderOptions, response?: IResponseFn>): Promise>; - list(data: IListOptions, response?: IResponseFn>): Promise>; - list(options: HeaderOptions, response?: IResponseFn>): Promise>; - list(response?: IResponseFn>): Promise>; + list(data: subscriptions.ISubscriptionListOptions, options: HeaderOptions, response?: IResponseFn>): Promise>; + list(data: subscriptions.ISubscriptionListOptions, response?: IResponseFn>): Promise>; + list(options: HeaderOptions, response?: IResponseFn>): Promise>; + list(response?: IResponseFn>): Promise>; /** * Removes the currently applied discount on a subscription. @@ -5511,6 +5519,33 @@ declare namespace StripeNode { deleteDiscount(subscriptionId: string, response?: IResponseFn): Promise;; } + class Subscriptions extends SubscriptionsBase { + /** + * Creates a new subscription on an existing customer. + * + * @returns The newly created subscription object if the call succeeded. If the customer has no card or the + * attempted charge fails, this call throws an error (unless the specified plan is free or has a trial + * period). + * + * @param options The options for the new subscription + */ + create(data: subscriptions.ISubscriptionCreationOptions, options: HeaderOptions, response?: IResponseFn): Promise; + create(data: subscriptions.ISubscriptionCreationOptions, response?: IResponseFn): Promise; + } + class CustomerSubscriptions extends SubscriptionsBase { + /** + * Creates a new subscription on an existing customer. + * + * @returns The newly created subscription object if the call succeeded. If the customer has no card or the + * attempted charge fails, this call throws an error (unless the specified plan is free or has a trial + * period). + * + * @param options The options for the new subscription + */ + create(data: subscriptions.ISubscriptionCustCreationOptions, options: HeaderOptions, response?: IResponseFn): Promise; + create(data: subscriptions.ISubscriptionCustCreationOptions, response?: IResponseFn): Promise; + } + class Disputes extends StripeResource { /** * Retrieves the dispute with the given ID. From 1ec3d510e0c4d7c50e708ca7cb0765c7e06fa2ed Mon Sep 17 00:00:00 2001 From: Daniel Chao Date: Wed, 11 May 2016 22:49:18 -0700 Subject: [PATCH 042/402] Add sqs-consumer typings (#9277) * add sqs-consumer typings * add explicit any * use site url * Rename sqs-consumer-test.ts to sqs-consumer-tests.ts --- sqs-consumer/sqs-consumer-tests.ts | 28 +++++++++++++++++++ sqs-consumer/sqs-consumer.d.ts | 43 ++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 sqs-consumer/sqs-consumer-tests.ts create mode 100644 sqs-consumer/sqs-consumer.d.ts diff --git a/sqs-consumer/sqs-consumer-tests.ts b/sqs-consumer/sqs-consumer-tests.ts new file mode 100644 index 0000000000..516aeb6adf --- /dev/null +++ b/sqs-consumer/sqs-consumer-tests.ts @@ -0,0 +1,28 @@ +/// + +import * as Consumer from "sqs-consumer"; + +var app = Consumer.create({ + queueUrl: 'https://sqs.eu-west-1.amazonaws.com/account-id/queue-name', + handleMessage: function (message, done) { + // do some work with `message` + done(); + } +}); + +var app2 = Consumer.create({ + queueUrl: 'https://sqs.eu-west-1.amazonaws.com/account-id/queue-name', + handleMessage: function(message, done){ + done(); + }, + region: "us-west-1", + batchSize: 15, + visibilityTimeout: 50, + waitTimeSeconds: 50 +}); + +app.on('error', function (err: any) { + console.log(err.message); +}); + +app.start(); diff --git a/sqs-consumer/sqs-consumer.d.ts b/sqs-consumer/sqs-consumer.d.ts new file mode 100644 index 0000000000..8c2315d083 --- /dev/null +++ b/sqs-consumer/sqs-consumer.d.ts @@ -0,0 +1,43 @@ +// Type definitions for sqs-consumer +// Project: https://github.com/BBC/sqs-consumer +// Definitions by: Daniel Chao +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "sqs-consumer" { + + import { SQS } from "aws-sdk"; + + module SQSConsumer { + + interface MessageHandler { + (message: SQS.Message, done: Function): any; + } + + interface ConsumerOpts { + queueUrl: string; + handleMessage: MessageHandler; + region?: string; + attributeNames?: string[]; + messageAttributeNames?: string[]; + batchSize?: number; + visibilityTimeout?: number; + waitTimeSeconds?: number; + authenticationErrorTimeout?: number; + sqs?: SQS; + } + + interface Consumer extends NodeJS.EventEmitter { + start (): void; + stop (): void; + } + + interface ConsumerFactory { + create(opts: ConsumerOpts): Consumer; + } + } + const Consumer: SQSConsumer.ConsumerFactory; + export = Consumer; + +} From 1f8e49ff30c26891569a2d4594bd3d6923108b4a Mon Sep 17 00:00:00 2001 From: Brendon Colburn Date: Sat, 14 May 2016 10:26:58 -0400 Subject: [PATCH 043/402] Add some properties to Restangularized Elements (#9240) When an element is restangularized it often has one to many of the properties added in this proposed code change. Leveraging the route, id, and reqParams gives greater functionality to restangularized objects in typescript projects. --- restangular/restangular.d.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/restangular/restangular.d.ts b/restangular/restangular.d.ts index 410713e938..b1a975ccfc 100644 --- a/restangular/restangular.d.ts +++ b/restangular/restangular.d.ts @@ -116,6 +116,9 @@ declare namespace restangular { withHttpConfig(httpConfig: angular.IRequestShortcutConfig): IElement; save(queryParams?: any, headers?: any): IPromise; getRestangularUrl(): string; + route?: string; + id?: string; + reqParams?: any; } interface ICollection extends IService, Array { From dfb808f777e080fa093669e84d122a5a6c163311 Mon Sep 17 00:00:00 2001 From: Nicolas Schmitt Date: Sat, 14 May 2016 16:28:41 +0200 Subject: [PATCH 044/402] update react-autosuggest (#9262) * update react-autosuggest * fixed InputProps.onChange & authors * removed unnecessary interface --- react-autosuggest/react-autosuggest-tests.tsx | 352 +++++++++++++++++- react-autosuggest/react-autosuggest.d.ts | 76 ++-- 2 files changed, 389 insertions(+), 39 deletions(-) diff --git a/react-autosuggest/react-autosuggest-tests.tsx b/react-autosuggest/react-autosuggest-tests.tsx index 4fb4947e19..7a16a56914 100644 --- a/react-autosuggest/react-autosuggest-tests.tsx +++ b/react-autosuggest/react-autosuggest-tests.tsx @@ -1,12 +1,346 @@ -/// -/// +// React-Autosuggest Test +// ================================================================================ +/// +/// +/// +//region Imports +import React = require('react'); +import ReactDOM = require('react-dom'); import Autosuggest = require('react-autosuggest'); -import * as React from 'react'; +//endregion -let autosuggest = suggestion.name} - renderSuggestion={(suggestion: any) => ({suggestion.name})} - inputProps={{value: "El", onChange: (event: any, params: {newValue: string, method: string}) => {}}} -/> +interface Language { + name: string; + year: number; +} + +// https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions#Using_Special_Characters +function escapeRegexCharacters(str: string): string { + return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +export class ReactAutosuggestBasicTest extends React.Component { + //region Fields + public 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) { + super(props); + + this.state = { + value: '', + suggestions: this.getSuggestions('') + }; + } + //endregion + + //region Rendering methods + public render(): JSX.Element { + const {value, suggestions} = this.state; + const inputProps = { + placeholder: `Type 'c'`, + value, + onChange: this.onChange.bind(this) + }; + + return ; + } + + protected renderSuggestion(suggestion: Language): JSX.Element { + return {suggestion.name}; + } + //endregion + + //region Event handlers + protected onChange(event: React.FormEvent, {newValue, method}): void { + this.setState({ + value: newValue + }); + } + + protected onSuggestionsUpdateRequested({ value }): void { + this.setState({ + suggestions: this.getSuggestions(value) + }); + } + //endregion + + //region Helper methods + protected getSuggestions(value: string): Language[] { + const escapedValue = escapeRegexCharacters(value.trim()); + + if (escapedValue === '') { + return []; + } + + const regex = new RegExp('^' + escapedValue, 'i'); + + return ReactAutosuggestBasicTest.languages.filter(language => regex.test(language.name)); + } + + protected getSuggestionValue(suggestion: Language): string { + return suggestion.name; + } + //endregion +} + +ReactDOM.render(, document.getElementById('app')); + +interface LanguageGroup { + title: string; + languages: Language[]; +} + +export class ReactAutosuggestMultipleTest extends React.Component { + //region Fields + public static languages: LanguageGroup[] = [ + { + title: '1970s', + languages: [ + {name: 'C', year: 1972} + ] + }, + { + title: '1980s', + languages: [ + {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} + ] + }, + { + title: '2000s', + languages: [ + {name: 'C#', year: 2000}, + {name: 'Scala', year: 2003}, + {name: 'Clojure', year: 2007}, + {name: 'Go', year: 2009} + ] + }, + { + title: '2010s', + languages: [ + {name: 'Elm', year: 2012} + ] + } + ]; + //endregion + + //region Constructor + constructor(props: any) { + super(props); + + this.state = { + value: '', + suggestions: this.getSuggestions('') + }; + } + //endregion + + //region Rendering methods + public render(): JSX.Element { + const { value, suggestions } = this.state; + const inputProps = { + placeholder: `Type 'c'`, + value, + onChange: this.onChange.bind(this) + }; + + return ; + } + + protected renderSuggestion(suggestion: Language): JSX.Element { + return {suggestion.name}; + } + + protected renderSectionTitle(section: LanguageGroup): JSX.Element { + return {section.title}; + } + //endregion + + //region Event handlers + protected onChange(event: React.FormEvent, { newValue, method }): void { + this.setState({ + value: newValue + }); + } + + protected onSuggestionsUpdateRequested({ value }): void { + this.setState({ + suggestions: this.getSuggestions(value) + }); + } + //endregion + + //region Helper methods + protected getSuggestions(value: string): LanguageGroup[] { + const escapedValue = escapeRegexCharacters(value.trim()); + + if (escapedValue === '') { + return []; + } + + const regex = new RegExp('^' + escapedValue, 'i'); + + return ReactAutosuggestMultipleTest.languages + .map(section => { + return { + title: section.title, + languages: section.languages.filter(language => regex.test(language.name)) + }; + }) + .filter(section => section.languages.length > 0); + } + + protected getSuggestionValue(suggestion: Language) { + return suggestion.name; + } + + protected getSectionSuggestions(section: LanguageGroup) { + return section.languages; + } + //endregion +} + +ReactDOM.render(, document.getElementById('app')); + +interface IPerson { + first: string; + last: string; + twitter: string; +} + +export class ReactAutosuggestCustomTest extends React.Component { + //region Fields + public static people: IPerson[] = [ + {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) { + super(props); + + this.state = { + value: '', + suggestions: this.getSuggestions('') + }; + } + //endregion + + //region Rendering methods + public render(): JSX.Element { + const { value, suggestions } = this.state; + const inputProps = { + placeholder: "Type 'c'", + value, + onChange: this.onChange.bind(this) + }; + + return ; + } + + protected renderSuggestion(suggestion: IPerson, { value, valueBeforeUpDown }): 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 + } + }); + + return + + { + parts.map((part, index) => { + const className = part.highlight ? 'highlight' : null; + + return {part.text}; + }) + } + + ; + } + //endregion + + //region Event handlers + protected onChange(event: React.FormEvent, {newValue, method}): void { + this.setState({ + value: newValue + }); + } + + protected onSuggestionsUpdateRequested({ value }): void { + this.setState({ + suggestions: this.getSuggestions(value) + }); + } + //endregion + + //region Helper methods + protected getSuggestions(value: string): IPerson[] { + const escapedValue = escapeRegexCharacters(value.trim()); + + if (escapedValue === '') { + return []; + } + + const regex = new RegExp('\\b' + escapedValue, 'i'); + + return ReactAutosuggestCustomTest.people.filter(person => regex.test(this.getSuggestionValue(person))); + } + + protected getSuggestionValue(suggestion: IPerson): string { + return `${suggestion.first} ${suggestion.last}`; + } + //endregion +} + +ReactDOM.render(, document.getElementById('app')); diff --git a/react-autosuggest/react-autosuggest.d.ts b/react-autosuggest/react-autosuggest.d.ts index cb67474ae1..f53238b882 100644 --- a/react-autosuggest/react-autosuggest.d.ts +++ b/react-autosuggest/react-autosuggest.d.ts @@ -1,51 +1,67 @@ -// Type definitions for react-autosuggest 3.7.1 -// Project: https://github.com/moroshko/react-autosuggest -// Definitions by: Stephen Jelfs +// Type definitions for react-autosuggest v3.7.3 +// Project: http://react-autosuggest.js.org/ +// Definitions by: Nicolas Schmitt // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// -declare module "react-autosuggest" { - interface Suggestion { - text: string; - } +declare namespace ReactAutosuggest { + import React = __React; + + interface SuggestionUpdateRequest { + value: string; + reason: string; + } + + interface InputValues { + value: string; + valueBeforeUpDown?: string; + } + + interface InputProps extends React.HTMLAttributes { + value: string; + onChange: (event: React.FormEvent, params?: {newValue: string, method: string}) => void; + } + + interface SuggestionSelectedEventData { + method: string; + sectionIndex: number; + suggestion: any; + suggestionValue: string; + } interface Theme { - container?: string; - containerOpen?: string; - input?: string; - suggestionsContainer?: string; - suggestion?: string; - suggestionFocused?: string; - sectionContainer?: string; - sectionTitle?: string; - sectionSuggestionsContainer?: string; + container: string; + containerOpen: string; + input: string; + sectionContainer: string; + sectionSuggestionsContainer: string; + sectionTitle: string; + suggestion: string; + suggestionFocused: string; + suggestionsContainer: string; } - interface InputProps { - value: string; - onChange: (event: any, params: {newValue: string, method: string}) => void; - type?: string; - placeholder?: string; - } - - interface AutosuggestProps extends __React.Props { + interface AutosuggestProps extends React.Props { suggestions: any[]; - onSuggestionsUpdateRequested?: (params: {value: string, reason: string}) => void; + onSuggestionsUpdateRequested?: (request: SuggestionUpdateRequest) => void; getSuggestionValue: (suggestion: any) => string; - renderSuggestion: (suggestion: any, params: {value: string, valueBeforeUpDown: string}) => __React.ReactElement; + renderSuggestion: (suggestion: any, inputValues: InputValues) => JSX.Element; inputProps: InputProps; shouldRenderSuggestions?: (value: string) => boolean; multiSection?: boolean; - renderSectionTitle?: (section: any) => __React.ReactElement; + renderSectionTitle?: (section: any, inputValues: InputValues) => JSX.Element; getSectionSuggestions?: (section: any) => any[]; - onSuggestionSelected?: (event: any, params: {suggestion: any, suggestionValue: string, method: string}) => void; + onSuggestionSelected?: (event: React.FormEvent, data: SuggestionSelectedEventData) => void; focusInputOnSuggestionClick?: boolean; theme?: Theme; id?: string; } - class Autosuggest extends __React.Component {} + class Autosuggest extends React.Component {} +} +declare module 'react-autosuggest' { + import Autosuggest = ReactAutosuggest.Autosuggest; export = Autosuggest; } From fc810d7671e259fc01e8d8941e5e450579bb72cd Mon Sep 17 00:00:00 2001 From: Linda_pp Date: Sun, 15 May 2016 00:03:34 +0900 Subject: [PATCH 045/402] Add popper.d.ts (#9266) https://github.com/FezVrasta/popper.js/ --- popper.js/popper-tests.ts | 39 ++++++++++++++++++++++++++ popper.js/popper.d.ts | 58 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 97 insertions(+) create mode 100644 popper.js/popper-tests.ts create mode 100644 popper.js/popper.d.ts diff --git a/popper.js/popper-tests.ts b/popper.js/popper-tests.ts new file mode 100644 index 0000000000..2dc98bbda3 --- /dev/null +++ b/popper.js/popper-tests.ts @@ -0,0 +1,39 @@ +/// + +import * as Popper from 'popper.js'; + +var reference = document.querySelector('.my-button'); +var thePopper = new Popper( + reference, { + content: 'My awesome popper!' + } +); +thePopper.update(); +thePopper.destroy(); + +var options = { + placement: 'bottom', + offset: 0, + arrowElement: document.querySelector('.arrow'), + modifiersIgnored: ['applyStyle'], + } as Popper.PopperOptions; + +var thePopperWithOptions = new Popper( + reference, { + content: 'My awesome popper!', + }, options); + +var popper = document.querySelector('.my-popper'); +var anotherPopper = new Popper( + reference, + popper +); + +var reference = document.querySelector('.my-button'); +var popper = document.querySelector('.my-popper'); +var anotherPopper = new Popper(reference, popper).onCreate(function(instance) { + console.log(instance.offsets); +}).onUpdate(function(data) { + var p = data.offsets.popper; + console.log(`top: ${p.top}, left: ${p.left}`); +}); diff --git a/popper.js/popper.d.ts b/popper.js/popper.d.ts new file mode 100644 index 0000000000..71713a2ae1 --- /dev/null +++ b/popper.js/popper.d.ts @@ -0,0 +1,58 @@ +// Type definitions for popper.js v0.4.0 +// Project: https://github.com/FezVrasta/popper.js/ +// Definitions by: rhysd +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace Popper { + export interface PopperOptions { + placement?: string; + gpuAcceleration?: boolean; + offset?: number; + boundariesElement?: string | Element; + boundariesPadding?: number; + preventOverflowOrder?: ("left" | "right" | "top" | "bottom")[]; + flipBehavior?: string | string[]; + modifiers?: string[]; + modifiersIgnored?: string[]; + removeOnDestroy?: boolean; + arrowElement?: string | Element; + } + export class Modifiers { + applyStyle(data: Object): Object; + shift(data: Object): Object; + preventOverflow(data: Object): Object; + keepTogether(data: Object): Object; + flip(data: Object): Object; + offset(data: Object): Object; + arrow(data: Object): Object; + } + export interface Data { + placement: string; + offsets: { + popper: { + position: string; + top: number; + left: number; + }; + }; + } +} + +declare class Popper { + public modifiers: Popper.Modifiers; + public placement: string; + + constructor(reference: Element, popper: Element | Object, options?: Popper.PopperOptions); + + destroy(): void; + update(): void; + onCreate(cb: (data: Popper.Data) => void): this; + onUpdate(cb: (data: Popper.Data) => void): this; + parse(config: Object): Element; + runModifiers(data: Object, modifiers: string[], ends: Function): void; + isModifierRequired(): boolean; +} + +declare module "popper.js" { + export = Popper; +} From 57fdaeeec3e49a60b41c9743b788adb108e9953b Mon Sep 17 00:00:00 2001 From: Tom O'Neill Date: Sat, 14 May 2016 17:05:24 +0200 Subject: [PATCH 046/402] Update NetworkInformation.d.ts (#9269) --- cordova/plugins/NetworkInformation.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/cordova/plugins/NetworkInformation.d.ts b/cordova/plugins/NetworkInformation.d.ts index 4f80fdbb7e..0d49597e3a 100644 --- a/cordova/plugins/NetworkInformation.d.ts +++ b/cordova/plugins/NetworkInformation.d.ts @@ -47,6 +47,7 @@ interface Connection { */ type: string; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var Connection: { From 94e7e129eefc0adb155472616413607519777def Mon Sep 17 00:00:00 2001 From: Linda_pp Date: Sun, 15 May 2016 00:05:45 +0900 Subject: [PATCH 047/402] New: Add type definitions for 'rc-tooltip' module (#9271) --- rc-tooltip/rc-tooltip-tests.tsx | 37 +++++++++++++++++++++++++++++ rc-tooltip/rc-tooltip.d.ts | 41 +++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+) create mode 100644 rc-tooltip/rc-tooltip-tests.tsx create mode 100644 rc-tooltip/rc-tooltip.d.ts diff --git a/rc-tooltip/rc-tooltip-tests.tsx b/rc-tooltip/rc-tooltip-tests.tsx new file mode 100644 index 0000000000..33816d7949 --- /dev/null +++ b/rc-tooltip/rc-tooltip-tests.tsx @@ -0,0 +1,37 @@ +/// +/// + +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; +import * as Tooltip from 'rc-tooltip'; + +ReactDOM.render( + tooltip}> + hover + , + document.querySelector('.app') +); + +ReactDOM.render( + tooltip} + overlayClassName="overlay" + mouseEnterDelay={0} + mouseLeaveDelay={0.1} + overlayStyle={{color: 'red'}} + prefixCls="my-" + transitionName="cool-transition" + onVisibleChange={() => console.log('visible changed')} + visible + defaultVisible + onPopupAlign={(popup, align) => console.log('aligned:', popup, align)} + arrowContent={
} + getTooltipContainer={() => document.querySelector('.foo')} + destroyTooltipOnHide + > + hover + , + document.querySelector('.another-app') +); diff --git a/rc-tooltip/rc-tooltip.d.ts b/rc-tooltip/rc-tooltip.d.ts new file mode 100644 index 0000000000..317b8d1fc4 --- /dev/null +++ b/rc-tooltip/rc-tooltip.d.ts @@ -0,0 +1,41 @@ +// Type definitions for rc-tooltip v3.3.2 +// Project: https://github.com/react-component/tooltip +// Definitions by: rhysd +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace Tooltip { + import React = __React; + + export type Trigger = "hover" | "click" | "focus"; + export type Placement = + "left" | "right" | "top" | "bottom" | + "topLeft" | "topRight" | "bottomLeft" | "bottomRight"; + + export interface Props extends React.Props { + overlayClassName?: string; + trigger?: Trigger[]; + mouseEnterDelay?: number; + mouseLeaveDelay?: number; + overlayStyle?: React.CSSProperties; + prefixCls?: string; + transitionName?: string; + onVisibleChange?: () => void; + visible?: boolean; + defaultVisible?: boolean; + placement?: Placement | Object; + align?: Object; + onPopupAlign?: (popupDomNode: Element, align: Object) => void; + overlay: React.ReactElement; + arrowContent?: React.ReactNode; + getTooltipContainer?: () => Element; + destroyTooltipOnHide?: boolean; + } +} + +declare class Tooltip extends __React.Component {} + +declare module "rc-tooltip" { + export = Tooltip +} From 9ee4cbccdc782cd36f223c15865ef380786a39ec Mon Sep 17 00:00:00 2001 From: Rajab Shakirov Date: Sat, 14 May 2016 18:05:57 +0300 Subject: [PATCH 048/402] update react-calendar-timeline.d.ts for ES6 module system support. (#9272) * update react-calendar-timeline.d.ts by issue: https://github.com/namespace-ee/react-calendar-timeline/issues/17#issuecomment-217128161 * update definitions for ES6 module system support. --- .../react-calendar-timeline-tests.tsx | 6 +++--- react-calendar-timeline/react-calendar-timeline.d.ts | 9 ++++----- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/react-calendar-timeline/react-calendar-timeline-tests.tsx b/react-calendar-timeline/react-calendar-timeline-tests.tsx index ab477ec6e7..7ce99f1ddf 100644 --- a/react-calendar-timeline/react-calendar-timeline-tests.tsx +++ b/react-calendar-timeline/react-calendar-timeline-tests.tsx @@ -4,7 +4,7 @@ import * as React from "react"; import * as moment from 'moment'; -import * as Timeline from 'react-calendar-timeline'; +import ReactCalendarTimeline from 'react-calendar-timeline'; const groups = [ {id: 1, title: 'group 1'}, @@ -17,12 +17,12 @@ const items = [ {id: 3, group: 1, title: 'item 3', start_time: moment().add(2, 'hour'), end_time: moment().add(3, 'hour')} ] -class ReactCalendarTimeline extends React.Component<{}, {}> { +class ExampleOfUsingReactCalendarTimeline extends React.Component<{}, {}> { render(){ return(
Rendered by react! - ); start_time: any; end_time: any; canMove?: boolean; @@ -65,7 +65,6 @@ declare module "react-calendar-timeline" { onBoundsChange?(canvasTimeStart:any, canvasTimeEnd:any): any; children?: any; } - - let ReactCalendarTimeline: __React.ClassicComponentClass; - export = ReactCalendarTimeline; -} + let ReactCalendarTimeline : __React.ClassicComponentClass; + export default ReactCalendarTimeline; +} \ No newline at end of file From d49da70120a46b4276439b7d1bcf20d6d55f7b16 Mon Sep 17 00:00:00 2001 From: Jeongho Nam Date: Sun, 15 May 2016 00:55:34 +0900 Subject: [PATCH 049/402] STL-TypeScript v0.9.5-b (#9289) * TypeScript-STL TypeScript-STL v0.9.5 by Jeongho Nam * TypeScript-STL v0.9.5 by Jeongho Nam * STL-TypeScript v0.9.5-b Try again --- typescript-stl/typescript-stl-tests.ts | 7 + typescript-stl/typescript-stl.d.ts | 9356 ++++++++++++++++++++++++ 2 files changed, 9363 insertions(+) create mode 100644 typescript-stl/typescript-stl-tests.ts create mode 100644 typescript-stl/typescript-stl.d.ts diff --git a/typescript-stl/typescript-stl-tests.ts b/typescript-stl/typescript-stl-tests.ts new file mode 100644 index 0000000000..aebf205f06 --- /dev/null +++ b/typescript-stl/typescript-stl-tests.ts @@ -0,0 +1,7 @@ +/// + +declare var global: any; +declare var require: any; + +global["std"] = require("typescript-stl"); +std.example.test_all(); \ No newline at end of file diff --git a/typescript-stl/typescript-stl.d.ts b/typescript-stl/typescript-stl.d.ts new file mode 100644 index 0000000000..659bd89cc2 --- /dev/null +++ b/typescript-stl/typescript-stl.d.ts @@ -0,0 +1,9356 @@ +// Type definitions for TypeScript-STL v0.9.4 +// Project: https://github.com/samchon/stl +// Definitions by: Jeongho Nam +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace std.base { + /** + *

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_: IContainer; + /** + * Construct from the source {@link IContainer container}. + * + * @param source The source + */ + constructor(source: 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(): Container; + /** + *

Whether an iterator is equal with the iterator.

+ * + *

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

+ * + *

Note

+ *

Iterator's equal_to() only compare souce container and index number.

+ * + *

Although elements in a pair, key and value are equal_to, if the source map or + * index number is different, then the {@link equal_to equal_to()} 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. + */ + equal_to(obj: Iterator): boolean; + /** + *

Get value of the iterator is pointing.

+ * + * @return A value of the iterator. + */ + value: T; + abstract swap(obj: Iterator): void; + } +} +declare namespace std.base { + /** + * A reverse and bi-directional iterator.

+ * + * @author Jeongho Nam + */ + abstract class ReverseIterator extends Iterator { + protected iterator_: Iterator; + constructor(iterator: Iterator); + equal_to(obj: Iterator): boolean; + equal_to(obj: ReverseIterator): boolean; + /** + * @inheritdoc + */ + value: T; + swap(obj: Iterator): void; + swap(obj: ReverseIterator): void; + } +} +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

+ * + *

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

+ * + *

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. + *
+ *
+ * + *
    + *
  • Reference: http://www.cplusplus.com/reference/vector/vector/ + *
+ * + * @param Type of the elements. + * + * @author Jeongho Nam + */ + class Vector extends Array implements base.IArray { + /** + * Type definition of {@link Vector}'s {@link VectorIterator iterator}. + */ + static iterator: typeof VectorIterator; + /** + *

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: base.IContainer); + /** + *

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: base.Iterator, end: base.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; + /** + * @inheritdoc + */ + pop_back(): 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; + /** + *

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 end end()} if the operation erased the last element in the + * sequence. + */ + erase(begin: VectorIterator, end: VectorIterator): VectorIterator; + /** + * @inheritdoc + */ + swap(obj: base.IContainer): void; + } + /** + *

An iterator of Vector.

+ * + * @param Type of the elements. + * + * @author Jeongho Nam + */ + class VectorIterator extends base.Iterator implements base.IArrayIterator { + /** + * Sequence number of iterator in the source {@link Vector}. + */ + protected index_: number; + /** + *

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 + */ + protected vector: Vector; + /** + * @inheritdoc + */ + /** + * Set value. + */ + value: T; + /** + *

Whether an iterator is equal with the iterator.

+ * + *

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

+ * + *

Note

+ *

Iterator's equal_to() only compare souce container and index number.

+ * + *

Although elements in a pair, key and value are equal_to, if the source map or + * index number is different, then the {@link equal_to equal_to()} 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. + */ + equal_to(obj: VectorIterator): boolean; + index: number; + /** + * @inheritdoc + */ + prev(): VectorIterator; + /** + * @inheritdoc + */ + next(): VectorIterator; + /** + * @inheritdoc + */ + advance(n: number): VectorIterator; + /** + * @inheritdoc + */ + swap(obj: VectorIterator): void; + } + /** + *

A reverse-iterator of Vector.

+ * + * @param Type of the elements. + * + * @author Jeongho Nam + */ + class VectorReverseIterator extends base.ReverseIterator implements base.IArrayIterator { + constructor(iterator: VectorIterator); + /** + * @hidden + */ + private vector_iterator; + index: number; + value: T; + /** + * @inheritdoc + */ + prev(): VectorReverseIterator; + /** + * @inheritdoc + */ + next(): VectorReverseIterator; + /** + * @inheritdoc + */ + advance(n: number): VectorReverseIterator; + } +} +declare namespace std.base { + /** + *

An abstract

+ * + *

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.

+ * + *

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(array: Array); + /** + *

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: IContainer); + /** + *

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 + */ + abstract assign>(begin: InputIterator, end: InputIterator): void; + /** + * @inheritdoc + */ + clear(): void; + /** + * @inheritdoc + */ + abstract push(...items: U[]): number; + /** + * @inheritdoc + */ + abstract insert(position: Iterator, val: T): Iterator; + /** + * @inheritdoc + */ + abstract erase(position: Iterator): Iterator; + /** + * @inheritdoc + */ + abstract erase(begin: Iterator, end: Iterator): Iterator; + /** + * @inheritdoc + */ + abstract begin(): Iterator; + /** + * @inheritdoc + */ + abstract end(): Iterator; + /** + * @inheritdoc + */ + abstract rbegin(): ReverseIterator; + /** + * @inheritdoc + */ + abstract rend(): ReverseIterator; + /** + * @inheritdoc + */ + abstract size(): number; + /** + * @inheritdoc + */ + empty(): boolean; + /** + * @inheritdoc + */ + swap(obj: Container): void; + } +} +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}s, {@link Deque}s 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}s 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}s perform worse 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
+ *
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.
+ *
+ * + *
    + *
  • Reference: http://www.cplusplus.com/reference/deque/deque/
  • + *
+ * + * @param Type of the elements. + * + * @author Jeongho Nam + */ + class Deque extends base.Container implements base.IArray, base.IDeque { + /** + * Type definition of {@link Deque}'s {@link DequeIterator iterator}. + */ + static iterator: typeof DequeIterator; + /** + *

Row size of the {@link matrix_ matrix} which contains elements.

+ * + *

Note that the {@link ROW} affects on time complexity of accessing and inserting element. + * Accessing element is {@link ROW} times slower than ordinary {@link Vector} and inserting element + * in middle position is {@link ROW} times faster than ordinary {@link Vector}.

+ * + *

When the {@link ROW} returns 8, time complexity of accessing element is O(8) and inserting + * element in middle position is O(N/8). ({@link Vector}'s time complexity of accessement is O(1) + * and inserting element is O(N)).

+ */ + private static ROW; + /** + *

Minimum {@link capacity}.

+ * + *

Although a {@link Deque} has few elements, even no element is belonged to, the {@link Deque} + * keeps the minimum {@link capacity} at least.

+ */ + private static MIN_CAPACITY; + /** + *

A matrix containing elements.

+ * + *

This {@link matrix_} is the biggest difference one between {@link Vector} and {@link Deque}. + * Its number of rows follows {@link ROW} and number of columns follows {@link get_col_size} which + * returns divide of {@link capacity} and {@link ROW}.

+ * + * By separating segment of elements (segment: row, elements in a segment: col), {@link Deque} takes + * advantage of time complexity on inserting element in middle position. {@link Deque} is {@link ROW} + * times faster than {@link Vector} when inserting elements in middle position.

+ * + *

However, separating segment of elements from matrix, {@link Deque} also takes disadvantage of + * time complexity on accessing element. {@link Deque} is {@link ROW} times slower than {@link Vector} + * when accessing element.

+ */ + private matrix_; + /** + * Number of elements in the {@link Deque}. + */ + private size_; + /** + *

Size of allocated storage capacity.

+ * + *

The {@link capacity_ capacity} is size of the storage space currently allocated for the + * {@link Deque container}, expressed in terms of elements.

+ * + *

This {@link capacity_ 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_ 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_ capacity} of a {@link Deque container} can be explicitly altered by + * calling member {@link Deque.reserve}.

+ */ + private capacity_; + /** + * Get column size; {@link capacity_ capacity} / {@link ROW row}. + */ + private get_col_size(); + /** + *

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: base.IContainer); + /** + *

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: base.Iterator, end: base.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 + */ + 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.

+ * + *

Fetches index of row and column of {@link matrix_} from sequence number.

+ * + * @param index Sequence number + */ + 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 + */ + erase(position: DequeIterator): DequeIterator; + /** + * @inheritdoc + */ + erase(begin: DequeIterator, end: DequeIterator): DequeIterator; + /** + * @inheritdoc + */ + swap(obj: base.IContainer): void; + /** + * @hidden + */ + private swap_deque(obj); + } + /** + * An iterator of {@link Deque}. + * + * @author Jeongho Nam + */ + class DequeIterator extends base.Iterator implements base.IArrayIterator { + private deque; + /** + * 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); + /** + * @inheritdoc + */ + value: T; + /** + *

Whether an iterator is equal with the iterator.

+ * + *

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

+ * + *

Note

+ *

Iterator's equal_to() only compare souce container and index number.

+ * + *

Although elements in a pair, key and value are equal_to, if the source map or + * index number is different, then the {@link equal_to equal_to()} 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. + */ + equal_to(obj: DequeIterator): boolean; + /** + * @inheritdoc + */ + index: number; + /** + * @inheritdoc + */ + prev(): DequeIterator; + /** + * @inheritdoc + */ + next(): DequeIterator; + /** + * @inheritdoc + */ + advance(n: number): DequeIterator; + /** + * @inheritdoc + */ + swap(obj: DequeIterator): void; + } + /** + *

A reverse-iterator of Deque.

+ * + * @param Type of the elements. + * + * @author Jeongho Nam + */ + class DequeReverseIterator extends base.ReverseIterator implements base.IArrayIterator { + constructor(iterator: DequeIterator); + /** + * @hidden + */ + private deque_iterator; + index: number; + value: T; + /** + * @inheritdoc + */ + prev(): DequeReverseIterator; + /** + * @inheritdoc + */ + next(): DequeReverseIterator; + /** + * @inheritdoc + */ + advance(n: number): DequeReverseIterator; + } +} +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.

+ * + *

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.
+ *
+ * + *
    + *
  • Reference: http://www.cplusplus.com/reference/list/list/ + *
+ * + * @param Type of the elements. + * + * @author Jeongho Nam + */ + class List extends base.Container implements base.IDeque { + /** + * An iterator of beginning. + */ + protected begin_: ListIterator; + /** + * An iterator of end. + */ + protected end_: ListIterator; + /** + * Number of elements in the {@link List}. + */ + protected size_: number; + /** + *

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: base.IContainer); + /** + *

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: base.Iterator, end: base.Iterator); + /** + * @inheritdoc + */ + assign(n: number, val: T): void; + /** + * @inheritdoc + */ + assign>(begin: InputIterator, end: InputIterator): void; + /** + * @inheritdoc + */ + clear(): void; + /** + * @inheritdoc + */ + begin(): ListIterator; + /** + * @inheritdoc + */ + end(): ListIterator; + /** + * @inheritdoc + */ + rbegin(): ListReverseIterator; + /** + * @inheritdoc + */ + rend(): ListReverseIterator; + /** + * @inheritdoc + */ + size(): number; + /** + * @inheritdoc + */ + front(): T; + /** + * @inheritdoc + */ + back(): T; + /** + * @inheritdoc + */ + push(...items: U[]): number; + /** + * @inheritdoc + */ + push_front(val: T): void; + /** + * @inheritdoc + */ + push_back(val: T): void; + /** + * @inheritdoc + */ + pop_front(): void; + /** + * @inheritdoc + */ + pop_back(): void; + /** + *

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.

+ * + * @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; + /** + * + * @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; + /** + * @hidden + */ + private insert_by_val(position, val); + /** + * @hidden + */ + private insertByRepeatingVal(position, size, val); + /** + * @hidden + */ + private insert_by_range(position, begin, end); + /** + *

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; + /** + * @hidden + */ + private erase_by_iterator(it); + /** + * @hidden + */ + private erase_by_range(begin, end); + /** + *

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; + /** + * @inheritdoc + */ + swap(obj: base.IContainer): void; + /** + * @hidden + */ + private swap_list(obj); + } + /** + * An iterator, node of a List. + */ + class ListIterator extends base.Iterator { + protected prev_: ListIterator; + protected next_: ListIterator; + protected value_: T; + /** + *

Construct from the source {@link List container}.

+ * + *

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 + */ + setPrev(prev: ListIterator): void; + /** + * @inheritdoc + */ + setNext(next: ListIterator): void; + /** + * @inheritdoc + */ + equal_to(obj: ListIterator): boolean; + /** + * @inheritdoc + */ + prev(): ListIterator; + /** + * @inheritdoc + */ + next(): ListIterator; + /** + * @inheritdoc + */ + advance(step: number): ListIterator; + /** + * @inheritdoc + */ + value: T; + /** + * @inheritdoc + */ + swap(obj: ListIterator): void; + } + /** + *

A reverse-iterator of List.

+ * + * @param Type of the elements. + * + * @author Jeongho Nam + */ + class ListReverseIterator extends base.ReverseIterator { + constructor(iterator: ListIterator); + /** + * @hidden + */ + private list_iterator; + value: T; + /** + * @inheritdoc + */ + prev(): ListReverseIterator; + /** + * @inheritdoc + */ + next(): ListReverseIterator; + /** + * @inheritdoc + */ + advance(n: number): ListReverseIterator; + } +} +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.

+ * + *
    + *
  • Reference: http://www.cplusplus.com/reference/queue/queue/
  • + *
+ * + * @param Type of elements. + * + * @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; + } + /** + *

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.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: base.Iterator, end: base.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: base.Iterator, end: base.Iterator, compare: (left: T, right: T) => boolean); + /** + * @hidden + */ + protected construct_from_array(items: Array): void; + /** + * @hidden + */ + protected construct_from_container(container: base.IContainer): void; + /** + * @hidden + */ + protected construct_from_range(begin: base.Iterator, end: base.Iterator): void; + /** + *

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.

+ * + *
    + *
  • Reference: http://www.cplusplus.com/reference/stack/stack/
  • + *
+ * + * @param Type of elements. + * + * @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.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 + *
+ * + *
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 { + /** + * Type definition of {@link SetContainer}'s {@link SetIterator iterator}. + */ + static iterator: typeof SetIterator; + /** + *

{@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}.

+ */ + protected data_: List; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from elements. + */ + constructor(items: Array); + /** + * Copy Constructor. + */ + constructor(container: IContainer); + /** + * Construct from range iterators. + */ + constructor(begin: Iterator, end: Iterator); + /** + * @hidden + */ + protected construct_from_array(items: Array): void; + /** + * @hidden + */ + protected construct_from_container(container: Container): void; + /** + * @hidden + */ + protected construct_from_range(begin: Iterator, end: Iterator): void; + /** + * @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: U[]): 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 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 insert_by_hint(hint: SetIterator, val: T): SetIterator; + /** + * @hidden + */ + protected 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; + /** + * @hidden + */ + private erase_by_val(val); + /** + * @hidden + */ + private erase_by_iterator(it); + /** + * @hidden + */ + private erase_by_range(begin, end); + /** + *

Abstract method handling insertion for indexing.

+ * + *

This method, {@link handle_insert} is designed to register the item to somewhere storing those + * {@link SetIterator iterators} for indexing, fast accessment and retrievalance.

+ * + *

When {@link insert} is called, a new element will be inserted into the {@link data_ list container} + * and a new {@link SetIterator iterator} item, pointing the element, will be created and the newly + * created iterator item will be shifted into this method {@link handle_insert} after the insertion.

+ * + *

If the derived one is {@link RBTree tree-based} like {@link TreeSet}, the item 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 item will be registered into the + * {@link HashSet.hash_buckets_ hash bucket}.

+ * + * @param item Iterator of inserted item. + */ + protected abstract handle_insert(item: SetIterator): void; + /** + *

Abstract method handling deletion for indexing.

+ * + *

This method, {@link handle_insert} is designed to unregister the item to somewhere storing + * those {@link SetIterator iterators} for indexing, fast accessment and retrievalance.

+ * + *

When {@link erase} is called with item, an {@link SetIterator iterator} 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 item 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 item will be unregistered + * from the {@link HashSet.hash_buckets_ hash bucket}.

+ * + * @param item Iterator of erased item. + */ + protected abstract handle_erase(item: SetIterator): void; + } +} +declare namespace std { + /** + *

An iterator of a Set.

+ * + * @author Jeongho Nam + */ + class SetIterator extends base.Iterator implements IComparable> { + private list_iterator_; + /** + *

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.SetContainer, it: ListIterator); + /** + * @inheritdoc + */ + prev(): SetIterator; + /** + * @inheritdoc + */ + next(): SetIterator; + /** + * @inheritdoc + */ + advance(size: number): SetIterator; + /** + * @hidden + */ + private set; + get_list_iterator(): ListIterator; + /** + * @inheritdoc + */ + value: T; + /** + * @inheritdoc + */ + equal_to(obj: SetIterator): boolean; + /** + * @inheritdoc + */ + less(obj: SetIterator): boolean; + /** + * @inheritdoc + */ + hash(): number; + /** + * @inheritdoc + */ + swap(obj: SetIterator): void; + } + /** + *

A reverse-iterator of Set.

+ * + * @param Type of the elements. + * + * @author Jeongho Nam + */ + class SetReverseIterator extends base.ReverseIterator { + constructor(iterator: SetIterator); + /** + * @hidden + */ + private set_iterator; + /** + * @inheritdoc + */ + prev(): SetReverseIterator; + /** + * @inheritdoc + */ + next(): SetReverseIterator; + /** + * @inheritdoc + */ + advance(n: number): 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 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 + *
+ * + *
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 { + /** + * Default Constructor. + */ + constructor(); + /** + * @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>(begin: InputIterator, end: InputIterator): 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 + *
+ * + *
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 { + /** + * Default Constructor. + */ + constructor(); + /** + * @inheritdoc + */ + count(val: T): number; + /** + *

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>(begin: InputIterator, end: InputIterator): void; + } +} +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
+ * + *
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.
+ *
+ * + *
    + *
  • Reference: http://www.cplusplus.com/reference/unordered_set/unordered_set/
  • + *
+ * + * @param Type of the elements. + * Each element in an {@link HashSet} is also uniquely identified by this value. + * + * @author Jeongho Nam + */ + class HashSet extends base.UniqueSet { + private hash_buckets_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from elements. + */ + constructor(items: Array); + /** + * Copy Constructor. + */ + constructor(container: base.IContainer); + /** + * Construct from range iterators. + */ + constructor(begin: base.Iterator, end: base.Iterator); + /** + * @hidden + */ + protected construct_from_array(items: Array): void; + /** + * @inheritdoc + */ + assign>(begin: InputIterator, end: InputIterator): void; + /** + * @inheritdoc + */ + clear(): void; + /** + * @inheritdoc + */ + find(val: T): SetIterator; + /** + * @hidden + */ + protected insert_by_val(val: T): any; + /** + * @hidden + */ + protected insert_by_range>(begin: InputIterator, end: InputIterator): void; + /** + * @inheritdoc + */ + protected handle_insert(item: SetIterator): void; + /** + * @inheritdoc + */ + protected handle_erase(item: SetIterator): void; + /** + * @inheritdoc + */ + swap(obj: base.IContainer): void; + /** + * @hidden + */ + private swap_tree_set(obj); + } + /** + *

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 HashSet} 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
+ * + *
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.
+ *
+ * + *
    + *
  • Reference: http://www.cplusplus.com/reference/unordered_set/unordered_multiset/
  • + *
+ * + * @param Type of the elements. + * Each element in an {@link UnorderedMultiSet} is also identified by this value.. + * + * @author Jeongho Nam + */ + class HashMultiSet extends base.MultiSet { + private hash_buckets_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from elements. + */ + constructor(items: Array); + /** + * Copy Constructor. + */ + constructor(container: base.IContainer); + /** + * Construct from range iterators. + */ + constructor(begin: base.Iterator, end: base.Iterator); + /** + * @hidden + */ + protected construct_from_array(items: Array): void; + /** + * @inheritdoc + */ + assign>(begin: InputIterator, end: InputIterator): void; + /** + * @inheritdoc + */ + clear(): void; + /** + * @inheritdoc + */ + find(val: T): SetIterator; + /** + * @hidden + */ + protected insert_by_val(val: T): any; + /** + * @hidden + */ + protected insert_by_range>(begin: InputIterator, end: InputIterator): void; + /** + * @inheritdoc + */ + protected handle_insert(it: SetIterator): void; + /** + * @inheritdoc + */ + protected handle_erase(it: SetIterator): void; + /** + * @inheritdoc + */ + swap(obj: base.IContainer): void; + /** + * @hidden + */ + private swap_tree_set(obj); + } +} +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 + *
+ * + *
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 { + /** + * Type definition of {@link MapContainer}'s {@link MapIterator iterator}. + */ + static iterator: typeof MapIterator; + /** + *

{@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}.

+ */ + protected data_: List>; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from elements. + */ + constructor(items: Array>); + /** + * Contruct from tuples. + * + * @param array Tuples to be contained. + */ + constructor(array: Array<[Key, T]>); + /** + * Copy Constructor. + */ + constructor(container: MapContainer); + /** + * Construct from range iterators. + */ + constructor(begin: MapIterator, end: MapIterator); + /** + * @hidden + */ + protected construct_from_array(items: Array | [Key, T]>): void; + /** + * @hidden + */ + protected construct_from_container(container: MapContainer): void; + /** + * @hidden + */ + protected construct_from_range(begin: MapIterator, end: MapIterator): void; + /** + *

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: MapIterator, end: MapIterator): void; + /** + *

Clear content.

+ * + *

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

+ */ + 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

+ * + *

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

+ * + * @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; + /** + * Test whether the container is empty. + */ + empty(): boolean; + /** + *

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 {@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, pair: Pair): 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: MapIterator, tuple: [L, U]): MapIterator; + /** + *

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(begin: MapIterator, end: MapIterator): void; + /** + * @hidden + */ + protected abstract insert_by_pair(pair: Pair): any; + /** + * @hidden + */ + private insert_by_tuple(tuple); + /** + * @hidden + */ + protected insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; + /** + * @hidden + */ + private insert_by_hint_with_tuple(hint, tuple); + /** + * @hidden + */ + protected insert_by_range(begin: MapIterator, end: MapIterator): 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; + /** + * @hidden + */ + private erase_by_key(key); + /** + * @hidden + */ + private erase_by_iterator(it); + /** + * @hidden + */ + private erase_by_range(begin, end); + /** + *

Abstract method handling insertion for indexing.

+ * + *

This method, {@link handle_insert} is designed to register the item to somewhere storing those + * {@link MapIterator iterators} for indexing, fast accessment and retrievalance.

+ * + *

When {@link insert} is called, a new element will be inserted into the {@link data_ list container} + * and a new {@link MapIterator iterator} item, pointing the element, will be created and the newly + * created iterator item will be shifted into this method {@link handle_insert} after the insertion.

+ * + *

If the derived one is {@link RBTree tree-based} like {@link TreeMap}, the item will be + * registered into the {@link TreeMap.tree_ tree} as a {@link XTreeNode tree node item}. Else if the derived + * one is {@link HashBuckets hash-based} like {@link HashSet}, the item will be registered into the + * {@link HashMap.hash_buckets_ hash bucket}.

+ * + * @param item Iterator of inserted item. + */ + protected abstract handle_insert(item: MapIterator): void; + /** + *

Abstract method handling deletion for indexing.

+ * + *

This method, {@link handle_insert} is designed to unregister the item to somewhere storing + * those {@link MapIterator iterators} for indexing, fast accessment and retrievalance.

+ * + *

When {@link erase} is called with item, an {@link MapIterator iterator} 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 TreeMap}, the item will be + * unregistered from the {@link TreeMap.tree_ tree} as a {@link XTreeNode tree node item}. Else if the + * derived one is {@link HashBuckets hash-based} like {@link HashSet}, the item will be unregistered + * from the {@link HashMap.hash_buckets_ hash bucket}.

+ * + * @param item Iterator of erased item. + */ + protected abstract handle_erase(item: MapIterator): void; + /** + *

Swap content.

+ * + *

Exchanges the content of the container by the content of obj, which is another + * {@link MapContainer 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 MapContainer 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 MapContaier container}. + */ + swap(obj: MapContainer): void; + } +} +declare namespace std { + /** + * An iterator of {@link MapColntainer map container}. + * + * @author Jeongho Nam + */ + class MapIterator implements IComparable> { + /** + * The source {@link MapContainer} of the iterator is directing for. + */ + protected source_: base.MapContainer; + /** + * A {@link ListIterator} pointing {@link Pair} of key and value. + */ + protected list_iterator_: ListIterator>; + /** + * 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.MapContainer, list_iterator: ListIterator>); + /** + * 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; + /** + * Get source. + */ + get_source(): base.MapContainer; + /** + * Get ListIterator. + */ + get_list_iterator(): ListIterator>; + /** + * Get first, key element. + */ + first: Key; + /** + * Get second, value element. + */ + /** + * Set second value. + */ + second: T; + /** + *

Whether an iterator is equal with the iterator.

+ * + *

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

+ * + * @param obj An iterator to compare + * @return Indicates whether equal or not. + */ + equal_to(obj: MapIterator): boolean; + less(obj: MapIterator): boolean; + hash(): number; + swap(obj: MapIterator): void; + } +} +declare namespace std { + /** + * A reverse-iterator of {@link MapColntainer map container}. + * + * @author Jeongho Nam + */ + class MapReverseIterator extends MapIterator { + /** + * 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.MapContainer, list_iterator: ListIterator>); + /** + * @inheritdoc + */ + prev(): MapReverseIterator; + /** + * @inheritdoc + */ + next(): MapReverseIterator; + /** + * @inheritdoc + */ + advance(step: number): MapReverseIterator; + } +} +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 + *
+ * + *
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 { + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from elements. + */ + constructor(items: Array>); + /** + * Contruct from tuples. + * + * @param array Tuples to be contained. + */ + constructor(array: Array<[Key, T]>); + /** + * Copy Constructor. + */ + constructor(container: MapContainer); + /** + * Construct from range iterators. + */ + constructor(begin: MapIterator, end: MapIterator); + /** + * @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; + /** + *

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 {@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(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: MapIterator, tuple: [L, U]): MapIterator; + /** + * @inheritdoc + */ + insert(begin: MapIterator, end: MapIterator): void; + } +} +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 + *
+ * + *
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 { + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from elements. + */ + constructor(items: Array>); + /** + * Contruct from tuples. + * + * @param array Tuples to be contained. + */ + constructor(array: Array<[Key, T]>); + /** + * Copy Constructor. + */ + constructor(container: MapContainer); + /** + * Construct from range iterators. + */ + constructor(begin: MapIterator, end: MapIterator); + /** + * @inheritdoc + */ + count(key: Key): number; + /** + *

Insert elements.

+ * + *

Extends the container by inserting new elements, effectively increasing the container {@link size} by + * the number of elements inserted.

+ * + * @param pair {@link Pair} to be inserted as an element. + * + * @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: MapIterator, tuple: [L, U]): MapIterator; + /** + * @inheritdoc + */ + insert(begin: MapIterator, end: MapIterator): void; + } +} +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
+ * + *
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.
+ *
+ * + *
    + *
  • Reference: http://www.cplusplus.com/reference/unordered_map/unordered_map/
  • + *
+ * + * @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. + * + * @author Jeongho Nam + */ + class HashMap extends base.UniqueMap { + private hash_buckets_; + /** + * Default Constructor. + */ + constructor(); + /** + * Contruct from elements. + * + * @param array Elements to be contained. + */ + constructor(array: Array>); + /** + * Contruct from tuples. + * + * @param array Tuples to be contained. + */ + constructor(array: Array<[Key, T]>); + /** + * Copy Constructor. + * + * @param container Another map to copy. + */ + constructor(container: base.MapContainer); + /** + * 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: MapIterator, end: MapIterator); + /** + * @hidden + */ + protected construct_from_array(items: Array>): void; + /** + * @inheritdoc + */ + assign(begin: MapIterator, end: MapIterator): void; + /** + * @inheritdoc + */ + clear(): void; + /** + * @inheritdoc + */ + find(key: Key): MapIterator; + /** + * @hidden + */ + protected insert_by_pair(pair: Pair): any; + /** + * @hidden + */ + protected insert_by_range(begin: MapIterator, end: MapIterator): void; + /** + * @inheritdoc + */ + protected handle_insert(it: MapIterator): void; + /** + * @inheritdoc + */ + protected handle_erase(it: MapIterator): void; + /** + * @inheritdoc + */ + swap(obj: base.MapContainer): void; + /** + * @hidden + */ + private swap_hash_map(obj); + } + /** + *

Hashed, unordered Multimap.

+ * + *

{@link HashMap}s are associative containers that store elements formed by the combination of + * a key value and a mapped value, much like {@link HashMap} containers, but allowing + * different elements to have equivalent 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).

+ * + *

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
+ * + *
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.
+ *
+ * + *
    + *
  • Reference: http://www.cplusplus.com/reference/unordered_map/unordered_multimap/
  • + *
+ * + * @param Type of the key values. + * Each element in an {@link HashMap} is identified by a key value. + * @param Type of the mapped value. + * Each element in an {@link HashMap} is used to store some data as its mapped value. + * + * @author Jeongho Nam + */ + class HashMultiMap extends base.MultiMap { + /** + * + */ + private hash_buckets_; + /** + * Default Constructor. + */ + constructor(); + /** + * Contruct from elements. + * + * @param array Elements to be contained. + */ + constructor(array: Array>); + /** + * Contruct from tuples. + * + * @param array Tuples to be contained. + */ + constructor(array: Array<[Key, T]>); + /** + * Copy Constructor. + * + * @param container Another map to copy. + */ + constructor(container: base.MapContainer); + /** + * 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: MapIterator, end: MapIterator); + /** + * @hidden + */ + protected construct_from_array(items: Array>): void; + /** + * @inheritdoc + */ + assign(begin: MapIterator, end: MapIterator): void; + /** + * @inheritdoc + */ + clear(): void; + /** + * @inheritdoc + */ + find(key: Key): MapIterator; + /** + * @hidden + */ + protected insert_by_pair(pair: Pair): any; + /** + * @hidden + */ + protected insert_by_range(begin: MapIterator, end: MapIterator): void; + /** + * @inheritdoc + */ + protected handle_insert(it: MapIterator): void; + /** + * @inheritdoc + */ + protected handle_erase(it: MapIterator): void; + /** + * @inheritdoc + */ + swap(obj: base.MapContainer): void; + /** + * @hidden + */ + private swap_hash_multimap(obj); + } +} +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

+ * + *

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 + *
+ * + *
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.
+ *
+ * + *
    + *
  • Reference: http://www.cplusplus.com/reference/set/set/
  • + *
+ * + * @param Type of the elements. + * Each element in an {@link TreeSet} is also uniquely identified by this value. + * + * @author Jeongho Nam + */ + class TreeSet extends base.UniqueSet { + /** + * RB-Tree+ object for implemeting the {@link TreeSet}. + */ + private tree_; + /** + * 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: base.Iterator, end: base.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: base.Iterator, end: base.Iterator, compare: (left: T, right: T) => boolean); + /** + * @inheritdoc + */ + assign>(begin: InputIterator, end: InputIterator): void; + /** + * @inheritdoc + */ + clear(): void; + /** + * @inheritdoc + */ + find(val: T): SetIterator; + /** + *

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 Set} 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 Set} contains an element equivalent to val: 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 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 Set.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 not 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(element, val) would return true.

+ * + *

If the {@link Set} class is instantiated with the default comparison type ({@link 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 {@link Set} contains an element equivalent to val: 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 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 Set.end} if all elements are considered to go after val. + */ + upper_bound(val: T): SetIterator; + /** + *

Get range of equal elements.

+ * + *

Because all elements in a {@link Set} container are unique, the range returned will contain a + * single element at most.

+ * + *

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 {@link Set} 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 val 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>; + /** + * @hidden + */ + protected insert_by_val(val: T): any; + /** + * @inheritdoc + */ + protected handle_insert(item: SetIterator): void; + /** + * @inheritdoc + */ + protected handle_erase(item: SetIterator): void; + /** + * @inheritdoc + */ + swap(obj: base.IContainer): void; + /** + * @hidden + */ + private swap_tree_set(obj); + } + /** + *

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

+ * + *

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 + *
+ * + *
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.
+ *
+ * + *
    + *
  • Reference: http://www.cplusplus.com/reference/set/multiset/
  • + *
+ * + * @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). + * + * @author Jeongho Nam + */ + class TreeMultiSet extends base.MultiSet { + /** + * RB-Tree+ object for implemeting the {@link TreeMultiSet}. + */ + private tree_; + /** + * 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: base.Iterator, end: base.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: base.Iterator, end: base.Iterator, compare: (left: T, right: T) => boolean); + /** + * @inheritdoc + */ + assign>(begin: InputIterator, end: InputIterator): void; + /** + * @inheritdoc + */ + clear(): void; + /** + * @inheritdoc + */ + find(val: T): SetIterator; + /** + *

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 TreeMultiSet} 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 TreeMultiSet} 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 TreeMultiSet.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 TreeMultiSet} 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 {@TreeMultiSet} 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 TreeMultiSet.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>; + /** + * @hidden + */ + protected insert_by_val(val: T): any; + /** + * @inheritdoc + */ + protected handle_insert(item: SetIterator): void; + /** + * @inheritdoc + */ + protected handle_erase(item: SetIterator): void; + /** + * @inheritdoc + */ + swap(obj: base.IContainer): void; + /** + * @hidden + */ + private swap_tree_set(obj); + } +} +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
+ * + *
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.
+ *
+ * + *
    + *
  • Reference: http://www.cplusplus.com/reference/map/map/
  • + *
+ * + * @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 + */ + class TreeMap extends base.UniqueMap { + /** + * RB-Tree+ object for implemeting the {@link TreeMap}. + */ + private tree_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from compare. + * + * @param compare A binary predicate determines order of elements. + */ + constructor(compare: (left: Key, right: 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: (left: Key, right: 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: (left: Key, right: Key) => boolean); + /** + * Copy Constructor. + * + * @param container Another map to copy. + */ + constructor(container: base.MapContainer); + /** + * Copy Constructor. + * + * @param container Another map to copy. + * @param compare A binary predicate determines order of elements. + */ + constructor(container: base.MapContainer, compare: (left: Key, right: 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: MapIterator, end: MapIterator); + /** + * 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: MapIterator, end: MapIterator, compare: (left: Key, right: Key) => boolean); + /** + * @inheritdoc + */ + assign(begin: MapIterator, end: MapIterator): void; + /** + * @inheritdoc + */ + clear(): void; + /** + * @inheritdoc + */ + find(key: Key): MapIterator; + /** + *

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 TreeMap} 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 TreeMap} 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 TreeMap.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 TreeMap} 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} 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

. + * + *

Because the elements in a {@link TreeMap} container have unique keys, the range returned will + * contain a single element at most.

+ * + *

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>; + /** + * @hidden + */ + protected insert_by_pair(pair: Pair): any; + /** + * @inheritdoc + */ + protected handle_insert(item: MapIterator): void; + /** + * @inheritdoc + */ + protected handle_erase(item: MapIterator): void; + /** + * @inheritdoc + */ + swap(obj: base.MapContainer): void; + /** + * @hidden + */ + private swap_tree_map(obj); + } + /** + *

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.

+ * + *

Container properties

+ *
+ *
Associative
+ *
+ * Elements in associative containers are referenced by their key and not by their absolute + * position in the + *
+ * + *
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.
+ *
+ * + *
    + *
  • Reference: http://www.cplusplus.com/reference/map/multimap/
  • + *
+ * + * @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 + */ + class TreeMultiMap extends base.MultiMap { + private tree_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from compare. + * + * @param compare A binary predicate determines order of elements. + */ + constructor(compare: (left: Key, right: 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: (left: Key, right: 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: (left: Key, right: Key) => boolean); + /** + * Copy Constructor. + * + * @param container Another map to copy. + */ + constructor(container: base.MapContainer); + /** + * Copy Constructor. + * + * @param container Another map to copy. + * @param compare A binary predicate determines order of elements. + */ + constructor(container: base.MapContainer, compare: (left: Key, right: 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: MapIterator, end: MapIterator); + /** + * 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: MapIterator, end: MapIterator, compare: (left: Key, right: Key) => boolean); + /** + * @inheritdoc + */ + assign(begin: MapIterator, end: MapIterator): void; + /** + * @inheritdoc + */ + clear(): void; + /** + * @inheritdoc + */ + find(key: Key): MapIterator; + /** + *

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 TreeMultiMap} 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 TreeMultiMap} contains an element with keys equivalent to k: + * 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 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 TreeMultiMap.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 TreeMultiMap} 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 {@link TreeMultiMap} contains an element with keys equivalent to k: + * In this case {@link lower_bound} returns an iterator pointing to first of such element, whereas + * {@link upper_bound} returns an iterator pointing to the element following the last.

+ * + * @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 TreeMultiMap.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>; + /** + * @hidden + */ + protected insert_by_pair(pair: Pair): any; + /** + * @inheritdoc + */ + protected handle_insert(item: MapIterator): void; + /** + * @inheritdoc + */ + protected handle_erase(item: MapIterator): void; + /** + * @inheritdoc + */ + swap(obj: base.MapContainer): void; + /** + * @hidden + */ + private swap_tree_multimap(obj); + } +} +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. + * + * @return Returns fn. + */ + function for_each, Func extends (val: T) => any>(first: Iterator, last: Iterator, fn: Func): Func; + /** + *

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: Iterator, last: Iterator, 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: Iterator, last: Iterator, 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: Iterator, last: Iterator, 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: Iterator1, last1: Iterator1, first2: base.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: Iterator1, last1: Iterator1, first2: base.Iterator, pred: (x: T, y: T) => boolean): 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). + * + * @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 base.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 base.Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, 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 base.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 base.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: Iterator, last: Iterator, val: T): Iterator; + /** + *

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: Iterator, last: Iterator, pred: (val: T) => boolean): Iterator; + /** + *

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: Iterator, last: Iterator, pred: (val: T) => boolean): Iterator; + /** + *

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 base.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 base.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 base.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 base.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: Iterator, last: Iterator): Iterator; + /** + *

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: Iterator, last: Iterator, pred: (x: T, y: T) => boolean): Iterator; + /** + *

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 base.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 base.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 base.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 base.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: Iterator, last: Iterator, 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: Iterator, last: Iterator, pred: (val: T) => boolean): number; + /** + *

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.Iterator>(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.Iterator>(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.Iterator>(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.Iterator>(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.Iterator>(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 base.Iterator, OutputIterator extends base.Iterator>(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: Iterator, last: Iterator): Iterator; + /** + *

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: Iterator, last: Iterator, pred: (left: t, right: t) => boolean): Iterator; + /** + *

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.Iterator>(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.Iterator>(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: Iterator, last: Iterator, val: T): Iterator; + /** + *

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: Iterator, last: Iterator, pred: (left: T) => boolean): Iterator; + /** + *

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.Iterator>(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.Iterator>(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: Iterator, last: Iterator, 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.Iterator>(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.Iterator>(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: base.Iterator, y: base.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 base.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: Iterator, last: Iterator): 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.Iterator>(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: Iterator, middle: Iterator, last: Iterator): Iterator; + /** + *

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.Iterator>(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; + /** + *

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. + * 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 + * first. {@link IArrayIterator RandomAccessIterator} shall point to a type for which + * {@link Iterator.swap swap} is properly defined. + * + * @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. + * 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 + * first. {@link IArrayIterator RandomAccessIterator} shall point to a type for which + * {@link Iterator.swap swap} is properly defined. + * + * @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 base.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 base.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; + /** + *

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; + /** + *

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.Iterator, OutputIterator2 extends base.Iterator>(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; + /** + *

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 base.Iterator, OutputIterator extends base.Iterator>(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 base.Iterator, OutputIterator extends base.Iterator>(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 base.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 base.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 base.Iterator, OutputIterator extends base.Iterator>(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 base.Iterator, OutputIterator extends base.Iterator>(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 base.Iterator, OutputIterator extends base.Iterator>(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 base.Iterator, OutputIterator extends base.Iterator>(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 base.Iterator, OutputIterator extends base.Iterator>(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 base.Iterator, OutputIterator extends base.Iterator>(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 base.Iterator, OutputIterator extends base.Iterator>(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 base.Iterator, OutputIterator extends base.Iterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator, compare: (x: T, y: T) => boolean): OutputIterator; + /** + *

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; +} +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; + /** + *

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. + */ + equal_to(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. + */ + hash(): number; + } + /** + * Default hash function. + * + * @param obj + */ + function hash(obj: any): 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; + /** + *

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 std.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 = 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 + */ + namespace 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 { + /** + *

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: Iterator, last: Iterator): number; +} +declare namespace std { + /** + *

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 { + /** + * A message representing specification about the Exception. + */ + protected message: string; + /** + * Default Constructor. + */ + constructor(); + /** + *

Construct from a message.

+ * + * @param message A message representing specification about the Exception. + */ + constructor(what: 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(what: 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(what: 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(what: 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(what: 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(what: 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(what: 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/outflow_error/ + *
+ * + * @author Jeongho Nam + */ + class OverflowError extends RuntimeError { + /** + *

Construct from a message.

+ * + * @param message A message representing specification about the Exception. + */ + constructor(what: 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(what: 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(what: string); + } +} +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 + */ + class ErrorInstance { + /** + * A reference to an {@link ErrorCategory} object. + */ + protected category_: ErrorCategory; + /** + * A numerical value identifying an error instance. + */ + 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 { + /** + *

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 { + /** + * Error code. + */ + 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; + } + /** + *

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; + } + /** + *

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); + } + /** + *

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 { + /** + *

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}.

+ * + *
    + *
  • Reference: http://www.cplusplus.com/reference/utility/pair/
  • + *
+ * + * @param Type of member {@link first}. + * @param Type of member {@link second}. + * + * @author Jeongho Nam + */ + class Pair { + /** + *

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. + */ + equal_to(pair: Pair): boolean; + 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.example { + function test_all(): 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.

+ * + *
    + *
  • Reference: https://en.wikipedia.org/w/index.php?title=Red%E2%80%93black_tree&redirect=no
  • + *
+ * + * @param Type of elements. + * + * @inventor Rudolf Bayer + * @author Migrated by Jeongho Nam + */ + abstract class XTree { + /** + * Root node. + */ + protected root_: XTreeNode; + /** + * Default Constructor. + */ + constructor(); + /** + * 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_equals(left: T, right: T): boolean; + abstract is_less(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 { + /** + * @author Jeongho Nam + */ + class AtomicTree extends XTree> { + private compare_; + /** + * Default Constructor. + */ + constructor(compare?: (left: T, right: T) => boolean); + find(val: T): XTreeNode>; + find(it: SetIterator): XTreeNode>; + /** + * @hidden + */ + private find_by_val(val); + get_compare(): (left: T, right: T) => boolean; + /** + * @inheritdoc + */ + is_equals(left: SetIterator, right: SetIterator): boolean; + /** + * @inheritdoc + */ + is_less(left: SetIterator, right: SetIterator): 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 { + const MIN_SIZE: number; + const RATIO: number; + const MAX_RATIO: number; + function code(par: any): number; +} +declare namespace std.base { + /** + *

Hask buckets.

+ * + * @author Jeongho Nam + */ + class HashBuckets { + private buckets_; + private item_size_; + /** + * Default Constructor. + */ + constructor(); + /** + * Reserve the bucket size. + * + * @param size Number of bucket size to reserve. + */ + reserve(size: number): void; + clear(): void; + size(): number; + item_size(): number; + at(index: number): Vector; + private hash_index(val); + insert(val: T): void; + erase(val: T): void; + } +} +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 IArray 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; + } +} +declare namespace std.base { + /** + *

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 Iterator { + /** + * 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

+ * + *

{@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

+ * + *

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(): ReverseIterator; + /** + *

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(): ReverseIterator; + /** + * 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: U[]): 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; + } +} +declare namespace std.base { + /** + *

An interface for deque

+ * + * @author Jeongho Nam + */ + interface IDeque 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 { + /** + *

Linear

+ * + * @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; + } +} +declare namespace std.base { + class MapHashBuckets extends HashBuckets> { + private map; + constructor(map: MapContainer); + find(key: K): MapIterator; + } +} +declare namespace std.base { + /** + * @author Jeongho Nam + */ + class PairTree extends XTree> { + private compare_; + /** + * Default Constructor. + */ + constructor(compare?: (left: Key, right: Key) => boolean); + find(key: Key): XTreeNode>; + find(it: MapIterator): XTreeNode>; + /** + * @hidden + */ + private find_by_key(key); + get_compare(): (left: Key, right: Key) => boolean; + /** + * @inheritdoc + */ + is_equals(left: MapIterator, right: MapIterator): boolean; + /** + * @inheritdoc + */ + is_less(left: MapIterator, right: MapIterator): boolean; + } +} +declare namespace std.base { + class SetHashBuckets extends HashBuckets> { + private set; + constructor(set: SetContainer); + find(val: T): SetIterator; + } +} +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. + */ + grand_parent: XTreeNode; + /** + * Get sibling, opposite side node in same parent. + */ + sibling: XTreeNode; + /** + * Get uncle, parent's sibling. + */ + uncle: XTreeNode; + } +} +/** +* STL (Standard Template Library) Containers for TypeScript. +* +* @author Jeongho Nam +*/ +declare namespace std { +} +/** + * Base classes composing STL in background. + * + * @author Jeongho Nam + */ +declare namespace std.base { +} +/** + * Examples for supporting developers who use STL library. + * + * @author Jeongho Nam + */ +declare namespace std.example { +} +declare namespace std.example { + function test_bind(): void; +} +declare namespace std.example { + function test_deque(): void; +} +declare namespace std.example { + function test_for_each(): void; +} +declare namespace std.example { + function test_hash_map(): void; +} +declare namespace std.example { + function test_list(): void; +} +declare namespace std.example { + function sorting(): void; +} +declare namespace std.example { + function tree_set(): void; +} From 25fe7e572ec37b11b5af0c60b04070c9dd9d2c43 Mon Sep 17 00:00:00 2001 From: Alexandre Roba Date: Sat, 14 May 2016 17:58:12 +0200 Subject: [PATCH 050/402] Feature/swagger express middleware (#9281) * Added the definition for the swagger open api definition * Added the documentation part that describe how to use the definition * Added the comments * Renamed the test files to follow naming convention * Corrected the header to comply with the naming convention * Merged all the files into a single file --- .../swagger-express-middleware-tests.ts | 996 ++++++++++++++++++ .../swagger-express-middleware.d.ts | 592 +++++++++++ 2 files changed, 1588 insertions(+) create mode 100644 swagger-express-middleware/swagger-express-middleware-tests.ts create mode 100644 swagger-express-middleware/swagger-express-middleware.d.ts diff --git a/swagger-express-middleware/swagger-express-middleware-tests.ts b/swagger-express-middleware/swagger-express-middleware-tests.ts new file mode 100644 index 0000000000..2af3ab4d0c --- /dev/null +++ b/swagger-express-middleware/swagger-express-middleware-tests.ts @@ -0,0 +1,996 @@ +/// + +import * as express from "express"; +import * as SwaggerExpressMiddleware from "swagger-express-middleware"; + +let app = express(); +let router = express.Router(); + +SwaggerExpressMiddleware("PetStore.yaml", app, (err: any, middleware: SwaggerExpressMiddleware.SwaggerMiddleware) => { + let filesOptions: SwaggerExpressMiddleware.FilesOptions = { + useBasePath: false, + apiPath: "/api-docs/", + rawFilesPath: "/api-docs/" + }; + + let parseRequestOptions: SwaggerExpressMiddleware.ParseRequestOptions = { + cookie: { secret: undefined }, + json: { + limit: '1mb' + }, + text: { + limit: '1mb', + type: 'text/*' + }, + urlencoded:{ + extended:true + }, + raw:{ + inflate:false, + limit:100 + } + + } + + app.use( + middleware.metadata(router), + middleware.CORS(), + middleware.files(router, filesOptions), + middleware.parseRequest(parseRequestOptions), + middleware.validateRequest(), + middleware.mock(router) + ); +}); + +app.listen(8000, function () { + console.log('The PetStore sample is now running at http://localhost:8000'); +}); + +let petStoreMinimal: SwaggerExpressMiddleware.SwaggerObject = + { + "swagger": "2.0", + "info": { + "version": "1.0.0", + "title": "Swagger Petstore", + "description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", + "termsOfService": "http://swagger.io/terms/", + "contact": { + "name": "Swagger API Team" + }, + "license": { + "name": "MIT" + } + }, + "host": "petstore.swagger.io", + "basePath": "/api", + "schemes": [ + "http" + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "paths": { + "/pets": { + "get": { + "description": "Returns all pets from the system that the user has access to", + "produces": [ + "application/json" + ], + "responses": { + "200": { + "description": "A list of pets.", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Pet" + } + } + } + } + } + } + }, + "definitions": { + "Pet": { + "type": "object", + "required": [ + "id", + "name" + ], + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + }, + "tag": { + "type": "string" + } + } + } + } + }; + +let petstoreExpandedApiDefinition: SwaggerExpressMiddleware.SwaggerObject = { + "swagger": "2.0", + "info": { + "version": "1.0.0", + "title": "Swagger Petstore", + "description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", + "termsOfService": "http://swagger.io/terms/", + "contact": { + "name": "Swagger API Team", + "email": "foo@example.com", + "url": "http://madskristensen.net" + }, + "license": { + "name": "MIT", + "url": "http://github.com/gruntjs/grunt/blob/master/LICENSE-MIT" + } + }, + "host": "petstore.swagger.io", + "basePath": "/api", + "schemes": [ + "http" + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "paths": { + "/pets": { + "get": { + "description": "Returns all pets from the system that the user has access to\nNam sed condimentum est. Maecenas tempor sagittis sapien, nec rhoncus sem sagittis sit amet. Aenean at gravida augue, ac iaculis sem. Curabitur odio lorem, ornare eget elementum nec, cursus id lectus. Duis mi turpis, pulvinar ac eros ac, tincidunt varius justo. In hac habitasse platea dictumst. Integer at adipiscing ante, a sagittis ligula. Aenean pharetra tempor ante molestie imperdiet. Vivamus id aliquam diam. Cras quis velit non tortor eleifend sagittis. Praesent at enim pharetra urna volutpat venenatis eget eget mauris. In eleifend fermentum facilisis. Praesent enim enim, gravida ac sodales sed, placerat id erat. Suspendisse lacus dolor, consectetur non augue vel, vehicula interdum libero. Morbi euismod sagittis libero sed lacinia.\n\nSed tempus felis lobortis leo pulvinar rutrum. Nam mattis velit nisl, eu condimentum ligula luctus nec. Phasellus semper velit eget aliquet faucibus. In a mattis elit. Phasellus vel urna viverra, condimentum lorem id, rhoncus nibh. Ut pellentesque posuere elementum. Sed a varius odio. Morbi rhoncus ligula libero, vel eleifend nunc tristique vitae. Fusce et sem dui. Aenean nec scelerisque tortor. Fusce malesuada accumsan magna vel tempus. Quisque mollis felis eu dolor tristique, sit amet auctor felis gravida. Sed libero lorem, molestie sed nisl in, accumsan tempor nisi. Fusce sollicitudin massa ut lacinia mattis. Sed vel eleifend lorem. Pellentesque vitae felis pretium, pulvinar elit eu, euismod sapien.\n", + "operationId": "findPets", + "parameters": [ + { + "name": "tags", + "in": "query", + "description": "tags to filter by", + "required": false, + "type": "array", + "collectionFormat": "csv", + "items": { + "type": "string" + } + }, + { + "name": "limit", + "in": "query", + "description": "maximum number of results to return", + "required": false, + "type": "integer", + "format": "int32" + } + ], + "responses": { + "200": { + "description": "pet response", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Pet" + } + } + }, + "default": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + }, + "post": { + "description": "Creates a new pet in the store. Duplicates are allowed", + "operationId": "addPet", + "parameters": [ + { + "name": "pet", + "in": "body", + "description": "Pet to add to the store", + "required": true, + "schema": { + "$ref": "#/definitions/NewPet" + } + } + ], + "responses": { + "200": { + "description": "pet response", + "schema": { + "$ref": "#/definitions/Pet" + } + }, + "default": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + } + }, + "/pets/{id}": { + "get": { + "description": "Returns a user based on a single ID, if the user does not have access to the pet", + "operationId": "find pet by id", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "ID of pet to fetch", + "required": true, + "type": "integer", + "format": "int64" + } + ], + "responses": { + "200": { + "description": "pet response", + "schema": { + "$ref": "#/definitions/Pet" + } + }, + "default": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + }, + "delete": { + "description": "deletes a single pet based on the ID supplied", + "operationId": "deletePet", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "ID of pet to delete", + "required": true, + "type": "integer", + "format": "int64" + } + ], + "responses": { + "204": { + "description": "pet deleted" + }, + "default": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + } + } + }, + "definitions": { + "Pet": { + "type": "object", + "allOf": [ + { + "$ref": "#/definitions/NewPet" + }, + { + "required": [ + "id" + ], + "properties": { + "id": { + "type": "integer", + "format": "int64" + } + } + } + ] + }, + "NewPet": { + "type": "object", + "required": [ + "name" + ], + "properties": { + "name": { + "type": "string" + }, + "tag": { + "type": "string" + } + } + }, + "Error": { + "type": "object", + "required": [ + "code", + "message" + ], + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + } + } + } + } +}; + +let apiWithExamples: SwaggerExpressMiddleware.SwaggerObject = + { + "swagger": "2.0", + "info": { + "title": "Simple API overview", + "version": "v2" + }, + "paths": { + "/": { + "get": { + "operationId": "listVersionsv2", + "summary": "List API versions", + "produces": [ + "application/json" + ], + "responses": { + "200": { + "description": "200 300 response", + "examples": { + "application/json": "{\n \"versions\": [\n {\n \"status\": \"CURRENT\",\n \"updated\": \"2011-01-21T11:33:21Z\",\n \"id\": \"v2.0\",\n \"links\": [\n {\n \"href\": \"http://127.0.0.1:8774/v2/\",\n \"rel\": \"self\"\n }\n ]\n },\n {\n \"status\": \"EXPERIMENTAL\",\n \"updated\": \"2013-07-23T11:33:21Z\",\n \"id\": \"v3.0\",\n \"links\": [\n {\n \"href\": \"http://127.0.0.1:8774/v3/\",\n \"rel\": \"self\"\n }\n ]\n }\n ]\n}" + } + }, + "300": { + "description": "200 300 response", + "examples": { + "application/json": "{\n \"versions\": [\n {\n \"status\": \"CURRENT\",\n \"updated\": \"2011-01-21T11:33:21Z\",\n \"id\": \"v2.0\",\n \"links\": [\n {\n \"href\": \"http://127.0.0.1:8774/v2/\",\n \"rel\": \"self\"\n }\n ]\n },\n {\n \"status\": \"EXPERIMENTAL\",\n \"updated\": \"2013-07-23T11:33:21Z\",\n \"id\": \"v3.0\",\n \"links\": [\n {\n \"href\": \"http://127.0.0.1:8774/v3/\",\n \"rel\": \"self\"\n }\n ]\n }\n ]\n}" + } + } + } + } + }, + "/v2": { + "get": { + "operationId": "getVersionDetailsv2", + "summary": "Show API version details", + "produces": [ + "application/json" + ], + "responses": { + "200": { + "description": "200 203 response", + "examples": { + "application/json": "{\n \"version\": {\n \"status\": \"CURRENT\",\n \"updated\": \"2011-01-21T11:33:21Z\",\n \"media-types\": [\n {\n \"base\": \"application/xml\",\n \"type\": \"application/vnd.openstack.compute+xml;version=2\"\n },\n {\n \"base\": \"application/json\",\n \"type\": \"application/vnd.openstack.compute+json;version=2\"\n }\n ],\n \"id\": \"v2.0\",\n \"links\": [\n {\n \"href\": \"http://127.0.0.1:8774/v2/\",\n \"rel\": \"self\"\n },\n {\n \"href\": \"http://docs.openstack.org/api/openstack-compute/2/os-compute-devguide-2.pdf\",\n \"type\": \"application/pdf\",\n \"rel\": \"describedby\"\n },\n {\n \"href\": \"http://docs.openstack.org/api/openstack-compute/2/wadl/os-compute-2.wadl\",\n \"type\": \"application/vnd.sun.wadl+xml\",\n \"rel\": \"describedby\"\n },\n {\n \"href\": \"http://docs.openstack.org/api/openstack-compute/2/wadl/os-compute-2.wadl\",\n \"type\": \"application/vnd.sun.wadl+xml\",\n \"rel\": \"describedby\"\n }\n ]\n }\n}" + } + }, + "203": { + "description": "200 203 response", + "examples": { + "application/json": "{\n \"version\": {\n \"status\": \"CURRENT\",\n \"updated\": \"2011-01-21T11:33:21Z\",\n \"media-types\": [\n {\n \"base\": \"application/xml\",\n \"type\": \"application/vnd.openstack.compute+xml;version=2\"\n },\n {\n \"base\": \"application/json\",\n \"type\": \"application/vnd.openstack.compute+json;version=2\"\n }\n ],\n \"id\": \"v2.0\",\n \"links\": [\n {\n \"href\": \"http://23.253.228.211:8774/v2/\",\n \"rel\": \"self\"\n },\n {\n \"href\": \"http://docs.openstack.org/api/openstack-compute/2/os-compute-devguide-2.pdf\",\n \"type\": \"application/pdf\",\n \"rel\": \"describedby\"\n },\n {\n \"href\": \"http://docs.openstack.org/api/openstack-compute/2/wadl/os-compute-2.wadl\",\n \"type\": \"application/vnd.sun.wadl+xml\",\n \"rel\": \"describedby\"\n }\n ]\n }\n}" + } + } + } + } + } + }, + "consumes": [ + "application/json" + ] + }; + +let petStoreWithExternalDocs: SwaggerExpressMiddleware.SwaggerObject = + { + "swagger": "2.0", + "info": { + "version": "1.0.0", + "title": "Swagger Petstore", + "description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", + "termsOfService": "http://swagger.io/terms/", + "contact": { + "name": "Swagger API Team", + "email": "apiteam@swagger.io", + "url": "http://swagger.io" + }, + "license": { + "name": "MIT", + "url": "http://github.com/gruntjs/grunt/blob/master/LICENSE-MIT" + } + }, + "externalDocs": { + "description": "find more info here", + "url": "https://swagger.io/about" + }, + "host": "petstore.swagger.io", + "basePath": "/api", + "schemes": [ + "http" + ], + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "paths": { + "/pets": { + "get": { + "description": "Returns all pets from the system that the user has access to", + "operationId": "findPets", + "externalDocs": { + "description": "find more info here", + "url": "https://swagger.io/about" + }, + "produces": [ + "application/json", + "application/xml", + "text/xml", + "text/html" + ], + "parameters": [ + { + "name": "tags", + "in": "query", + "description": "tags to filter by", + "required": false, + "type": "array", + "items": { + "type": "string" + }, + "collectionFormat": "csv" + }, + { + "name": "limit", + "in": "query", + "description": "maximum number of results to return", + "required": false, + "type": "integer", + "format": "int32" + } + ], + "responses": { + "200": { + "description": "pet response", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Pet" + } + } + }, + "default": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorModel" + } + } + } + }, + "post": { + "description": "Creates a new pet in the store. Duplicates are allowed", + "operationId": "addPet", + "produces": [ + "application/json" + ], + "parameters": [ + { + "name": "pet", + "in": "body", + "description": "Pet to add to the store", + "required": true, + "schema": { + "$ref": "#/definitions/NewPet" + } + } + ], + "responses": { + "200": { + "description": "pet response", + "schema": { + "$ref": "#/definitions/Pet" + } + }, + "default": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorModel" + } + } + } + } + }, + "/pets/{id}": { + "get": { + "description": "Returns a user based on a single ID, if the user does not have access to the pet", + "operationId": "findPetById", + "produces": [ + "application/json", + "application/xml", + "text/xml", + "text/html" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "description": "ID of pet to fetch", + "required": true, + "type": "integer", + "format": "int64" + } + ], + "responses": { + "200": { + "description": "pet response", + "schema": { + "$ref": "#/definitions/Pet" + } + }, + "default": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorModel" + } + } + } + }, + "delete": { + "description": "deletes a single pet based on the ID supplied", + "operationId": "deletePet", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "ID of pet to delete", + "required": true, + "type": "integer", + "format": "int64" + } + ], + "responses": { + "204": { + "description": "pet deleted" + }, + "default": { + "description": "unexpected error", + "schema": { + "$ref": "#/definitions/ErrorModel" + } + } + } + } + } + }, + "definitions": { + "Pet": { + "type": "object", + "allOf": [ + { + "$ref": "#/definitions/NewPet" + }, + { + "required": [ + "id" + ], + "properties": { + "id": { + "type": "integer", + "format": "int64" + } + } + } + ] + }, + "NewPet": { + "type": "object", + "required": [ + "name" + ], + "properties": { + "name": { + "type": "string" + }, + "tag": { + "type": "string" + } + } + }, + "ErrorModel": { + "type": "object", + "required": [ + "code", + "message" + ], + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + } + } + } + } + }; + +let uberApiDefinition: SwaggerExpressMiddleware.SwaggerObject = + { + "swagger": "2.0", + "info": { + "title": "Uber API", + "description": "Move your app forward with the Uber API", + "version": "1.0.0" + }, + "host": "api.uber.com", + "schemes": [ + "https" + ], + "basePath": "/v1", + "produces": [ + "application/json" + ], + "paths": { + "/products": { + "get": { + "summary": "Product Types", + "description": "The Products endpoint returns information about the Uber products offered at a given location. The response includes the display name and other details about each product, and lists the products in the proper display order.", + "parameters": [ + { + "name": "latitude", + "in": "query", + "description": "Latitude component of location.", + "required": true, + "type": "number", + "format": "double" + }, + { + "name": "longitude", + "in": "query", + "description": "Longitude component of location.", + "required": true, + "type": "number", + "format": "double" + } + ], + "tags": [ + "Products" + ], + "responses": { + "200": { + "description": "An array of products", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Product" + } + } + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + } + }, + "/estimates/price": { + "get": { + "summary": "Price Estimates", + "description": "The Price Estimates endpoint returns an estimated price range for each product offered at a given location. The price estimate is provided as a formatted string with the full price range and the localized currency symbol.

The response also includes low and high estimates, and the [ISO 4217](http://en.wikipedia.org/wiki/ISO_4217) currency code for situations requiring currency conversion. When surge is active for a particular product, its surge_multiplier will be greater than 1, but the price estimate already factors in this multiplier.", + "parameters": [ + { + "name": "start_latitude", + "in": "query", + "description": "Latitude component of start location.", + "required": true, + "type": "number", + "format": "double" + }, + { + "name": "start_longitude", + "in": "query", + "description": "Longitude component of start location.", + "required": true, + "type": "number", + "format": "double" + }, + { + "name": "end_latitude", + "in": "query", + "description": "Latitude component of end location.", + "required": true, + "type": "number", + "format": "double" + }, + { + "name": "end_longitude", + "in": "query", + "description": "Longitude component of end location.", + "required": true, + "type": "number", + "format": "double" + } + ], + "tags": [ + "Estimates" + ], + "responses": { + "200": { + "description": "An array of price estimates by product", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/PriceEstimate" + } + } + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + } + }, + "/estimates/time": { + "get": { + "summary": "Time Estimates", + "description": "The Time Estimates endpoint returns ETAs for all products offered at a given location, with the responses expressed as integers in seconds. We recommend that this endpoint be called every minute to provide the most accurate, up-to-date ETAs.", + "parameters": [ + { + "name": "start_latitude", + "in": "query", + "description": "Latitude component of start location.", + "required": true, + "type": "number", + "format": "double" + }, + { + "name": "start_longitude", + "in": "query", + "description": "Longitude component of start location.", + "required": true, + "type": "number", + "format": "double" + }, + { + "name": "customer_uuid", + "in": "query", + "type": "string", + "format": "uuid", + "description": "Unique customer identifier to be used for experience customization." + }, + { + "name": "product_id", + "in": "query", + "type": "string", + "description": "Unique identifier representing a specific product for a given latitude & longitude." + } + ], + "tags": [ + "Estimates" + ], + "responses": { + "200": { + "description": "An array of products", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Product" + } + } + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + } + }, + "/me": { + "get": { + "summary": "User Profile", + "description": "The User Profile endpoint returns information about the Uber user that has authorized with the application.", + "tags": [ + "User" + ], + "responses": { + "200": { + "description": "Profile information for a user", + "schema": { + "$ref": "#/definitions/Profile" + } + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + } + }, + "/history": { + "get": { + "summary": "User Activity", + "description": "The User Activity endpoint returns data about a user's lifetime activity with Uber. The response will include pickup locations and times, dropoff locations and times, the distance of past requests, and information about which products were requested.

The history array in the response will have a maximum length based on the limit parameter. The response value count may exceed limit, therefore subsequent API requests may be necessary.", + "parameters": [ + { + "name": "offset", + "in": "query", + "type": "integer", + "format": "int32", + "description": "Offset the list of returned results by this amount. Default is zero." + }, + { + "name": "limit", + "in": "query", + "type": "integer", + "format": "int32", + "description": "Number of items to retrieve. Default is 5, maximum is 100." + } + ], + "tags": [ + "User" + ], + "responses": { + "200": { + "description": "History information for the given user", + "schema": { + "$ref": "#/definitions/Activities" + } + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + } + } + }, + "definitions": { + "Product": { + "properties": { + "product_id": { + "type": "string", + "description": "Unique identifier representing a specific product for a given latitude & longitude. For example, uberX in San Francisco will have a different product_id than uberX in Los Angeles." + }, + "description": { + "type": "string", + "description": "Description of product." + }, + "display_name": { + "type": "string", + "description": "Display name of product." + }, + "capacity": { + "type": "string", + "description": "Capacity of product. For example, 4 people." + }, + "image": { + "type": "string", + "description": "Image URL representing the product." + } + } + }, + "PriceEstimate": { + "properties": { + "product_id": { + "type": "string", + "description": "Unique identifier representing a specific product for a given latitude & longitude. For example, uberX in San Francisco will have a different product_id than uberX in Los Angeles" + }, + "currency_code": { + "type": "string", + "description": "[ISO 4217](http://en.wikipedia.org/wiki/ISO_4217) currency code." + }, + "display_name": { + "type": "string", + "description": "Display name of product." + }, + "estimate": { + "type": "string", + "description": "Formatted string of estimate in local currency of the start location. Estimate could be a range, a single number (flat rate) or \"Metered\" for TAXI." + }, + "low_estimate": { + "type": "number", + "description": "Lower bound of the estimated price." + }, + "high_estimate": { + "type": "number", + "description": "Upper bound of the estimated price." + }, + "surge_multiplier": { + "type": "number", + "description": "Expected surge multiplier. Surge is active if surge_multiplier is greater than 1. Price estimate already factors in the surge multiplier." + } + } + }, + "Profile": { + "properties": { + "first_name": { + "type": "string", + "description": "First name of the Uber user." + }, + "last_name": { + "type": "string", + "description": "Last name of the Uber user." + }, + "email": { + "type": "string", + "description": "Email address of the Uber user" + }, + "picture": { + "type": "string", + "description": "Image URL of the Uber user." + }, + "promo_code": { + "type": "string", + "description": "Promo code of the Uber user." + } + } + }, + "Activity": { + "properties": { + "uuid": { + "type": "string", + "description": "Unique identifier for the activity" + } + } + }, + "Activities": { + "properties": { + "offset": { + "type": "integer", + "format": "int32", + "description": "Position in pagination." + }, + "limit": { + "type": "integer", + "format": "int32", + "description": "Number of items to retrieve (100 max)." + }, + "count": { + "type": "integer", + "format": "int32", + "description": "Total number of items available." + }, + "history": { + "type": "array", + "items": { + "$ref": "#/definitions/Activity" + } + } + } + }, + "Error": { + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + }, + "fields": { + "type": "string" + } + } + } + } + } + diff --git a/swagger-express-middleware/swagger-express-middleware.d.ts b/swagger-express-middleware/swagger-express-middleware.d.ts new file mode 100644 index 0000000000..21e8324ff2 --- /dev/null +++ b/swagger-express-middleware/swagger-express-middleware.d.ts @@ -0,0 +1,592 @@ +// Type definitions for swagger-express-middleware 1.x +// Project: https://github.com/BigstickCarpet/swagger-express-middleware +// Definitions by: Alexandre Roba +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/* =================== USAGE =================== +import * as express from "express"; +import * as SwaggerExpressMiddleware from "swagger-express-middleware"; + +let app = express(); + +SwaggerExpressMiddleware("PetStore.yaml", app, (err: any, middleware: SwaggerExpressMiddleware.SwaggerMiddleware) => { + app.use( + middleware.metadata(), + middleware.CORS(), + middleware.files(), + middleware.parseRequest(), + middleware.validateRequest(), + middleware.mock() + ); +}); + +app.listen(8000, function () { + console.log('The PetStore sample is now running at http://localhost:8000'); +}); + + =============================================== */ + +/// + +declare module "swagger-express-middleware" { + import {Application, Router, RequestHandler, Request, Response} from "express"; + + let s: s.SwaggerMiddlewareConstructor; + + namespace s { + interface SwaggerMiddlewareConstructor { + (apiDefinitionPathOrObject: string | SwaggerObject, appOrRouter: Application | Router, cb: SwaggerMiddlewareConstructorCallback): SwaggerMiddleware; + } + interface SwaggerMiddlewareConstructorCallback { + (err: any, middleware: SwaggerMiddleware): void; + } + export interface SwaggerMiddleware { + /** + * Annotates the HTTP request (the `req` object) with Swagger metadata. + * This middleware populates Request.swagger + */ + metadata: MetadataSignature; + /** + * Handles CORS preflight requests and sets CORS headers for all requests according the Swagger API definition. + */ + CORS: CORSSignature; + /** + * Serves the Swagger API file(s) in JSON and YAML formats, so they can be used with third-party front-end tools like Swagger UI and Swagger Editor. + */ + files: FilesSignature; + /** + * Parses the HTTP request into typed values. + */ + parseRequest: ParseRequestSignature; + /** + * Validates the HTTP request against the Swagger API. + * An error is sent downstream if the request is invalid for any reason. + */ + validateRequest(): RequestHandler; + /** + * Implements mock behavior for HTTP requests, based on the Swagger API. + */ + mock: MockSignature; + } + + interface MockSignature { + ( + /** + * Express routing options (e.g. `caseSensitive`, `strict`). + * If an Express Application or Router is passed, then its routing settings will be used. + */ + router?: Application | Router, + /** + * The data store that will be used to persist REST resources. + * If `router` is an Express Application, then you can set/get the data store + * using `router.get("mock data store") + */ + datastore?: any): RequestHandler + } + interface MetadataSignature { + (router?: Application | Router): RequestHandler + } + + interface CORSSignature { + (): RequestHandler + } + + interface FilesSignature { + ( + /** + * Options for how the files are served + */ + options?: FilesOptions): RequestHandler + ( + /** + * If an Express Application or Router is passed, then its routing settings will be used. + */ + router: Application | Router, + /** + * Options for how the files are served + */ + options?: FilesOptions): RequestHandler + } + + interface ParseRequestSignature { + ( + /** + * Options for each of the request-parsing middleware + */ + options?: ParseRequestOptions): RequestHandler + ( + /** + * An Express Application or Router. + * If provided, this will be used to register path-param middleware via Router.Param + */ + router: Application | Router, + /** + * Options for each of the request-parsing middleware + */ + options?: ParseRequestOptions): RequestHandler + } + + export interface FilesOptions { + useBasePath?: boolean + apiPath?: string + rawFilesPath?: string + } + + export interface ParseRequestOptions { + /** + * Cookie parser options + */ + cookie?: CookieParserOptionItem + /** + * JSON body parser options + */ + json?: JsonParseOptionItem + /** + * Plain-text body parser options + */ + text?: TextParserOptionItem + /** + * URL-encoded body parser options + */ + urlencoded?: UrlEncodedOptionItem + /** + * Raw body parser options + */ + raw?: RawParserOptionItem + /** + * Multipart form data parser options + */ + multipart?: MulterOptions + } + + interface MulterOptions{ + /** The destination directory for the uploaded files. */ + dest?: string; + /** The storage engine to use for uploaded files. */ + storage?: StorageEngine; + /** An object specifying the size limits of the following optional properties. This object is passed to busboy directly, and the details of properties can be found on https://github.com/mscdex/busboy#busboy-methods */ + limits?: { + /** Max field name size (Default: 100 bytes) */ + fieldNameSize?: number; + /** Max field value size (Default: 1MB) */ + fieldSize?: number; + /** Max number of non- file fields (Default: Infinity) */ + fields?: number; + /** For multipart forms, the max file size (in bytes)(Default: Infinity) */ + fileSize?: number; + /** For multipart forms, the max number of file fields (Default: Infinity) */ + files?: number; + /** For multipart forms, the max number of parts (fields + files)(Default: Infinity) */ + parts?: number; + /** For multipart forms, the max number of header key=> value pairs to parse Default: 2000(same as node's http). */ + headerPairs?: number; + }; + /** A function to control which files to upload and which to skip. */ + fileFilter?: (req: Request, file: File, callback: (error: Error, acceptFile: boolean) => void) => void; + + } + + interface StorageEngine { + _handleFile(req: Request, file: File, callback: (error?: any, info?: File) => void): void; + _removeFile(req: Request, file: File, callback: (error: Error) => void): void; + } + + export interface File { + /** Field name specified in the form */ + fieldname: string; + /** Name of the file on the user's computer */ + originalname: string; + /** Encoding type of the file */ + encoding: string; + /** Mime type of the file */ + mimetype: string; + /** Size of the file in bytes */ + size: number; + /** The folder to which the file has been saved (DiskStorage) */ + destination: string; + /** The name of the file within the destination (DiskStorage) */ + filename: string; + /** Location of the uploaded file (DiskStorage) */ + path: string; + /** A Buffer of the entire file (MemoryStorage) */ + buffer: Buffer; + } + + interface RawParserOptionItem { + /** + * if deflated bodies will be inflated. (default: true) + */ + inflate?: boolean; + /** + * Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; + * if it is a string, the value is passed to the bytes library for parsing. Defaults to '100kb'. + */ + limit?: string | number; + /** + * The type option is used to determine what media type the middleware will parse. + * This option can be a function or a string. + * If a string, type option is passed directly to the type-is library and this can be an extension name (like bin), a mime type (like application/octet-stream), or a mime type with a wildcard (like * /* or application/*). + * If a function, the type option is called as fn(req) and the request is parsed if it returns a truthy value. + * Defaults to application/octet-stream. + */ + type?: ((req: Request) => string) | string + /** + * function to verify body content, the parsing can be aborted by throwing an error. + */ + verify?: (req: Request, res: Response, buf: Buffer, encoding: string) => void; + + } + + interface CookieParserOptionItem { + /** + * A string or array used for signing cookies. + * This is optional and if not specified, will not parse signed cookies. + * If a string is provided, this is used as the secret. + * If an array is provided, an attempt will be made to unsign the cookie with each secret in order. + */ + secret?: string | Array + /** + * an object that is passed to cookie.parse as the second option + */ + options?: any + } + + interface JsonParseOptionItem { + /** + * if deflated bodies will be inflated. (default: true) + */ + inflate?: boolean; + /** + * Controls the maximum request body size. + * If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the bytes library for parsing. + * Defaults to '100kb' + */ + limit?: string | number; + /** + * The type option is used to determine what media type the middleware will parse. + * This option can be a function or a string. + * If a string, type option is passed directly to the type-is library and this can be an extension name (like json), a mime type (like application/json), or a mime * type with a wildcard (like * /* or * /json). + * If a function, the type option is called as fn(req) and the request is parsed if it returns a truthy value. Defaults to application/json + */ + type?: ((req: Request) => string) | string + /** + * The verify option, if supplied, is called as verify(req, res, buf, encoding), where buf is a Buffer of the raw request body and encoding is the encoding of the request. + * The parsing can be aborted by throwing an error. + */ + verify?: (req: Request, res: Response, buf: Buffer, encoding: string) => void; + /** + * only parse objects and arrays. (default: true) + */ + strict?: boolean; + /** + * passed to JSON.parse(). + */ + receiver?: (key: string, value: any) => any; + } + + interface TextParserOptionItem { + /** + * if deflated bodies will be inflated. (default: true) + */ + inflate?: boolean; + /** + * Controls the maximum request body size. + * If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the bytes library for parsing. + * Defaults to '100kb' + */ + limit?: string | number; + /** + * The type option is used to determine what media type the middleware will parse. + * This option can be a function or a string. + * If a string, type option is passed directly to the type-is library and this can be an extension name (like txt), a mime type (like text/plain), or a mime type * with a wildcard (like * /* or text/*). + * If a function, the type option is called as fn(req) and the request is parsed if it returns a truthy value. Defaults to text/plain. + */ + type?: ((req: Request) => string) | string + /** + * function to verify body content, the parsing can be aborted by throwing an error. + */ + verify?: (req: Request, res: Response, buf: Buffer, encoding: string) => void; + /** + * the default charset to parse as, if not specified in content-type. (default: 'utf-8') + */ + defaultCharset?: string; + } + + interface UrlEncodedOptionItem { + /** + * if deflated bodies will be inflated. (default: true) + */ + inflate?: boolean; + /** + * Controls the maximum request body size. + * If this is a number, then the value specifies the number of bytes; + * if it is a string, the value is passed to the bytes library for parsing. + * Defaults to '100kb'. + */ + limit?: string | number; + /** + * The type option is used to determine what media type the middleware will parse. + * This option can be a function or a string. + * If a string, type option is passed directly to the type-is library and this can be an extension name (like urlencoded), a mime type (like application/x-www-form-urlencoded), + * or a mime type with a wildcard (like * /x-www-form-urlencoded). If a function, the type option is called as fn(req) and the request is parsed if it returns a truthy value. + * Defaults to application/x-www-form-urlencoded. + */ + type?: ((req: Request) => string) | string + /** + * function to verify body content, the parsing can be aborted by throwing an error. + */ + verify?: (req: Request, res: Response, buf: Buffer, encoding: string) => void; + /** + * parse extended syntax with the qs module. + */ + extended?: boolean; + } + + export interface SwaggerObject { + swagger: string + info: InfoObject + host?: string + basePath?: string + schemes?: string[] + consumes?: MimeTypes + produces?: MimeTypes + paths: PathsObject + definitions?: DefinitionsObject + parameters?: ParametersDefinitionsObject + responses?: ResponsesDefinitionsObject + securityDefinitions?: SecurityDefinitionsObject + security?: SecurityRequirementObject[] + tags?: TagObject[] + externalDocs?: ExternalDocumentationObject + } + + type MimeTypes = string[] + + export interface InfoObject { + title: string + description?: string + termsOfService?: string + contact?: ContactObject + license?: LicenseObject + version: string + } + + export interface ContactObject { + name?: string + url?: string + email?: string + } + + export interface LicenseObject { + name: string + url?: string + } + + export interface PathsObject { + [index: string]: PathItemObject | any + } + + export interface PathItemObject { + $ref?: string + get?: OperationObject + put?: OperationObject + post?: OperationObject + 'delete'?: OperationObject + options?: OperationObject + head?: OperationObject + patch?: OperationObject + parameters?: Parameters + } + + export interface OperationObject { + tags?: string[] + summary?: string + description?: string + externalDocs?: ExternalDocumentationObject + operationId?: string + consumes?: MimeTypes + produces?: MimeTypes + parameters?: Parameters + responses: ResponsesObject + schemes?: string[] + deprecated?: boolean + security?: SecurityRequirementObject[] + } + + export interface DefinitionsObject { + [index: string]: SchemaObject + } + + export interface ResponsesObject { + [index: string]: Response | any + 'default': Response + } + + type Response = ResponseObject | ReferenceObject + + export interface ResponsesDefinitionsObject { + [index: string]: ResponseObject + } + + export interface ResponseObject { + description: string + schema?: SchemaObject + headers?: HeadersObject + examples?: ExampleObject + } + + export interface HeadersObject { + [index: string]: HeaderObject + } + + export interface HeaderObject extends ItemsObject { + } + + export interface ExampleObject { + [index: string]: any + } + + export interface SecurityDefinitionsObject { + [index: string]: SecuritySchemeObject + } + + export interface SecuritySchemeObject { + type: string + description?: string + name: string + 'in': string + flow: string + authorizationUrl: string + tokenUrl: string + scopes: ScopesObject + } + export interface ScopesObject { + [index: string]: any + } + + export interface SecurityRequirementObject { + [index: string]: string[] + } + + export interface TagObject { + name: string + description?: string + externalDocs?: ExternalDocumentationObject + } + + export interface ItemsObject { + type: string + format?: string + items?: ItemsObject + collectionFormat?: string + 'default'?: any + maximum?: number + exclusiveMaximum: boolean + minimum?: number + exclusiveMinimum?: boolean + maxLength?: number + minLength?: number + pattern?: string + maxItems?: number + minItems?: number + uniqueItems?: boolean + 'enum'?: any[] + multipleOf?: number + } + + export interface ParametersDefinitionsObject { + [index: string]: ParameterObject + } + + type Parameters = (ParameterObject | ReferenceObject)[] + + export interface ParameterObject { + name: string + 'in': string + description?: string + required?: boolean + } + + export interface InBodyParameterObject extends ParameterObject { + schema: SchemaObject + } + + export interface GeneralParameterObject extends ParameterObject, ItemsObject { + allowEmptyValue?: boolean + } + + export interface ReferenceObject { + $ref: string + } + + export interface ExternalDocumentationObject { + [index: string]: any + description?: string + url: string + } + + export interface SchemaObject extends IJsonSchema { + [index: string]: any + discriminator?: string + readOnly?: boolean + xml?: XMLObject + externalDocs?: ExternalDocumentationObject + example?: any + } + + interface IJsonSchema { + id?: string + $schema?: string + title?: string + description?: string + multipleOf?: number + maximum?: number + exclusiveMaximum?: boolean + minimum?: number + exclusiveMinimum?: boolean + maxLength?: number + minLength?: number + pattern?: string + additionalItems?: boolean | IJsonSchema + items?: IJsonSchema | IJsonSchema[] + maxItems?: number + minItems?: number + uniqueItems?: boolean + maxProperties?: number + minProperties?: number + required?: string[] + additionalProperties?: boolean | IJsonSchema + definitions?: { + [name: string]: IJsonSchema + } + properties?: { + [name: string]: IJsonSchema + } + patternProperties?: { + [name: string]: IJsonSchema + } + dependencies?: { + [name: string]: IJsonSchema | string[] + } + 'enum'?: any[] + type?: string | string[] + allOf?: IJsonSchema[] + anyOf?: IJsonSchema[] + oneOf?: IJsonSchema[] + not?: IJsonSchema + $ref?: string + format?: string + } + + export interface XMLObject { + [index: string]: any + name?: string + namespace?: string + prefix?: string + attribute?: boolean + wrapped?: boolean + } + } + + export = s; +} \ No newline at end of file From b2286eb5f91aaf0a29ae11dfd153158b6662e93a Mon Sep 17 00:00:00 2001 From: Federico Caselli Date: Sat, 14 May 2016 18:17:57 +0200 Subject: [PATCH 051/402] Added declaration of module 'mathjs' (#9294) Mathjs can now be correctly used in nodejs, importing it in typescript with `import * as mathjs from 'mathjs';` --- mathjs/mathjs.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/mathjs/mathjs.d.ts b/mathjs/mathjs.d.ts index e9c15e1817..f21c192bb9 100644 --- a/mathjs/mathjs.d.ts +++ b/mathjs/mathjs.d.ts @@ -2208,3 +2208,8 @@ declare namespace mathjs { toString(): string; } } + +declare module 'mathjs'{ + export = math; +} + From ac927d3148210ddc1fcf3f57ad3792122e9b0cc5 Mon Sep 17 00:00:00 2001 From: Felix Date: Sat, 14 May 2016 18:18:15 +0200 Subject: [PATCH 052/402] =?UTF-8?q?-=20derive=20TabProps=20from=20SharedEn?= =?UTF-8?q?hancedButtonProps=20(TabProps=20are=20passed=E2=80=A6=20(#9218)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * - derive TabProps from SharedEnhancedButtonProps (TabProps are passed down to EnhancedButton inside)- Change signature of "onTouchTap" handler in TabProps to suit overridden "onTouchTap" in SharedEnhancedButtonProps * - fixed TabProps onTouchTap signature, added disabled property --- material-ui/material-ui.d.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/material-ui/material-ui.d.ts b/material-ui/material-ui.d.ts index 177cac59e1..970387459f 100644 --- a/material-ui/material-ui.d.ts +++ b/material-ui/material-ui.d.ts @@ -1587,18 +1587,20 @@ declare namespace __MaterialUI { export class Tabs extends React.Component { } - interface TabProps extends React.Props { + interface TabProps extends SharedEnhancedButtonProps { className?: string; icon?: React.ReactNode; label?: React.ReactNode; onActive?: (tab: Tab) => void; - onTouchTap?: (value: any, e: TouchTapEvent, tab: Tab) => void; + onTouchTap?: (value: any, e?: TouchTapEvent, tab?: Tab) => void; selected?: boolean; style?: React.CSSProperties; value?: any; width?: string; + disabled?: boolean; } - export class Tab extends React.Component { + export class Tab extends React.Component< + TabProps, {}> { } } From bdae66f35a53a1d97b85757848fdb2bf1b5c5847 Mon Sep 17 00:00:00 2001 From: Tsvetomir Tsonev Date: Sat, 14 May 2016 19:18:29 +0300 Subject: [PATCH 053/402] Update Kendo UI TypeScript definitions (#9296) * Update Kendo UI TypeScript definitions * Fix scale type * Add Grid footerAttributes --- kendo-ui/kendo-ui.d.ts | 538 +++++++++++++++++++++++++++++++++-------- 1 file changed, 441 insertions(+), 97 deletions(-) diff --git a/kendo-ui/kendo-ui.d.ts b/kendo-ui/kendo-ui.d.ts index 20b6bf16a2..cf57014386 100644 --- a/kendo-ui/kendo-ui.d.ts +++ b/kendo-ui/kendo-ui.d.ts @@ -262,7 +262,7 @@ declare namespace kendo { static fn: Observable; static extend(prototype: Object): Observable; - init(...args: any[]): void + init(...args: any[]): void; bind(eventName: string, handler: Function): Observable; one(eventName: string, handler: Function): Observable; first(eventName: string, handler: Function): Observable; @@ -1456,14 +1456,20 @@ declare namespace kendo.mobile { } interface ApplicationOptions { + browserHistory?: boolean; hideAddressBar?: boolean; updateDocumentTitle?: boolean; initial?: string; layout?: string; loading?: string; + modelScope?: Object; platform?: string; + retina?: boolean; serverNavigation?: boolean; + skin?: string; + statusBarStyle?: string; transition?: string; + useNativeScrolling?: boolean; } interface ApplicationEvent { @@ -1682,7 +1688,7 @@ declare namespace kendo.geometry { origin: kendo.geometry.Point; size: kendo.geometry.Size; - constructor(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; @@ -1792,6 +1798,7 @@ declare namespace kendo.drawing { clip(): kendo.drawing.Path; clip(clip: kendo.drawing.Path): void; clippedBBox(): kendo.geometry.Rect; + containsPoint(point: kendo.geometry.Point): boolean; geometry(): kendo.geometry.Arc; geometry(value: kendo.geometry.Arc): void; fill(color: string, opacity?: number): kendo.drawing.Arc; @@ -1812,6 +1819,7 @@ declare namespace kendo.drawing { fill?: kendo.drawing.FillOptions; opacity?: number; stroke?: kendo.drawing.StrokeOptions; + tooltip?: kendo.drawing.TooltipOptions; transform?: kendo.geometry.Transformation; visible?: boolean; } @@ -1835,6 +1843,7 @@ declare namespace kendo.drawing { clip(): kendo.drawing.Path; clip(clip: kendo.drawing.Path): void; clippedBBox(): kendo.geometry.Rect; + containsPoint(point: kendo.geometry.Point): boolean; geometry(): kendo.geometry.Circle; geometry(value: kendo.geometry.Circle): void; fill(color: string, opacity?: number): kendo.drawing.Circle; @@ -1855,6 +1864,7 @@ declare namespace kendo.drawing { fill?: kendo.drawing.FillOptions; opacity?: number; stroke?: kendo.drawing.StrokeOptions; + tooltip?: kendo.drawing.TooltipOptions; transform?: kendo.geometry.Transformation; visible?: boolean; } @@ -1870,6 +1880,7 @@ declare namespace kendo.drawing { options: ElementOptions; + parent: kendo.drawing.Group; constructor(options?: ElementOptions); @@ -1878,6 +1889,7 @@ declare namespace kendo.drawing { clip(): kendo.drawing.Path; clip(clip: kendo.drawing.Path): void; clippedBBox(): kendo.geometry.Rect; + containsPoint(point: kendo.geometry.Point): boolean; opacity(): number; opacity(opacity: number): void; transform(): kendo.geometry.Transformation; @@ -1982,6 +1994,7 @@ declare namespace kendo.drawing { clip(): kendo.drawing.Path; clip(clip: kendo.drawing.Path): void; clippedBBox(): kendo.geometry.Rect; + containsPoint(point: kendo.geometry.Point): boolean; insert(position: number, element: kendo.drawing.Element): void; opacity(): number; opacity(opacity: number): void; @@ -1998,6 +2011,7 @@ declare namespace kendo.drawing { cursor?: string; opacity?: number; pdf?: kendo.drawing.PDFOptions; + tooltip?: kendo.drawing.TooltipOptions; transform?: kendo.geometry.Transformation; visible?: boolean; } @@ -2021,6 +2035,7 @@ declare namespace kendo.drawing { clip(): kendo.drawing.Path; clip(clip: kendo.drawing.Path): void; clippedBBox(): kendo.geometry.Rect; + containsPoint(point: kendo.geometry.Point): boolean; opacity(): number; opacity(opacity: number): void; src(): string; @@ -2039,6 +2054,7 @@ declare namespace kendo.drawing { clip?: kendo.drawing.Path; cursor?: string; opacity?: number; + tooltip?: kendo.drawing.TooltipOptions; transform?: kendo.geometry.Transformation; visible?: boolean; } @@ -2128,6 +2144,7 @@ declare namespace kendo.drawing { clip(clip: kendo.drawing.Path): void; clippedBBox(): kendo.geometry.Rect; close(): kendo.drawing.MultiPath; + containsPoint(point: kendo.geometry.Point): boolean; curveTo(controlOut: any, controlIn: any, endPoint: any): kendo.drawing.MultiPath; curveTo(controlOut: any, controlIn: any, endPoint: kendo.geometry.Point): kendo.drawing.MultiPath; curveTo(controlOut: any, controlIn: kendo.geometry.Point, endPoint: any): kendo.drawing.MultiPath; @@ -2160,6 +2177,7 @@ declare namespace kendo.drawing { fill?: kendo.drawing.FillOptions; opacity?: number; stroke?: kendo.drawing.StrokeOptions; + tooltip?: kendo.drawing.TooltipOptions; transform?: kendo.geometry.Transformation; visible?: boolean; } @@ -2233,6 +2251,7 @@ declare namespace kendo.drawing { clip(clip: kendo.drawing.Path): void; clippedBBox(): kendo.geometry.Rect; close(): kendo.drawing.Path; + containsPoint(point: kendo.geometry.Point): boolean; curveTo(controlOut: any, controlIn: any, endPoint: any): kendo.drawing.Path; curveTo(controlOut: any, controlIn: any, endPoint: kendo.geometry.Point): kendo.drawing.Path; curveTo(controlOut: any, controlIn: kendo.geometry.Point, endPoint: any): kendo.drawing.Path; @@ -2265,6 +2284,7 @@ declare namespace kendo.drawing { fill?: kendo.drawing.FillOptions; opacity?: number; stroke?: kendo.drawing.StrokeOptions; + tooltip?: kendo.drawing.TooltipOptions; transform?: kendo.geometry.Transformation; visible?: boolean; } @@ -2321,6 +2341,7 @@ declare namespace kendo.drawing { clip(): kendo.drawing.Path; clip(clip: kendo.drawing.Path): void; clippedBBox(): kendo.geometry.Rect; + containsPoint(point: kendo.geometry.Point): boolean; geometry(): kendo.geometry.Rect; geometry(value: kendo.geometry.Rect): void; fill(color: string, opacity?: number): kendo.drawing.Rect; @@ -2341,6 +2362,7 @@ declare namespace kendo.drawing { fill?: kendo.drawing.FillOptions; opacity?: number; stroke?: kendo.drawing.StrokeOptions; + tooltip?: kendo.drawing.TooltipOptions; transform?: kendo.geometry.Transformation; visible?: boolean; } @@ -2411,18 +2433,43 @@ declare namespace kendo.drawing { clear(): void; draw(element: kendo.drawing.Element): void; eventTarget(e: any): kendo.drawing.Element; + hideTooltip(): void; resize(force?: boolean): void; + showTooltip(element: kendo.drawing.Element, options?: any): void; } + interface SurfaceTooltipAnimationClose { + effects?: string; + duration?: number; + } + + interface SurfaceTooltipAnimationOpen { + effects?: string; + duration?: number; + } + + interface SurfaceTooltipAnimation { + close?: SurfaceTooltipAnimationClose; + open?: SurfaceTooltipAnimationOpen; + } + + interface SurfaceTooltip { + animation?: boolean|SurfaceTooltipAnimation; + appendTo?: string|JQuery; + } + interface SurfaceOptions { name?: string; type?: string; height?: string; width?: string; + tooltip?: SurfaceTooltip; click?(e: SurfaceClickEvent): void; mouseenter?(e: SurfaceMouseenterEvent): void; mouseleave?(e: SurfaceMouseleaveEvent): void; + tooltipClose?(e: SurfaceTooltipCloseEvent): void; + tooltipOpen?(e: SurfaceTooltipOpenEvent): void; } interface SurfaceEvent { sender: Surface; @@ -2445,6 +2492,16 @@ declare namespace kendo.drawing { originalEvent?: any; } + interface SurfaceTooltipCloseEvent extends SurfaceEvent { + element?: kendo.drawing.Element; + target?: kendo.drawing.Element; + } + + interface SurfaceTooltipOpenEvent extends SurfaceEvent { + element?: kendo.drawing.Element; + target?: kendo.drawing.Element; + } + class Text extends kendo.drawing.Element { @@ -2459,6 +2516,7 @@ declare namespace kendo.drawing { clip(): kendo.drawing.Path; clip(clip: kendo.drawing.Path): void; clippedBBox(): kendo.geometry.Rect; + containsPoint(point: kendo.geometry.Point): boolean; content(): string; content(value: string): void; fill(color: string, opacity?: number): kendo.drawing.Text; @@ -2482,6 +2540,7 @@ declare namespace kendo.drawing { font?: string; opacity?: number; stroke?: kendo.drawing.StrokeOptions; + tooltip?: kendo.drawing.TooltipOptions; transform?: kendo.geometry.Transformation; visible?: boolean; } @@ -2492,6 +2551,28 @@ declare namespace kendo.drawing { } + interface TooltipOptions { + + + + autoHide?: boolean; + content?: string|Function; + position?: string; + height?: number|string; + hideDelay?: number; + offset?: number; + shared?: boolean; + showAfter?: number; + showOn?: string; + width?: number|string; + + + + + } + + + } declare namespace kendo.ui { class AutoComplete extends kendo.ui.Widget { @@ -2553,7 +2634,7 @@ declare namespace kendo.ui { interface AutoCompleteOptions { name?: string; - animation?: AutoCompleteAnimation; + animation?: boolean|AutoCompleteAnimation; dataSource?: any|any|kendo.data.DataSource; dataTextField?: string; delay?: number; @@ -2572,7 +2653,7 @@ declare namespace kendo.ui { headerTemplate?: string|Function; template?: string|Function; valuePrimitive?: boolean; - virtual?: AutoCompleteVirtual; + virtual?: boolean|AutoCompleteVirtual; change?(e: AutoCompleteChangeEvent): void; close?(e: AutoCompleteCloseEvent): void; dataBound?(e: AutoCompleteDataBoundEvent): void; @@ -2914,7 +2995,7 @@ declare namespace kendo.ui { text?: string; value?: string; valuePrimitive?: boolean; - virtual?: ComboBoxVirtual; + virtual?: boolean|ComboBoxVirtual; change?(e: ComboBoxChangeEvent): void; close?(e: ComboBoxCloseEvent): void; dataBound?(e: ComboBoxDataBoundEvent): void; @@ -3009,7 +3090,7 @@ declare namespace kendo.ui { interface ContextMenuOptions { name?: string; alignToAnchor?: boolean; - animation?: ContextMenuAnimation; + animation?: boolean|ContextMenuAnimation; closeOnClick?: boolean; dataSource?: any|any; direction?: string; @@ -3119,7 +3200,7 @@ declare namespace kendo.ui { interface DatePickerOptions { name?: string; - animation?: DatePickerAnimation; + animation?: boolean|DatePickerAnimation; ARIATemplate?: string; culture?: string; dates?: any; @@ -3209,7 +3290,7 @@ declare namespace kendo.ui { interface DateTimePickerOptions { name?: string; - animation?: DateTimePickerAnimation; + animation?: boolean|DateTimePickerAnimation; ARIATemplate?: string; culture?: string; dates?: any; @@ -3319,7 +3400,7 @@ declare namespace kendo.ui { interface DropDownListOptions { name?: string; - animation?: DropDownListAnimation; + animation?: boolean|DropDownListAnimation; autoBind?: boolean; cascadeFrom?: string; cascadeFromField?: string; @@ -3344,7 +3425,7 @@ declare namespace kendo.ui { text?: string; value?: string; valuePrimitive?: boolean; - virtual?: DropDownListVirtual; + virtual?: boolean|DropDownListVirtual; change?(e: DropDownListChangeEvent): void; close?(e: DropDownListCloseEvent): void; dataBound?(e: DropDownListDataBoundEvent): void; @@ -3418,6 +3499,10 @@ declare namespace kendo.ui { } + interface EditorDeserialization { + custom?: Function; + } + interface EditorFileBrowserMessages { uploadFile?: string; orderBy?: string; @@ -3646,6 +3731,18 @@ declare namespace kendo.ui { deleteColumn?: string; } + interface EditorPasteCleanup { + all?: boolean; + css?: boolean; + custom?: Function; + keepNewLines?: boolean; + msAllFormatting?: boolean; + msConvertLists?: boolean; + msTags?: boolean; + none?: boolean; + span?: boolean; + } + interface EditorPdfMargin { bottom?: number|string; left?: number|string; @@ -3678,6 +3775,7 @@ declare namespace kendo.ui { } interface EditorSerialization { + custom?: Function; entities?: boolean; scripts?: boolean; semantic?: boolean; @@ -3707,11 +3805,13 @@ declare namespace kendo.ui { interface EditorOptions { name?: string; + deserialization?: EditorDeserialization; domain?: string; encoded?: boolean; messages?: EditorMessages; + pasteCleanup?: EditorPasteCleanup; pdf?: EditorPdf; - resizable?: EditorResizable; + resizable?: boolean|EditorResizable; serialization?: EditorSerialization; stylesheets?: any; tools?: EditorTool[]; @@ -3745,6 +3845,101 @@ declare namespace kendo.ui { } + class FilterMenu extends kendo.ui.Widget { + + static fn: FilterMenu; + + options: FilterMenuOptions; + + field: string; + + element: JQuery; + wrapper: JQuery; + + static extend(proto: Object): FilterMenu; + + constructor(element: Element, options?: FilterMenuOptions); + + + clear(): void; + + } + + interface FilterMenuMessages { + and?: string; + clear?: string; + filter?: string; + info?: string; + isFalse?: string; + isTrue?: string; + or?: string; + selectValue?: string; + } + + interface FilterMenuOperatorsDate { + eq?: string; + neq?: string; + isnull?: string; + isnotnull?: string; + gte?: string; + gt?: string; + lte?: string; + lt?: string; + } + + interface FilterMenuOperatorsEnums { + eq?: string; + neq?: string; + isnull?: string; + isnotnull?: string; + } + + interface FilterMenuOperatorsNumber { + eq?: string; + neq?: string; + isnull?: string; + isnotnull?: string; + gte?: string; + gt?: string; + lte?: string; + lt?: string; + } + + interface FilterMenuOperatorsString { + eq?: string; + neq?: string; + isnull?: string; + isnotnull?: string; + isempty?: string; + isnotempty?: string; + startswith?: string; + contains?: string; + doesnotcontain?: string; + endswith?: string; + } + + interface FilterMenuOperators { + string?: FilterMenuOperatorsString; + number?: FilterMenuOperatorsNumber; + date?: FilterMenuOperatorsDate; + enums?: FilterMenuOperatorsEnums; + } + + interface FilterMenuOptions { + name?: string; + dataSource?: any|any|kendo.data.DataSource; + extra?: boolean; + field?: string; + messages?: FilterMenuMessages; + operators?: FilterMenuOperators; + } + interface FilterMenuEvent { + sender: FilterMenu; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + class FlatColorPicker extends kendo.ui.Widget { static fn: FlatColorPicker; @@ -3964,10 +4159,10 @@ declare namespace kendo.ui { autoBind?: boolean; columnResizeHandleWidth?: number; columns?: GanttColumn[]; - currentTimeMarker?: GanttCurrentTimeMarker; + currentTimeMarker?: boolean|GanttCurrentTimeMarker; dataSource?: any|any|kendo.data.GanttDataSource; dependencies?: any|any|kendo.data.GanttDependencyDataSource; - editable?: GanttEditable; + editable?: boolean|GanttEditable; navigatable?: boolean; workDayStart?: Date; workDayEnd?: Date; @@ -4253,7 +4448,8 @@ declare namespace kendo.ui { command?: GridColumnCommandItem[]; encoded?: boolean; field?: string; - filterable?: GridColumnFilterable; + filterable?: boolean|GridColumnFilterable; + footerAttributes?: any; footerTemplate?: string|Function; format?: string; groupable?: boolean; @@ -4265,7 +4461,7 @@ declare namespace kendo.ui { locked?: boolean; lockable?: boolean; minScreenWidth?: number; - sortable?: GridColumnSortable; + sortable?: boolean|GridColumnSortable; template?: string|Function; title?: string; width?: string|number; @@ -4301,8 +4497,10 @@ declare namespace kendo.ui { isFalse?: string; isTrue?: string; or?: string; + search?: string; selectValue?: string; cancel?: string; + selectedItemsFormat?: string; operator?: string; value?: string; checkAll?: string; @@ -4441,7 +4639,7 @@ declare namespace kendo.ui { paperSize?: string|any; template?: string; repeatHeaders?: boolean; - scale?: number|any|any; + scale?: number; proxyURL?: string; proxyTarget?: string; subject?: string; @@ -4465,31 +4663,31 @@ declare namespace kendo.ui { interface GridOptions { name?: string; - allowCopy?: GridAllowCopy; + allowCopy?: boolean|GridAllowCopy; altRowTemplate?: string|Function; autoBind?: boolean; columnResizeHandleWidth?: number; columns?: GridColumn[]; - columnMenu?: GridColumnMenu; + columnMenu?: boolean|GridColumnMenu; dataSource?: any|any|kendo.data.DataSource; detailTemplate?: string|Function; - editable?: GridEditable; + editable?: boolean|GridEditable; excel?: GridExcel; - filterable?: GridFilterable; - groupable?: GridGroupable; + filterable?: boolean|GridFilterable; + groupable?: boolean|GridGroupable; height?: number|string; messages?: GridMessages; mobile?: boolean|string; navigatable?: boolean; - noRecords?: GridNoRecords; - pageable?: GridPageable; + noRecords?: boolean|GridNoRecords; + pageable?: boolean|GridPageable; pdf?: GridPdf; reorderable?: boolean; resizable?: boolean; rowTemplate?: string|Function; - scrollable?: GridScrollable; + scrollable?: boolean|GridScrollable; selectable?: boolean|string; - sortable?: GridSortable; + sortable?: boolean|GridSortable; toolbar?: string | ((...args:any[]) => string) | GridToolbarItem[]; cancel?(e: GridCancelEvent): void; change?(e: GridChangeEvent): void; @@ -4806,7 +5004,7 @@ declare namespace kendo.ui { interface MenuOptions { name?: string; - animation?: MenuAnimation; + animation?: boolean|MenuAnimation; closeOnClick?: boolean; dataSource?: any|any; direction?: string; @@ -4913,7 +5111,7 @@ declare namespace kendo.ui { interface MultiSelectOptions { name?: string; - animation?: MultiSelectAnimation; + animation?: boolean|MultiSelectAnimation; autoBind?: boolean; autoClose?: boolean; dataSource?: any|any|kendo.data.DataSource; @@ -4937,7 +5135,7 @@ declare namespace kendo.ui { tagMode?: string; value?: any; valuePrimitive?: boolean; - virtual?: MultiSelectVirtual; + virtual?: boolean|MultiSelectVirtual; change?(e: MultiSelectChangeEvent): void; close?(e: MultiSelectCloseEvent): void; dataBound?(e: MultiSelectDataBoundEvent): void; @@ -5274,7 +5472,7 @@ declare namespace kendo.ui { interface PanelBarOptions { name?: string; - animation?: PanelBarAnimation; + animation?: boolean|PanelBarAnimation; contentUrls?: any; dataSource?: any|any; expandMode?: string; @@ -5382,7 +5580,7 @@ declare namespace kendo.ui { name?: string; dataSource?: any|kendo.data.PivotDataSource; filterable?: boolean; - sortable?: PivotConfiguratorSortable; + sortable?: boolean|PivotConfiguratorSortable; height?: number|string; messages?: PivotConfiguratorMessages; } @@ -5494,7 +5692,7 @@ declare namespace kendo.ui { excel?: PivotGridExcel; pdf?: PivotGridPdf; filterable?: boolean; - sortable?: PivotGridSortable; + sortable?: boolean|PivotGridSortable; columnWidth?: number; height?: number|string; columnHeaderTemplate?: string|Function; @@ -5583,7 +5781,7 @@ declare namespace kendo.ui { interface PopupOptions { name?: string; adjustSize?: any; - animation?: PopupAnimation; + animation?: boolean|PopupAnimation; anchor?: string|JQuery; appendTo?: string|JQuery; collision?: string; @@ -6021,7 +6219,7 @@ declare namespace kendo.ui { columnWidth?: number; dateHeaderTemplate?: string|Function; dayTemplate?: string|Function; - editable?: SchedulerViewEditable; + editable?: boolean|SchedulerViewEditable; endTime?: Date; eventHeight?: number; eventTemplate?: string|Function; @@ -6055,14 +6253,14 @@ declare namespace kendo.ui { allDayEventTemplate?: string|Function; allDaySlot?: boolean; autoBind?: boolean; - currentTimeMarker?: SchedulerCurrentTimeMarker; + currentTimeMarker?: boolean|SchedulerCurrentTimeMarker; dataSource?: any|any|kendo.data.SchedulerDataSource; date?: Date; dateHeaderTemplate?: string|Function; - editable?: SchedulerEditable; + editable?: boolean|SchedulerEditable; endTime?: Date; eventTemplate?: string|Function; - footer?: SchedulerFooter; + footer?: boolean|SchedulerFooter; group?: SchedulerGroup; height?: number|string; majorTick?: number; @@ -6574,6 +6772,7 @@ declare namespace kendo.ui { format?: string; formula?: string; index?: number; + link?: string; textAlign?: string; underline?: boolean; value?: number|string|boolean|Date; @@ -6643,7 +6842,7 @@ declare namespace kendo.ui { rows?: number; sheets?: SpreadsheetSheet[]; sheetsbar?: boolean; - toolbar?: SpreadsheetToolbar; + toolbar?: boolean|SpreadsheetToolbar; change?(e: SpreadsheetChangeEvent): void; render?(e: SpreadsheetRenderEvent): void; excelExport?(e: SpreadsheetExcelExportEvent): void; @@ -6769,7 +6968,7 @@ declare namespace kendo.ui { interface TabStripOptions { name?: string; - animation?: TabStripAnimation; + animation?: boolean|TabStripAnimation; collapsible?: boolean; contentUrls?: any; dataContentField?: string; @@ -6780,7 +6979,7 @@ declare namespace kendo.ui { dataTextField?: string; dataUrlField?: string; navigatable?: boolean; - scrollable?: TabStripScrollable; + scrollable?: boolean|TabStripScrollable; tabPosition?: string; value?: string; activate?(e: TabStripActivateEvent): void; @@ -6871,7 +7070,7 @@ declare namespace kendo.ui { interface TimePickerOptions { name?: string; - animation?: TimePickerAnimation; + animation?: boolean|TimePickerAnimation; culture?: string; dates?: any; format?: string; @@ -7078,7 +7277,7 @@ declare namespace kendo.ui { interface TooltipOptions { name?: string; autoHide?: boolean; - animation?: TooltipAnimation; + animation?: boolean|TooltipAnimation; content?: TooltipContent; callout?: boolean; filter?: string; @@ -7241,6 +7440,9 @@ declare namespace kendo.ui { addRow(parentRow: string): void; addRow(parentRow: Element): void; addRow(parentRow: JQuery): void; + autoFitColumn(column: number): void; + autoFitColumn(column: string): void; + autoFitColumn(column: any): void; cancelRow(): void; clearSelection(): void; collapse(): void; @@ -7313,13 +7515,13 @@ declare namespace kendo.ui { encoded?: boolean; expandable?: boolean; field?: string; - filterable?: TreeListColumnFilterable; + filterable?: boolean|TreeListColumnFilterable; footerTemplate?: string|Function; format?: string; headerAttributes?: any; headerTemplate?: string|Function; minScreenWidth?: number; - sortable?: TreeListColumnSortable; + sortable?: boolean|TreeListColumnSortable; template?: string|Function; title?: string; width?: string|number; @@ -7420,17 +7622,17 @@ declare namespace kendo.ui { columns?: TreeListColumn[]; resizable?: boolean; reorderable?: boolean; - columnMenu?: TreeListColumnMenu; + columnMenu?: boolean|TreeListColumnMenu; dataSource?: any|any|kendo.data.TreeListDataSource; - editable?: TreeListEditable; + editable?: boolean|TreeListEditable; excel?: TreeListExcel; - filterable?: TreeListFilterable; + filterable?: boolean|TreeListFilterable; height?: number|string; messages?: TreeListMessages; pdf?: TreeListPdf; scrollable?: boolean|any; selectable?: boolean|string; - sortable?: TreeListSortable; + sortable?: boolean|TreeListSortable; toolbar?: TreeListToolbarItem[]; cancel?(e: TreeListCancelEvent): void; change?(e: TreeListChangeEvent): void; @@ -7645,8 +7847,8 @@ declare namespace kendo.ui { } interface TreeViewAnimation { - collapse?: TreeViewAnimationCollapse; - expand?: TreeViewAnimationExpand; + collapse?: boolean|TreeViewAnimationCollapse; + expand?: boolean|TreeViewAnimationExpand; } interface TreeViewCheckboxes { @@ -7663,10 +7865,10 @@ declare namespace kendo.ui { interface TreeViewOptions { name?: string; - animation?: TreeViewAnimation; + animation?: boolean|TreeViewAnimation; autoBind?: boolean; autoScroll?: boolean; - checkboxes?: TreeViewCheckboxes; + checkboxes?: boolean|TreeViewCheckboxes; dataImageUrlField?: string; dataSource?: any|any|kendo.data.HierarchicalDataSource; dataSpriteCssClassField?: string; @@ -7978,7 +8180,7 @@ declare namespace kendo.ui { interface WindowOptions { name?: string; actions?: any; - animation?: WindowAnimation; + animation?: boolean|WindowAnimation; appendTo?: any|string; autoFocus?: boolean; content?: WindowContent; @@ -9211,7 +9413,7 @@ declare namespace kendo.dataviz.ui { size?: number; sizeField?: string; spacing?: number; - stack?: ChartSeriesItemStack; + stack?: boolean|ChartSeriesItemStack; startAngle?: number; target?: ChartSeriesItemTarget; targetField?: string; @@ -9427,7 +9629,7 @@ declare namespace kendo.dataviz.ui { scatter?: any; scatterLine?: any; spacing?: number; - stack?: ChartSeriesDefaultsStack; + stack?: boolean|ChartSeriesDefaultsStack; type?: string; tooltip?: ChartSeriesDefaultsTooltip; verticalArea?: any; @@ -10357,8 +10559,8 @@ declare namespace kendo.dataviz.ui { } interface ChartZoomable { - mousewheel?: ChartZoomableMousewheel; - selection?: ChartZoomableSelection; + mousewheel?: boolean|ChartZoomableMousewheel; + selection?: boolean|ChartZoomableSelection; } interface ChartExportImageOptions { @@ -10397,7 +10599,7 @@ declare namespace kendo.dataviz.ui { dataSource?: any|any|kendo.data.DataSource; legend?: ChartLegend; panes?: ChartPane[]; - pannable?: ChartPannable; + pannable?: boolean|ChartPannable; pdf?: ChartPdf; plotArea?: ChartPlotArea; renderAs?: string; @@ -10411,7 +10613,7 @@ declare namespace kendo.dataviz.ui { valueAxis?: ChartValueAxisItem[]; xAxis?: ChartXAxisItem[]; yAxis?: ChartYAxisItem[]; - zoomable?: ChartZoomable; + zoomable?: boolean|ChartZoomable; axisLabelClick?(e: ChartAxisLabelClickEvent): void; legendItemClick?(e: ChartLegendItemClickEvent): void; legendItemHover?(e: ChartLegendItemHoverEvent): void; @@ -10422,6 +10624,7 @@ declare namespace kendo.dataviz.ui { noteClick?(e: ChartNoteClickEvent): void; noteHover?(e: ChartNoteHoverEvent): void; plotAreaClick?(e: ChartPlotAreaClickEvent): void; + plotAreaHover?(e: ChartPlotAreaHoverEvent): void; render?(e: ChartEvent): void; select?(e: ChartSelectEvent): void; selectEnd?(e: ChartSelectEndEvent): void; @@ -10508,6 +10711,15 @@ declare namespace kendo.dataviz.ui { y?: any; } + interface ChartPlotAreaHoverEvent extends ChartEvent { + category?: any; + element?: any; + originalEvent?: any; + value?: any; + x?: any; + y?: any; + } + interface ChartSelectEvent extends ChartEvent { axis?: any; from?: any; @@ -10571,9 +10783,9 @@ declare namespace kendo.dataviz.ui { options: DiagramOptions; dataSource: kendo.data.DataSource; - connections: DiagramConnection[]; + connections: kendo.dataviz.diagram.Connection[]; connectionsDataSource: kendo.data.DataSource; - shapes: DiagramShape[]; + shapes: kendo.dataviz.diagram.Shape[]; element: JQuery; wrapper: JQuery; @@ -10604,7 +10816,13 @@ declare namespace kendo.dataviz.ui { exportPDF(options?: kendo.drawing.PDFOptions): JQueryPromise; exportSVG(options: any): JQueryPromise; focus(): void; + getConnectionByModelId(id: string): kendo.dataviz.diagram.Connection; + getConnectionByModelId(id: number): kendo.dataviz.diagram.Connection; + getConnectionByModelUid(uid: string): kendo.dataviz.diagram.Connection; getShapeById(id: string): any; + getShapeByModelId(id: string): kendo.dataviz.diagram.Shape; + getShapeByModelId(id: number): kendo.dataviz.diagram.Shape; + getShapeByModelUid(uid: string): kendo.dataviz.diagram.Shape; layerToModel(point: any): any; layout(options: any): void; load(json: string): void; @@ -10643,6 +10861,8 @@ declare namespace kendo.dataviz.ui { color?: string; fontFamily?: string; fontSize?: number; + fontStyle?: string; + fontWeight?: string; template?: string|Function; text?: string; visual?: Function; @@ -10724,7 +10944,7 @@ declare namespace kendo.dataviz.ui { interface DiagramConnectionDefaults { content?: DiagramConnectionDefaultsContent; - editable?: DiagramConnectionDefaultsEditable; + editable?: boolean|DiagramConnectionDefaultsEditable; endCap?: DiagramConnectionDefaultsEndCap; fromConnector?: string; hover?: DiagramConnectionDefaultsHover; @@ -10740,6 +10960,8 @@ declare namespace kendo.dataviz.ui { color?: string; fontFamily?: string; fontSize?: number; + fontStyle?: string; + fontWeight?: string; template?: string|Function; text?: string; visual?: Function; @@ -10834,7 +11056,7 @@ declare namespace kendo.dataviz.ui { interface DiagramConnection { content?: DiagramConnectionContent; - editable?: DiagramConnectionEditable; + editable?: boolean|DiagramConnectionEditable; endCap?: DiagramConnectionEndCap; from?: DiagramConnectionFrom; fromConnector?: string; @@ -10853,7 +11075,7 @@ declare namespace kendo.dataviz.ui { } interface DiagramEditableDrag { - snap?: DiagramEditableDragSnap; + snap?: boolean|DiagramEditableDragSnap; } interface DiagramEditableResizeHandlesFill { @@ -10917,10 +11139,10 @@ declare namespace kendo.dataviz.ui { interface DiagramEditable { connectionTemplate?: string|Function; - drag?: DiagramEditableDrag; + drag?: boolean|DiagramEditableDrag; remove?: boolean; - resize?: DiagramEditableResize; - rotate?: DiagramEditableRotate; + resize?: boolean|DiagramEditableResize; + rotate?: boolean|DiagramEditableRotate; shapeTemplate?: string|Function; tools?: DiagramEditableTool[]; } @@ -11067,6 +11289,8 @@ declare namespace kendo.dataviz.ui { color?: string; fontFamily?: string; fontSize?: number; + fontStyle?: string; + fontWeight?: string; template?: string|Function; text?: string; } @@ -11127,7 +11351,7 @@ declare namespace kendo.dataviz.ui { connectors?: DiagramShapeDefaultsConnector[]; connectorDefaults?: DiagramShapeDefaultsConnectorDefaults; content?: DiagramShapeDefaultsContent; - editable?: DiagramShapeDefaultsEditable; + editable?: boolean|DiagramShapeDefaultsEditable; fill?: DiagramShapeDefaultsFill; height?: number; hover?: DiagramShapeDefaultsHover; @@ -11223,6 +11447,8 @@ declare namespace kendo.dataviz.ui { color?: string; fontFamily?: string; fontSize?: number; + fontStyle?: string; + fontWeight?: string; template?: string|Function; text?: string; } @@ -11281,7 +11507,7 @@ declare namespace kendo.dataviz.ui { connectors?: DiagramShapeConnector[]; connectorDefaults?: DiagramShapeConnectorDefaults; content?: DiagramShapeContent; - editable?: DiagramShapeEditable; + editable?: boolean|DiagramShapeEditable; fill?: DiagramShapeFill; height?: number; hover?: DiagramShapeHover; @@ -11320,11 +11546,11 @@ declare namespace kendo.dataviz.ui { connections?: DiagramConnection[]; connectionsDataSource?: any|any|kendo.data.DataSource; dataSource?: any|any|kendo.data.DataSource; - editable?: DiagramEditable; + editable?: boolean|DiagramEditable; layout?: DiagramLayout; - pannable?: DiagramPannable; + pannable?: boolean|DiagramPannable; pdf?: DiagramPdf; - selectable?: DiagramSelectable; + selectable?: boolean|DiagramSelectable; shapeDefaults?: DiagramShapeDefaults; shapes?: DiagramShape[]; template?: string|Function; @@ -11385,16 +11611,19 @@ declare namespace kendo.dataviz.ui { } interface DiagramDragEvent extends DiagramEvent { + connectionHandle?: string; connections?: any; shapes?: any; } interface DiagramDragEndEvent extends DiagramEvent { + connectionHandle?: string; connections?: any; shapes?: any; } interface DiagramDragStartEvent extends DiagramEvent { + connectionHandle?: string; connections?: any; shapes?: any; } @@ -11700,9 +11929,9 @@ declare namespace kendo.dataviz.ui { } interface MapControls { - attribution?: MapControlsAttribution; - navigator?: MapControlsNavigator; - zoom?: MapControlsZoom; + attribution?: boolean|MapControlsAttribution; + navigator?: boolean|MapControlsNavigator; + zoom?: boolean|MapControlsZoom; } interface MapLayerDefaultsBing { @@ -11995,6 +12224,7 @@ declare namespace kendo.dataviz.ui { reset?(e: MapResetEvent): void; shapeClick?(e: MapShapeClickEvent): void; shapeCreated?(e: MapShapeCreatedEvent): void; + shapeFeatureCreated?(e: MapShapeFeatureCreatedEvent): void; shapeMouseEnter?(e: MapShapeMouseEnterEvent): void; shapeMouseLeave?(e: MapShapeMouseLeaveEvent): void; zoomStart?(e: MapZoomStartEvent): void; @@ -12056,6 +12286,13 @@ declare namespace kendo.dataviz.ui { originalEvent?: any; } + interface MapShapeFeatureCreatedEvent extends MapEvent { + dataItem?: any; + layer?: kendo.dataviz.map.layer.Shape; + group?: kendo.drawing.Group; + properties?: any; + } + interface MapShapeMouseEnterEvent extends MapEvent { layer?: kendo.dataviz.map.layer.Shape; shape?: kendo.drawing.Element; @@ -12773,7 +13010,7 @@ declare namespace kendo.dataviz.ui { size?: number; startAngle?: number; spacing?: number; - stack?: SparklineSeriesItemStack; + stack?: boolean|SparklineSeriesItemStack; tooltip?: SparklineSeriesItemTooltip; width?: number; target?: SparklineSeriesItemTarget; @@ -12836,7 +13073,7 @@ declare namespace kendo.dataviz.ui { overlay?: any; pie?: any; spacing?: number; - stack?: SparklineSeriesDefaultsStack; + stack?: boolean|SparklineSeriesDefaultsStack; type?: string; tooltip?: SparklineSeriesDefaultsTooltip; } @@ -14041,7 +14278,7 @@ declare namespace kendo.dataviz.ui { openField?: string; overlay?: StockChartNavigatorSeriesItemOverlay; spacing?: number; - stack?: StockChartNavigatorSeriesItemStack; + stack?: boolean|StockChartNavigatorSeriesItemStack; tooltip?: StockChartNavigatorSeriesItemTooltip; width?: number; } @@ -14311,7 +14548,7 @@ declare namespace kendo.dataviz.ui { openField?: string; overlay?: StockChartSeriesItemOverlay; spacing?: number; - stack?: StockChartSeriesItemStack; + stack?: boolean|StockChartSeriesItemStack; tooltip?: StockChartSeriesItemTooltip; visibleInLegend?: boolean; width?: number; @@ -14376,7 +14613,7 @@ declare namespace kendo.dataviz.ui { overlay?: any; pie?: any; spacing?: number; - stack?: StockChartSeriesDefaultsStack; + stack?: boolean|StockChartSeriesDefaultsStack; type?: string; tooltip?: StockChartSeriesDefaultsTooltip; } @@ -14702,6 +14939,7 @@ declare namespace kendo.dataviz.ui { noteClick?(e: StockChartNoteClickEvent): void; noteHover?(e: StockChartNoteHoverEvent): void; plotAreaClick?(e: StockChartPlotAreaClickEvent): void; + plotAreaHover?(e: StockChartPlotAreaHoverEvent): void; render?(e: StockChartEvent): void; seriesClick?(e: StockChartSeriesClickEvent): void; seriesHover?(e: StockChartSeriesHoverEvent): void; @@ -14782,6 +15020,15 @@ declare namespace kendo.dataviz.ui { y?: any; } + interface StockChartPlotAreaHoverEvent extends StockChartEvent { + category?: any; + element?: any; + originalEvent?: any; + value?: any; + x?: any; + y?: any; + } + interface StockChartSeriesClickEvent extends StockChartEvent { value?: any; category?: any; @@ -14920,7 +15167,7 @@ declare namespace kendo.dataviz.map { nw: kendo.dataviz.map.Location; se: kendo.dataviz.map.Location; - constructor(nw: kendo.dataviz.map.Location, se: kendo.dataviz.map.Location); + constructor(nw: kendo.dataviz.map.Location|any, se: kendo.dataviz.map.Location|any); static create(a: kendo.dataviz.map.Location, b?: kendo.dataviz.map.Location): kendo.dataviz.map.Extent; static create(a: kendo.dataviz.map.Location, b?: any): kendo.dataviz.map.Extent; @@ -15167,15 +15414,15 @@ declare namespace kendo.dataviz { range(): any; - slot(from: string, to?: string): kendo.geometry.Rect; - slot(from: string, to?: number): kendo.geometry.Rect; - slot(from: string, to?: Date): kendo.geometry.Rect; - slot(from: number, to?: string): kendo.geometry.Rect; - slot(from: number, to?: number): kendo.geometry.Rect; - slot(from: number, to?: Date): kendo.geometry.Rect; - slot(from: Date, to?: string): kendo.geometry.Rect; - slot(from: Date, to?: number): kendo.geometry.Rect; - slot(from: Date, to?: Date): kendo.geometry.Rect; + slot(from: string, to?: string, limit?: boolean): kendo.geometry.Rect; + slot(from: string, to?: number, limit?: boolean): kendo.geometry.Rect; + slot(from: string, to?: Date, limit?: boolean): kendo.geometry.Rect; + slot(from: number, to?: string, limit?: boolean): kendo.geometry.Rect; + slot(from: number, to?: number, limit?: boolean): kendo.geometry.Rect; + slot(from: number, to?: Date, limit?: boolean): kendo.geometry.Rect; + slot(from: Date, to?: string, limit?: boolean): kendo.geometry.Rect; + slot(from: Date, to?: number, limit?: boolean): kendo.geometry.Rect; + slot(from: Date, to?: Date, limit?: boolean): kendo.geometry.Rect; } @@ -15196,6 +15443,7 @@ declare namespace kendo.dataviz.diagram { options: CircleOptions; + drawingElement: kendo.drawing.Circle; constructor(options?: CircleOptions); @@ -15285,6 +15533,8 @@ declare namespace kendo.dataviz.diagram { color?: string; fontFamily?: string; fontSize?: number; + fontStyle?: string; + fontWeight?: string; template?: string|Function; text?: string; visual?: Function; @@ -15425,6 +15675,7 @@ declare namespace kendo.dataviz.diagram { options: GroupOptions; + drawingElement: kendo.drawing.Group; constructor(options?: GroupOptions); @@ -15457,6 +15708,7 @@ declare namespace kendo.dataviz.diagram { options: ImageOptions; + drawingElement: kendo.drawing.Image; constructor(options?: ImageOptions); @@ -15489,6 +15741,7 @@ declare namespace kendo.dataviz.diagram { options: LayoutOptions; + drawingElement: kendo.drawing.Layout; constructor(rect: kendo.dataviz.diagram.Rect, options?: LayoutOptions); @@ -15526,6 +15779,7 @@ declare namespace kendo.dataviz.diagram { options: LineOptions; + drawingElement: kendo.drawing.Path; constructor(options?: LineOptions); @@ -15561,6 +15815,7 @@ declare namespace kendo.dataviz.diagram { options: PathOptions; + drawingElement: kendo.drawing.Path; constructor(options?: PathOptions); @@ -15680,6 +15935,7 @@ declare namespace kendo.dataviz.diagram { options: PolylineOptions; + drawingElement: kendo.drawing.Path; constructor(options?: PolylineOptions); @@ -15801,6 +16057,7 @@ declare namespace kendo.dataviz.diagram { options: RectangleOptions; + drawingElement: kendo.drawing.Path; constructor(options?: RectangleOptions); @@ -15873,6 +16130,7 @@ declare namespace kendo.dataviz.diagram { getConnector(): void; getPosition(side: string): void; redraw(options: any): void; + redrawVisual(): void; } @@ -15922,6 +16180,8 @@ declare namespace kendo.dataviz.diagram { color?: string; fontFamily?: string; fontSize?: number; + fontStyle?: string; + fontWeight?: string; text?: string; } @@ -15972,7 +16232,7 @@ declare namespace kendo.dataviz.diagram { interface ShapeOptions { name?: string; id?: string; - editable?: ShapeEditable; + editable?: boolean|ShapeEditable; path?: string; stroke?: ShapeStroke; type?: string; @@ -16003,6 +16263,7 @@ declare namespace kendo.dataviz.diagram { options: TextBlockOptions; + drawingElement: kendo.drawing.Text; constructor(options?: TextBlockOptions); @@ -16022,6 +16283,8 @@ declare namespace kendo.dataviz.diagram { color?: string; fontFamily?: string; fontSize?: number; + fontStyle?: string; + fontWeight?: string; height?: number; text?: string; width?: number; @@ -16222,6 +16485,8 @@ declare namespace kendo.spreadsheet { isFilterable(): boolean; italic(): boolean; italic(value?: boolean): void; + link(): string; + link(url?: string): void; merge(): void; select(): void; sort(sort: number): void; @@ -16280,10 +16545,10 @@ declare namespace kendo.spreadsheet { rowHeight(): void; rowHeight(index: number, width?: number): void; selection(): kendo.spreadsheet.Range; + setDataSource(dataSource: kendo.data.DataSource, columns?: any): void; showGridLines(): boolean; showGridLines(showGridLiens?: boolean): void; toJSON(): void; - setDataSource(dataSource: kendo.data.DataSource, columns?: any): void; unhideColumn(index: number): void; unhideRow(index: number): void; @@ -16752,7 +17017,7 @@ declare namespace kendo.mobile.ui { style?: string; template?: string|Function; type?: string; - filterable?: ListViewFilterable; + filterable?: boolean|ListViewFilterable; virtualViewSize?: number; click?(e: ListViewClickEvent): void; dataBound?(e: ListViewEvent): void; @@ -17360,22 +17625,22 @@ declare namespace kendo.ooxml { interface WorkbookSheetRowCellBorderBottom { color?: string; - size?: string; + size?: number; } interface WorkbookSheetRowCellBorderLeft { color?: string; - size?: string; + size?: number; } interface WorkbookSheetRowCellBorderRight { color?: string; - size?: string; + size?: number; } interface WorkbookSheetRowCellBorderTop { color?: string; - size?: string; + size?: number; } interface WorkbookSheetRowCell { @@ -17607,7 +17872,7 @@ declare namespace kendo.dataviz.geometry { origin: kendo.geometry.Point; size: kendo.geometry.Size; - constructor(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; @@ -17717,6 +17982,7 @@ declare namespace kendo.dataviz.drawing { clip(): kendo.drawing.Path; clip(clip: kendo.drawing.Path): void; clippedBBox(): kendo.geometry.Rect; + containsPoint(point: kendo.geometry.Point): boolean; geometry(): kendo.geometry.Arc; geometry(value: kendo.geometry.Arc): void; fill(color: string, opacity?: number): kendo.drawing.Arc; @@ -17737,6 +18003,7 @@ declare namespace kendo.dataviz.drawing { fill?: kendo.drawing.FillOptions; opacity?: number; stroke?: kendo.drawing.StrokeOptions; + tooltip?: kendo.drawing.TooltipOptions; transform?: kendo.geometry.Transformation; visible?: boolean; } @@ -17760,6 +18027,7 @@ declare namespace kendo.dataviz.drawing { clip(): kendo.drawing.Path; clip(clip: kendo.drawing.Path): void; clippedBBox(): kendo.geometry.Rect; + containsPoint(point: kendo.geometry.Point): boolean; geometry(): kendo.geometry.Circle; geometry(value: kendo.geometry.Circle): void; fill(color: string, opacity?: number): kendo.drawing.Circle; @@ -17780,6 +18048,7 @@ declare namespace kendo.dataviz.drawing { fill?: kendo.drawing.FillOptions; opacity?: number; stroke?: kendo.drawing.StrokeOptions; + tooltip?: kendo.drawing.TooltipOptions; transform?: kendo.geometry.Transformation; visible?: boolean; } @@ -17795,6 +18064,7 @@ declare namespace kendo.dataviz.drawing { options: ElementOptions; + parent: kendo.drawing.Group; constructor(options?: ElementOptions); @@ -17803,6 +18073,7 @@ declare namespace kendo.dataviz.drawing { clip(): kendo.drawing.Path; clip(clip: kendo.drawing.Path): void; clippedBBox(): kendo.geometry.Rect; + containsPoint(point: kendo.geometry.Point): boolean; opacity(): number; opacity(opacity: number): void; transform(): kendo.geometry.Transformation; @@ -17907,6 +18178,7 @@ declare namespace kendo.dataviz.drawing { clip(): kendo.drawing.Path; clip(clip: kendo.drawing.Path): void; clippedBBox(): kendo.geometry.Rect; + containsPoint(point: kendo.geometry.Point): boolean; insert(position: number, element: kendo.drawing.Element): void; opacity(): number; opacity(opacity: number): void; @@ -17923,6 +18195,7 @@ declare namespace kendo.dataviz.drawing { cursor?: string; opacity?: number; pdf?: kendo.drawing.PDFOptions; + tooltip?: kendo.drawing.TooltipOptions; transform?: kendo.geometry.Transformation; visible?: boolean; } @@ -17946,6 +18219,7 @@ declare namespace kendo.dataviz.drawing { clip(): kendo.drawing.Path; clip(clip: kendo.drawing.Path): void; clippedBBox(): kendo.geometry.Rect; + containsPoint(point: kendo.geometry.Point): boolean; opacity(): number; opacity(opacity: number): void; src(): string; @@ -17964,6 +18238,7 @@ declare namespace kendo.dataviz.drawing { clip?: kendo.drawing.Path; cursor?: string; opacity?: number; + tooltip?: kendo.drawing.TooltipOptions; transform?: kendo.geometry.Transformation; visible?: boolean; } @@ -18053,6 +18328,7 @@ declare namespace kendo.dataviz.drawing { clip(clip: kendo.drawing.Path): void; clippedBBox(): kendo.geometry.Rect; close(): kendo.drawing.MultiPath; + containsPoint(point: kendo.geometry.Point): boolean; curveTo(controlOut: any, controlIn: any, endPoint: any): kendo.drawing.MultiPath; curveTo(controlOut: any, controlIn: any, endPoint: kendo.geometry.Point): kendo.drawing.MultiPath; curveTo(controlOut: any, controlIn: kendo.geometry.Point, endPoint: any): kendo.drawing.MultiPath; @@ -18085,6 +18361,7 @@ declare namespace kendo.dataviz.drawing { fill?: kendo.drawing.FillOptions; opacity?: number; stroke?: kendo.drawing.StrokeOptions; + tooltip?: kendo.drawing.TooltipOptions; transform?: kendo.geometry.Transformation; visible?: boolean; } @@ -18158,6 +18435,7 @@ declare namespace kendo.dataviz.drawing { clip(clip: kendo.drawing.Path): void; clippedBBox(): kendo.geometry.Rect; close(): kendo.drawing.Path; + containsPoint(point: kendo.geometry.Point): boolean; curveTo(controlOut: any, controlIn: any, endPoint: any): kendo.drawing.Path; curveTo(controlOut: any, controlIn: any, endPoint: kendo.geometry.Point): kendo.drawing.Path; curveTo(controlOut: any, controlIn: kendo.geometry.Point, endPoint: any): kendo.drawing.Path; @@ -18190,6 +18468,7 @@ declare namespace kendo.dataviz.drawing { fill?: kendo.drawing.FillOptions; opacity?: number; stroke?: kendo.drawing.StrokeOptions; + tooltip?: kendo.drawing.TooltipOptions; transform?: kendo.geometry.Transformation; visible?: boolean; } @@ -18246,6 +18525,7 @@ declare namespace kendo.dataviz.drawing { clip(): kendo.drawing.Path; clip(clip: kendo.drawing.Path): void; clippedBBox(): kendo.geometry.Rect; + containsPoint(point: kendo.geometry.Point): boolean; geometry(): kendo.geometry.Rect; geometry(value: kendo.geometry.Rect): void; fill(color: string, opacity?: number): kendo.drawing.Rect; @@ -18266,6 +18546,7 @@ declare namespace kendo.dataviz.drawing { fill?: kendo.drawing.FillOptions; opacity?: number; stroke?: kendo.drawing.StrokeOptions; + tooltip?: kendo.drawing.TooltipOptions; transform?: kendo.geometry.Transformation; visible?: boolean; } @@ -18336,18 +18617,43 @@ declare namespace kendo.dataviz.drawing { clear(): void; draw(element: kendo.drawing.Element): void; eventTarget(e: any): kendo.drawing.Element; + hideTooltip(): void; resize(force?: boolean): void; + showTooltip(element: kendo.drawing.Element, options?: any): void; } + interface SurfaceTooltipAnimationClose { + effects?: string; + duration?: number; + } + + interface SurfaceTooltipAnimationOpen { + effects?: string; + duration?: number; + } + + interface SurfaceTooltipAnimation { + close?: SurfaceTooltipAnimationClose; + open?: SurfaceTooltipAnimationOpen; + } + + interface SurfaceTooltip { + animation?: boolean|SurfaceTooltipAnimation; + appendTo?: string|JQuery; + } + interface SurfaceOptions { name?: string; type?: string; height?: string; width?: string; + tooltip?: SurfaceTooltip; click?(e: SurfaceClickEvent): void; mouseenter?(e: SurfaceMouseenterEvent): void; mouseleave?(e: SurfaceMouseleaveEvent): void; + tooltipClose?(e: SurfaceTooltipCloseEvent): void; + tooltipOpen?(e: SurfaceTooltipOpenEvent): void; } interface SurfaceEvent { sender: Surface; @@ -18370,6 +18676,16 @@ declare namespace kendo.dataviz.drawing { originalEvent?: any; } + interface SurfaceTooltipCloseEvent extends SurfaceEvent { + element?: kendo.drawing.Element; + target?: kendo.drawing.Element; + } + + interface SurfaceTooltipOpenEvent extends SurfaceEvent { + element?: kendo.drawing.Element; + target?: kendo.drawing.Element; + } + class Text extends kendo.drawing.Element { @@ -18384,6 +18700,7 @@ declare namespace kendo.dataviz.drawing { clip(): kendo.drawing.Path; clip(clip: kendo.drawing.Path): void; clippedBBox(): kendo.geometry.Rect; + containsPoint(point: kendo.geometry.Point): boolean; content(): string; content(value: string): void; fill(color: string, opacity?: number): kendo.drawing.Text; @@ -18407,6 +18724,7 @@ declare namespace kendo.dataviz.drawing { font?: string; opacity?: number; stroke?: kendo.drawing.StrokeOptions; + tooltip?: kendo.drawing.TooltipOptions; transform?: kendo.geometry.Transformation; visible?: boolean; } @@ -18417,6 +18735,28 @@ declare namespace kendo.dataviz.drawing { } + interface TooltipOptions { + + + + autoHide?: boolean; + content?: string|Function; + position?: string; + height?: number|string; + hideDelay?: number; + offset?: number; + shared?: boolean; + showAfter?: number; + showOn?: string; + width?: number|string; + + + + + } + + + } interface HTMLElement { @@ -18501,6 +18841,10 @@ interface JQuery { kendoEditor(options: kendo.ui.EditorOptions): JQuery; data(key: "kendoEditor"): kendo.ui.Editor; + kendoFilterMenu(): JQuery; + kendoFilterMenu(options: kendo.ui.FilterMenuOptions): JQuery; + data(key: "kendoFilterMenu"): kendo.ui.FilterMenu; + kendoFlatColorPicker(): JQuery; kendoFlatColorPicker(options: kendo.ui.FlatColorPickerOptions): JQuery; data(key: "kendoFlatColorPicker"): kendo.ui.FlatColorPicker; From 70d5dcff6f427b0ed6618ac9e3ec095e397bbd75 Mon Sep 17 00:00:00 2001 From: Paul Brohman Date: Sat, 14 May 2016 12:29:31 -0400 Subject: [PATCH 054/402] Updating the IStateOptions.reload to allow string or IState (#9298) `reload` allows for a string based state or a state object ``` reload (v0.2.5) - {boolean=false|string|object}, If true will force transition even if no state or params have changed. It will reload the resolves and views of the current state and parent states. If reload is a string (or state object), the state object is fetched (by name, or object reference); and \ the transition reloads the resolves and views for that matched state, and all its children states. ``` --- angular-ui-router/angular-ui-router.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/angular-ui-router/angular-ui-router.d.ts b/angular-ui-router/angular-ui-router.d.ts index 0512528097..945d07fb73 100644 --- a/angular-ui-router/angular-ui-router.d.ts +++ b/angular-ui-router/angular-ui-router.d.ts @@ -229,9 +229,9 @@ declare namespace angular.ui { */ notify?: boolean; /** - * {boolean=false}, If true will force transition even if the state or params have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd use this when you want to force a reload when everything is the same, including search params. + * {boolean=false|string|IState}, If true will force transition even if the state or params have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd use this when you want to force a reload when everything is the same, including search params. */ - reload?: boolean; + reload?: boolean | string | IState; } interface IHrefOptions { From 4f36f98aa3de0c5f320e674ba39a43081154f3b8 Mon Sep 17 00:00:00 2001 From: game7 Date: Sat, 14 May 2016 09:41:08 -0700 Subject: [PATCH 055/402] underscore.string to include decapitalize function (#9302) Update underscore.string.d.ts to include decapitalize function --- underscore.string/underscore.string.d.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/underscore.string/underscore.string.d.ts b/underscore.string/underscore.string.d.ts index 97c01579e1..ef4033d683 100644 --- a/underscore.string/underscore.string.d.ts +++ b/underscore.string/underscore.string.d.ts @@ -66,6 +66,13 @@ interface UnderscoreStringStaticExports { * @param str */ capitalize(str: string): string; + + /** + * Converts first letter of the string to lowercase. + * ('Foo Bar') => 'foo Bar' + * @param str + */ + decapitalize(str: string): string; /** * Chop a string into pieces. From eeede9d1ad03e27fe3537334c17ff09a77ac5819 Mon Sep 17 00:00:00 2001 From: Masahiro Wakame Date: Sun, 15 May 2016 01:59:20 +0900 Subject: [PATCH 056/402] split node-v4 definitions (#9341) --- node/node-4-tests.ts | 814 ++++++++++++++ node/node-4.d.ts | 2390 ++++++++++++++++++++++++++++++++++++++++++ node/node.d.ts | 4 +- 3 files changed, 3206 insertions(+), 2 deletions(-) create mode 100644 node/node-4-tests.ts create mode 100644 node/node-4.d.ts diff --git a/node/node-4-tests.ts b/node/node-4-tests.ts new file mode 100644 index 0000000000..8ead0224a2 --- /dev/null +++ b/node/node-4-tests.ts @@ -0,0 +1,814 @@ +/// +import * as assert from "assert"; +import * as fs from "fs"; +import * as events from "events"; +import * as zlib from "zlib"; +import * as url from "url"; +import * as util from "util"; +import * as crypto from "crypto"; +import * as tls from "tls"; +import * as http from "http"; +import * as https from "https"; +import * as net from "net"; +import * as tty from "tty"; +import * as dgram from "dgram"; +import * as querystring from "querystring"; +import * as path from "path"; +import * as readline from "readline"; +import * as childProcess from "child_process"; +import * as cluster from "cluster"; +import * as os from "os"; +import * as vm from "vm"; +// Specifically test buffer module regression. +import {Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer} from "buffer"; + +assert(1 + 1 - 2 === 0, "The universe isn't how it should."); + +assert.deepEqual({ x: { y: 3 } }, { x: { y: 3 } }, "DEEP WENT DERP"); + +assert.equal(3, "3", "uses == comparator"); + +assert.notStrictEqual(2, "2", "uses === comparator"); + +assert.notDeepStrictEqual({ x: { y: "3" } }, { x: { y: 3 } }, "uses === comparator"); + +assert.throws(() => { throw "a hammer at your face"; }, undefined, "DODGED IT"); + +assert.doesNotThrow(() => { + const b = false; + if (b) { throw "a hammer at your face"; } +}, undefined, "What the...*crunch*"); + +//////////////////////////////////////////////////// +/// Events tests : http://nodejs.org/api/events.html +//////////////////////////////////////////////////// + +namespace events_tests { + let emitter: events.EventEmitter; + let event: string; + let listener: Function; + let any: any; + + { + let result: events.EventEmitter; + + result = emitter.addListener(event, listener); + result = emitter.on(event, listener); + result = emitter.once(event, listener); + result = emitter.removeListener(event, listener); + result = emitter.removeAllListeners(); + result = emitter.removeAllListeners(event); + result = emitter.setMaxListeners(42); + } + + { + let result: number; + + result = events.EventEmitter.defaultMaxListeners; + result = events.EventEmitter.listenerCount(emitter, event); // deprecated + + result = emitter.getMaxListeners(); + result = emitter.listenerCount(event); + } + + { + let result: Function[]; + + result = emitter.listeners(event); + } + + { + let result: boolean; + + result = emitter.emit(event); + result = emitter.emit(event, any); + result = emitter.emit(event, any, any); + result = emitter.emit(event, any, any, any); + } +} + +//////////////////////////////////////////////////// +/// File system tests : http://nodejs.org/api/fs.html +//////////////////////////////////////////////////// +fs.writeFile("thebible.txt", + "Do unto others as you would have them do unto you.", + assert.ifError); + +fs.write(1234, "test"); + +fs.writeFile("Harry Potter", + "\"You be wizzing, Harry,\" jived Dumbledore.", + { + encoding: "ascii" + }, + assert.ifError); + +var content: string, + buffer: Buffer; + +content = fs.readFileSync('testfile', 'utf8'); +content = fs.readFileSync('testfile', {encoding : 'utf8'}); +buffer = fs.readFileSync('testfile'); +buffer = fs.readFileSync('testfile', {flag : 'r'}); +fs.readFile('testfile', 'utf8', (err, data) => content = data); +fs.readFile('testfile', {encoding : 'utf8'}, (err, data) => content = data); +fs.readFile('testfile', (err, data) => buffer = data); +fs.readFile('testfile', {flag : 'r'}, (err, data) => buffer = data); + +class Networker extends events.EventEmitter { + constructor() { + super(); + + this.emit("mingling"); + } +} + +var errno: number; +fs.readFile('testfile', (err, data) => { + if (err && err.errno) { + errno = err.errno; + } +}); + +fs.mkdtemp('/tmp/foo-', (err, folder) => { + console.log(folder); + // Prints: /tmp/foo-itXde2 +}); + +var tempDir: string; +tempDir = fs.mkdtempSync('/tmp/foo-'); + +/////////////////////////////////////////////////////// +/// Buffer tests : https://nodejs.org/api/buffer.html +/////////////////////////////////////////////////////// + +function bufferTests() { + var utf8Buffer = new Buffer('test'); + var base64Buffer = new Buffer('','base64'); + var octets: Uint8Array = null; + var octetBuffer = new Buffer(octets); + var sharedBuffer = new Buffer(octets.buffer); + var copiedBuffer = new Buffer(utf8Buffer); + console.log(Buffer.isBuffer(octetBuffer)); + console.log(Buffer.isEncoding('utf8')); + console.log(Buffer.byteLength('xyz123')); + console.log(Buffer.byteLength('xyz123', 'ascii')); + var result1 = Buffer.concat([utf8Buffer, base64Buffer]); + var result2 = Buffer.concat([utf8Buffer, base64Buffer], 9999999); + + // Class Method: Buffer.from(array) + { + const buf: Buffer = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); + } + + // Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) + { + const arr: Uint16Array = new Uint16Array(2); + arr[0] = 5000; + arr[1] = 4000; + + let buf: Buffer; + buf = Buffer.from(arr.buffer); + buf = Buffer.from(arr.buffer, 1); + buf = Buffer.from(arr.buffer, 0, 1); + } + + // Class Method: Buffer.from(buffer) + { + const buf1: Buffer = Buffer.from('buffer'); + const buf2: Buffer = Buffer.from(buf1); + } + + // Class Method: Buffer.from(str[, encoding]) + { + const buf1: Buffer = Buffer.from('this is a tést'); + const buf2: Buffer = Buffer.from('7468697320697320612074c3a97374', 'hex'); + } + + // Test that TS 1.6 works with the 'as Buffer' annotation + // on isBuffer. + var a: Buffer | number; + a = new Buffer(10); + if (Buffer.isBuffer(a)) { + a.writeUInt8(3, 4); + } + + // write* methods return offsets. + var b = new Buffer(16); + var result: number = b.writeUInt32LE(0, 0); + result = b.writeUInt16LE(0, 4); + result = b.writeUInt8(0, 6); + result = b.writeInt8(0, 7); + result = b.writeDoubleLE(0, 8); + + // fill returns the input buffer. + b.fill('a').fill('b'); + + { + let buffer = new Buffer('123'); + let index: number; + index = buffer.indexOf("23"); + index = buffer.indexOf("23", 1); + index = buffer.indexOf(23); + index = buffer.indexOf(buffer); + } + + // Imported Buffer from buffer module works properly + { + let b = new ImportedBuffer('123'); + b.writeUInt8(0, 6); + let sb = new ImportedSlowBuffer(43); + b.writeUInt8(0, 6); + } + + // Buffer has Uint8Array's buffer field (an ArrayBuffer). + { + let buffer = new Buffer('123'); + let octets = new Uint8Array(buffer.buffer); + } +} + + +//////////////////////////////////////////////////// +/// Url tests : http://nodejs.org/api/url.html +//////////////////////////////////////////////////// + +url.format(url.parse('http://www.example.com/xyz')); + +// https://google.com/search?q=you're%20a%20lizard%2C%20gary +url.format({ + protocol: 'https', + host: "google.com", + pathname: 'search', + query: { q: "you're a lizard, gary" } +}); + +var helloUrl = url.parse('http://example.com/?hello=world', true) +assert.equal(helloUrl.query.hello, 'world'); + + +// Old and new util.inspect APIs +util.inspect(["This is nice"], false, 5); +util.inspect(["This is nice"], { colors: true, depth: 5, customInspect: false }); + +//////////////////////////////////////////////////// +/// Stream tests : http://nodejs.org/api/stream.html +//////////////////////////////////////////////////// + +// http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options +function stream_readable_pipe_test() { + var r = fs.createReadStream('file.txt'); + var z = zlib.createGzip(); + var w = fs.createWriteStream('file.txt.gz'); + r.pipe(z).pipe(w); + r.close(); +} + +//////////////////////////////////////////////////// +/// Crypto tests : http://nodejs.org/api/crypto.html +//////////////////////////////////////////////////// + +var hmacResult: string = crypto.createHmac('md5', 'hello').update('world').digest('hex'); + +{ + let hmac: crypto.Hmac; + (hmac = crypto.createHmac('md5', 'hello')).end('world', 'utf8', () => { + let hash: Buffer|string = hmac.read(); + }); +} + +function crypto_cipher_decipher_string_test() { + var key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); + var clearText:string = "This is the clear text."; + var cipher:crypto.Cipher = crypto.createCipher("aes-128-ecb", key); + var cipherText:string = cipher.update(clearText, "utf8", "hex"); + cipherText += cipher.final("hex"); + + var decipher:crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); + var clearText2:string = decipher.update(cipherText, "hex", "utf8"); + clearText2 += decipher.final("utf8"); + + assert.equal(clearText2, clearText); +} + +function crypto_cipher_decipher_buffer_test() { + var key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); + var clearText:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]); + var cipher:crypto.Cipher = crypto.createCipher("aes-128-ecb", key); + var cipherBuffers:Buffer[] = []; + cipherBuffers.push(cipher.update(clearText)); + cipherBuffers.push(cipher.final()); + + var cipherText:Buffer = Buffer.concat(cipherBuffers); + + var decipher:crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); + var decipherBuffers:Buffer[] = []; + decipherBuffers.push(decipher.update(cipherText)); + decipherBuffers.push(decipher.final()); + + var clearText2:Buffer = Buffer.concat(decipherBuffers); + + assert.deepEqual(clearText2, clearText); +} + +//////////////////////////////////////////////////// +/// TLS tests : http://nodejs.org/api/tls.html +//////////////////////////////////////////////////// + +var ctx: tls.SecureContext = tls.createSecureContext({ + key: "NOT REALLY A KEY", + cert: "SOME CERTIFICATE", +}); +var blah = ctx.context; + +var tlsOpts: tls.TlsOptions = { + host: "127.0.0.1", + port: 55 +}; +var tlsSocket = tls.connect(tlsOpts); + + +//////////////////////////////////////////////////// + +// Make sure .listen() and .close() retuern a Server instance +http.createServer().listen(0).close().address(); +net.createServer().listen(0).close().address(); + +var request = http.request('http://0.0.0.0'); +request.once('error', function () {}); +request.setNoDelay(true); +request.abort(); + +//////////////////////////////////////////////////// +/// Http tests : http://nodejs.org/api/http.html +//////////////////////////////////////////////////// +namespace http_tests { + // Status codes + var code = 100; + var codeMessage = http.STATUS_CODES['400']; + var codeMessage = http.STATUS_CODES[400]; + + var agent: http.Agent = new http.Agent({ + keepAlive: true, + keepAliveMsecs: 10000, + maxSockets: Infinity, + maxFreeSockets: 256 + }); + + var agent: http.Agent = http.globalAgent; + + http.request({ + agent: false + }); + http.request({ + agent: agent + }); + http.request({ + agent: undefined + }); +} + +//////////////////////////////////////////////////// +/// Https tests : http://nodejs.org/api/https.html +//////////////////////////////////////////////////// +namespace https_tests { + var agent: https.Agent = new https.Agent({ + keepAlive: true, + keepAliveMsecs: 10000, + maxSockets: Infinity, + maxFreeSockets: 256, + maxCachedSessions: 100 + }); + + var agent: https.Agent = https.globalAgent; + + https.request({ + agent: false + }); + https.request({ + agent: agent + }); + https.request({ + agent: undefined + }); +} + +//////////////////////////////////////////////////// +/// TTY tests : http://nodejs.org/api/tty.html +//////////////////////////////////////////////////// + +namespace tty_tests { + let rs: tty.ReadStream; + let ws: tty.WriteStream; + + let rsIsRaw: boolean = rs.isRaw; + rs.setRawMode(true); + + let wsColumns: number = ws.columns; + let wsRows: number = ws.rows; + + let isTTY: boolean = tty.isatty(1); +} + +//////////////////////////////////////////////////// +/// Dgram tests : http://nodejs.org/api/dgram.html +//////////////////////////////////////////////////// + +var ds: dgram.Socket = dgram.createSocket("udp4", (msg: Buffer, rinfo: dgram.RemoteInfo): void => { +}); +var ai: dgram.AddressInfo = ds.address(); +ds.send(new Buffer("hello"), 0, 5, 5000, "127.0.0.1", (error: Error, bytes: number): void => { +}); + +//////////////////////////////////////////////////// +///Querystring tests : https://nodejs.org/api/querystring.html +//////////////////////////////////////////////////// + +namespace querystring_tests { + type SampleObject = {a: string; b: number;} + + { + let obj: SampleObject; + let sep: string; + let eq: string; + let options: querystring.StringifyOptions; + let result: string; + + result = querystring.stringify(obj); + result = querystring.stringify(obj, sep); + result = querystring.stringify(obj, sep, eq); + result = querystring.stringify(obj, sep, eq); + result = querystring.stringify(obj, sep, eq, options); + } + + { + let str: string; + let sep: string; + let eq: string; + let options: querystring.ParseOptions; + let result: SampleObject; + + result = querystring.parse(str); + result = querystring.parse(str, sep); + result = querystring.parse(str, sep, eq); + result = querystring.parse(str, sep, eq, options); + } + + { + let str: string; + let result: string; + + result = querystring.escape(str); + result = querystring.unescape(str); + } +} + +//////////////////////////////////////////////////// +/// path tests : http://nodejs.org/api/path.html +//////////////////////////////////////////////////// + +namespace path_tests { + + path.normalize('/foo/bar//baz/asdf/quux/..'); + + path.join('/foo', 'bar', 'baz/asdf', 'quux', '..'); + // returns + //'/foo/bar/baz/asdf' + + try { + path.join('foo', {}, 'bar'); + } + catch(error) { + + } + + path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile'); + //Is similar to: + // + //cd foo/bar + //cd /tmp/file/ + //cd .. + // cd a/../subfile + //pwd + + path.resolve('/foo/bar', './baz') + // returns + // '/foo/bar/baz' + + path.resolve('/foo/bar', '/tmp/file/') + // returns + // '/tmp/file' + + path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif') + // if currently in /home/myself/node, it returns + // '/home/myself/node/wwwroot/static_files/gif/image.gif' + + path.isAbsolute('/foo/bar') // true + path.isAbsolute('/baz/..') // true + path.isAbsolute('qux/') // false + path.isAbsolute('.') // false + + path.isAbsolute('//server') // true + path.isAbsolute('C:/foo/..') // true + path.isAbsolute('bar\\baz') // false + path.isAbsolute('.') // false + + path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb') +// returns +// '..\\..\\impl\\bbb' + + path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb') +// returns +// '../../impl/bbb' + + path.dirname('/foo/bar/baz/asdf/quux') +// returns +// '/foo/bar/baz/asdf' + + path.basename('/foo/bar/baz/asdf/quux.html') +// returns +// 'quux.html' + + path.basename('/foo/bar/baz/asdf/quux.html', '.html') +// returns +// 'quux' + + path.extname('index.html') +// returns +// '.html' + + path.extname('index.coffee.md') +// returns +// '.md' + + path.extname('index.') +// returns +// '.' + + path.extname('index') +// returns +// '' + + 'foo/bar/baz'.split(path.sep) +// returns +// ['foo', 'bar', 'baz'] + + 'foo\\bar\\baz'.split(path.sep) +// returns +// ['foo', 'bar', 'baz'] + + console.log(process.env.PATH) +// '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin' + + process.env.PATH.split(path.delimiter) +// returns +// ['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin'] + + console.log(process.env.PATH) +// 'C:\Windows\system32;C:\Windows;C:\Program Files\nodejs\' + + process.env.PATH.split(path.delimiter) +// returns +// ['C:\Windows\system32', 'C:\Windows', 'C:\Program Files\nodejs\'] + + path.parse('/home/user/dir/file.txt') +// returns +// { +// root : "/", +// dir : "/home/user/dir", +// base : "file.txt", +// ext : ".txt", +// name : "file" +// } + + path.parse('C:\\path\\dir\\index.html') +// returns +// { +// root : "C:\", +// dir : "C:\path\dir", +// base : "index.html", +// ext : ".html", +// name : "index" +// } + + path.format({ + root : "/", + dir : "/home/user/dir", + base : "file.txt", + ext : ".txt", + name : "file" + }); +// returns +// '/home/user/dir/file.txt' +} + +//////////////////////////////////////////////////// +/// readline tests : https://nodejs.org/api/readline.html +//////////////////////////////////////////////////// + +namespace readline_tests { + let rl: readline.ReadLine; + + { + let options: readline.ReadLineOptions; + let input: NodeJS.ReadableStream; + let output: NodeJS.WritableStream; + let completer: readline.Completer; + let terminal: boolean; + + let result: readline.ReadLine; + + result = readline.createInterface(options); + result = readline.createInterface(input); + result = readline.createInterface(input, output); + result = readline.createInterface(input, output, completer); + result = readline.createInterface(input, output, completer, terminal); + } + + { + let prompt: string; + + rl.setPrompt(prompt); + } + + { + let preserveCursor: boolean; + + rl.prompt(); + rl.prompt(preserveCursor); + } + + { + let query: string; + let callback: (answer: string) => void; + + rl.question(query, callback); + } + + { + let result: readline.ReadLine; + + result = rl.pause(); + } + + { + let result: readline.ReadLine; + + result = rl.resume(); + } + + { + rl.close(); + } + + { + let data: string|Buffer; + let key: readline.Key; + + rl.write(data); + rl.write(null, key); + } + + { + let stream: NodeJS.WritableStream; + let x: number; + let y: number; + + readline.cursorTo(stream, x, y); + } + + { + let stream: NodeJS.WritableStream; + let dx: number|string; + let dy: number|string; + + readline.moveCursor(stream, dx, dy); + } + + { + let stream: NodeJS.WritableStream; + let dir: number; + + readline.clearLine(stream, dir); + } + + { + let stream: NodeJS.WritableStream; + + readline.clearScreenDown(stream); + } +} + +////////////////////////////////////////////////////////////////////// +/// Child Process tests: https://nodejs.org/api/child_process.html /// +////////////////////////////////////////////////////////////////////// + +childProcess.exec("echo test"); +childProcess.spawnSync("echo test"); + +////////////////////////////////////////////////////////////////////// +/// cluster tests: https://nodejs.org/api/cluster.html /// +////////////////////////////////////////////////////////////////////// + +cluster.fork(); +Object.keys(cluster.workers).forEach(key => { + const worker = cluster.workers[key]; + if (worker.isDead()) { + console.log('worker %d is dead', worker.process.pid); + } +}); + +//////////////////////////////////////////////////// +/// os tests : https://nodejs.org/api/os.html +//////////////////////////////////////////////////// + +namespace os_tests { + { + let result: string; + + result = os.tmpdir(); + result = os.homedir(); + result = os.endianness(); + result = os.hostname(); + result = os.type(); + result = os.platform(); + result = os.arch(); + result = os.release(); + result = os.EOL; + } + + { + let result: number; + + result = os.uptime(); + result = os.totalmem(); + result = os.freemem(); + } + + { + let result: number[]; + + result = os.loadavg(); + } + + { + let result: os.CpuInfo[]; + + result = os.cpus(); + } + + { + let result: {[index: string]: os.NetworkInterfaceInfo[]}; + + result = os.networkInterfaces(); + } +} + +//////////////////////////////////////////////////// +/// vm tests : https://nodejs.org/api/vm.html +//////////////////////////////////////////////////// + +namespace vm_tests { + { + const sandbox = { + animal: 'cat', + count: 2 + }; + + const context = vm.createContext(sandbox); + console.log(vm.isContext(context)); + const script = new vm.Script('count += 1; name = "kitty"'); + + for (let i = 0; i < 10; ++i) { + script.runInContext(context); + } + + console.log(util.inspect(sandbox)); + + vm.runInNewContext('count += 1; name = "kitty"', sandbox); + console.log(util.inspect(sandbox)); + } + + { + const sandboxes = [{}, {}, {}]; + + const script = new vm.Script('globalVar = "set"'); + + sandboxes.forEach((sandbox) => { + script.runInNewContext(sandbox); + script.runInThisContext(); + }); + + console.log(util.inspect(sandboxes)); + + var localVar = 'initial value'; + vm.runInThisContext('localVar = "vm";'); + + console.log(localVar); + } + + { + const Debug = vm.runInDebugContext('Debug'); + Debug.scripts().forEach(function(script: any) { console.log(script.name); }); + } +} diff --git a/node/node-4.d.ts b/node/node-4.d.ts new file mode 100644 index 0000000000..a9d4709a91 --- /dev/null +++ b/node/node-4.d.ts @@ -0,0 +1,2390 @@ +// Type definitions for Node.js v4.x +// Project: http://nodejs.org/ +// Definitions by: Microsoft TypeScript , DefinitelyTyped +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/************************************************ +* * +* Node.js v4.x API * +* * +************************************************/ + +interface Error { + stack?: string; +} + + +// compat for TypeScript 1.8 +// if you use with --target es3 or --target es5 and use below definitions, +// use the lib.es6.d.ts that is bundled with TypeScript 1.8. +interface MapConstructor {} +interface WeakMapConstructor {} +interface SetConstructor {} +interface WeakSetConstructor {} + +/************************************************ +* * +* GLOBAL * +* * +************************************************/ +declare var process: NodeJS.Process; +declare var global: NodeJS.Global; + +declare var __filename: string; +declare var __dirname: string; + +declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; +declare function clearTimeout(timeoutId: NodeJS.Timer): void; +declare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; +declare function clearInterval(intervalId: NodeJS.Timer): void; +declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): any; +declare function clearImmediate(immediateId: any): void; + +interface NodeRequireFunction { + (id: string): any; +} + +interface NodeRequire extends NodeRequireFunction { + resolve(id:string): string; + cache: any; + extensions: any; + main: any; +} + +declare var require: NodeRequire; + +interface NodeModule { + exports: any; + require: NodeRequireFunction; + id: string; + filename: string; + loaded: boolean; + parent: any; + children: any[]; +} + +declare var module: NodeModule; + +// Same as module.exports +declare var exports: any; +declare var SlowBuffer: { + new (str: string, encoding?: string): Buffer; + new (size: number): Buffer; + new (size: Uint8Array): Buffer; + new (array: any[]): Buffer; + prototype: Buffer; + isBuffer(obj: any): boolean; + byteLength(string: string, encoding?: string): number; + concat(list: Buffer[], totalLength?: number): Buffer; +}; + + +// Buffer class +type BufferEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "binary" | "hex"; +interface Buffer extends NodeBuffer {} + +/** + * Raw data is stored in instances of the Buffer class. + * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. + * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + */ +declare var Buffer: { + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + */ + new (str: string, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + */ + new (size: number): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + new (array: Uint8Array): Buffer; + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + */ + new (arrayBuffer: ArrayBuffer): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + new (array: any[]): Buffer; + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + */ + new (buffer: Buffer): Buffer; + prototype: Buffer; + /** + * Allocates a new Buffer using an {array} of octets. + * + * @param array + */ + from(array: any[]): Buffer; + /** + * When passed a reference to the .buffer property of a TypedArray instance, + * the newly created Buffer will share the same allocated memory as the TypedArray. + * The optional {byteOffset} and {length} arguments specify a memory range + * within the {arrayBuffer} that will be shared by the Buffer. + * + * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() + * @param byteOffset + * @param length + */ + from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?:number): Buffer; + /** + * Copies the passed {buffer} data onto a new Buffer instance. + * + * @param buffer + */ + from(buffer: Buffer): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + * + * @param str + */ + from(str: string, encoding?: string): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + isEncoding(encoding: string): boolean; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + byteLength(string: string, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + concat(list: Buffer[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + compare(buf1: Buffer, buf2: Buffer): number; +}; + +/************************************************ +* * +* GLOBAL INTERFACES * +* * +************************************************/ +declare namespace NodeJS { + export interface ErrnoException extends Error { + errno?: number; + code?: string; + path?: string; + syscall?: string; + stack?: string; + } + + export interface EventEmitter { + addListener(event: string, listener: Function): this; + on(event: string, listener: Function): this; + once(event: string, listener: Function): this; + removeListener(event: string, listener: Function): this; + removeAllListeners(event?: string): this; + setMaxListeners(n: number): this; + getMaxListeners(): number; + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + listenerCount(type: string): number; + } + + export interface ReadableStream extends EventEmitter { + readable: boolean; + read(size?: number): string|Buffer; + setEncoding(encoding: string): void; + pause(): void; + resume(): void; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: T): void; + unshift(chunk: string): void; + unshift(chunk: Buffer): void; + wrap(oldStream: ReadableStream): ReadableStream; + } + + export interface WritableStream extends EventEmitter { + writable: boolean; + write(buffer: Buffer|string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + } + + export interface ReadWriteStream extends ReadableStream, WritableStream {} + + export interface Events extends EventEmitter { } + + export interface Domain extends Events { + run(fn: Function): void; + add(emitter: Events): void; + remove(emitter: Events): void; + bind(cb: (err: Error, data: any) => any): any; + intercept(cb: (data: any) => any): any; + dispose(): void; + + addListener(event: string, listener: Function): this; + on(event: string, listener: Function): this; + once(event: string, listener: Function): this; + removeListener(event: string, listener: Function): this; + removeAllListeners(event?: string): this; + } + + export interface MemoryUsage { + rss: number; + heapTotal: number; + heapUsed: number; + } + + export interface Process extends EventEmitter { + stdout: WritableStream; + stderr: WritableStream; + stdin: ReadableStream; + argv: string[]; + execArgv: string[]; + execPath: string; + abort(): void; + chdir(directory: string): void; + cwd(): string; + env: any; + exit(code?: number): void; + getgid(): number; + setgid(id: number): void; + setgid(id: string): void; + getuid(): number; + setuid(id: number): void; + setuid(id: string): void; + version: string; + versions: { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + openssl: string; + }; + config: { + target_defaults: { + cflags: any[]; + default_configuration: string; + defines: string[]; + include_dirs: string[]; + libraries: string[]; + }; + variables: { + clang: number; + host_arch: string; + node_install_npm: boolean; + node_install_waf: boolean; + node_prefix: string; + node_shared_openssl: boolean; + node_shared_v8: boolean; + node_shared_zlib: boolean; + node_use_dtrace: boolean; + node_use_etw: boolean; + node_use_openssl: boolean; + target_arch: string; + v8_no_strict_aliasing: number; + v8_use_snapshot: boolean; + visibility: string; + }; + }; + kill(pid:number, signal?: string|number): void; + pid: number; + title: string; + arch: string; + platform: string; + memoryUsage(): MemoryUsage; + nextTick(callback: Function): void; + umask(mask?: number): number; + uptime(): number; + hrtime(time?:number[]): number[]; + domain: Domain; + + // Worker + send?(message: any, sendHandle?: any): void; + disconnect(): void; + connected: boolean; + } + + export interface Global { + Array: typeof Array; + ArrayBuffer: typeof ArrayBuffer; + Boolean: typeof Boolean; + Buffer: typeof Buffer; + DataView: typeof DataView; + Date: typeof Date; + Error: typeof Error; + EvalError: typeof EvalError; + Float32Array: typeof Float32Array; + Float64Array: typeof Float64Array; + Function: typeof Function; + GLOBAL: Global; + Infinity: typeof Infinity; + Int16Array: typeof Int16Array; + Int32Array: typeof Int32Array; + Int8Array: typeof Int8Array; + Intl: typeof Intl; + JSON: typeof JSON; + Map: MapConstructor; + Math: typeof Math; + NaN: typeof NaN; + Number: typeof Number; + Object: typeof Object; + Promise: Function; + RangeError: typeof RangeError; + ReferenceError: typeof ReferenceError; + RegExp: typeof RegExp; + Set: SetConstructor; + String: typeof String; + Symbol: Function; + SyntaxError: typeof SyntaxError; + TypeError: typeof TypeError; + URIError: typeof URIError; + Uint16Array: typeof Uint16Array; + Uint32Array: typeof Uint32Array; + Uint8Array: typeof Uint8Array; + Uint8ClampedArray: Function; + WeakMap: WeakMapConstructor; + WeakSet: WeakSetConstructor; + clearImmediate: (immediateId: any) => void; + clearInterval: (intervalId: NodeJS.Timer) => void; + clearTimeout: (timeoutId: NodeJS.Timer) => void; + console: typeof console; + decodeURI: typeof decodeURI; + decodeURIComponent: typeof decodeURIComponent; + encodeURI: typeof encodeURI; + encodeURIComponent: typeof encodeURIComponent; + escape: (str: string) => string; + eval: typeof eval; + global: Global; + isFinite: typeof isFinite; + isNaN: typeof isNaN; + parseFloat: typeof parseFloat; + parseInt: typeof parseInt; + process: Process; + root: Global; + setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => any; + setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer; + setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer; + undefined: typeof undefined; + unescape: (str: string) => string; + gc: () => void; + v8debug?: any; + } + + export interface Timer { + ref() : void; + unref() : void; + } +} + +/** + * @deprecated + */ +interface NodeBuffer extends Uint8Array { + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): any; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer): number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): Buffer; + // TODO: encoding param + indexOf(value: string | number | Buffer, byteOffset?: number): number; + // TODO: entries + // TODO: includes + // TODO: keys + // TODO: values +} + +/************************************************ +* * +* MODULES * +* * +************************************************/ +declare module "buffer" { + export var INSPECT_MAX_BYTES: number; + var BuffType: typeof Buffer; + var SlowBuffType: typeof SlowBuffer; + export { BuffType as Buffer, SlowBuffType as SlowBuffer }; +} + +declare module "querystring" { + export interface StringifyOptions { + encodeURIComponent?: Function; + } + + export interface ParseOptions { + maxKeys?: number; + decodeURIComponent?: Function; + } + + export function stringify(obj: T, sep?: string, eq?: string, options?: StringifyOptions): string; + export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): any; + export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): T; + export function escape(str: string): string; + export function unescape(str: string): string; +} + +declare module "events" { + export class EventEmitter implements NodeJS.EventEmitter { + static EventEmitter: EventEmitter; + static listenerCount(emitter: EventEmitter, event: string): number; // deprecated + static defaultMaxListeners: number; + + addListener(event: string, listener: Function): this; + on(event: string, listener: Function): this; + once(event: string, listener: Function): this; + removeListener(event: string, listener: Function): this; + removeAllListeners(event?: string): this; + setMaxListeners(n: number): this; + getMaxListeners(): number; + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + listenerCount(type: string): number; + } +} + +declare module "http" { + import * as events from "events"; + import * as net from "net"; + import * as stream from "stream"; + + export interface RequestOptions { + protocol?: string; + host?: string; + hostname?: string; + family?: number; + port?: number; + localAddress?: string; + socketPath?: string; + method?: string; + path?: string; + headers?: { [key: string]: any }; + auth?: string; + agent?: Agent|boolean; + } + + export interface Server extends events.EventEmitter, net.Server { + setTimeout(msecs: number, callback: Function): void; + maxHeadersCount: number; + timeout: number; + } + /** + * @deprecated Use IncomingMessage + */ + export interface ServerRequest extends IncomingMessage { + connection: net.Socket; + } + export interface ServerResponse extends events.EventEmitter, stream.Writable { + // Extended base methods + write(buffer: Buffer): boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; + + writeContinue(): void; + writeHead(statusCode: number, reasonPhrase?: string, headers?: any): void; + writeHead(statusCode: number, headers?: any): void; + statusCode: number; + statusMessage: string; + headersSent: boolean; + setHeader(name: string, value: string | string[]): void; + sendDate: boolean; + getHeader(name: string): string; + removeHeader(name: string): void; + write(chunk: any, encoding?: string): any; + addTrailers(headers: any): void; + + // Extended base methods + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + end(data?: any, encoding?: string): void; + } + export interface ClientRequest extends events.EventEmitter, stream.Writable { + // Extended base methods + write(buffer: Buffer): boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; + + write(chunk: any, encoding?: string): void; + abort(): void; + setTimeout(timeout: number, callback?: Function): void; + setNoDelay(noDelay?: boolean): void; + setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; + + setHeader(name: string, value: string | string[]): void; + getHeader(name: string): string; + removeHeader(name: string): void; + addTrailers(headers: any): void; + + // Extended base methods + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + end(data?: any, encoding?: string): void; + } + export interface IncomingMessage extends events.EventEmitter, stream.Readable { + httpVersion: string; + headers: any; + rawHeaders: string[]; + trailers: any; + rawTrailers: any; + setTimeout(msecs: number, callback: Function): NodeJS.Timer; + /** + * Only valid for request obtained from http.Server. + */ + method?: string; + /** + * Only valid for request obtained from http.Server. + */ + url?: string; + /** + * Only valid for response obtained from http.ClientRequest. + */ + statusCode?: number; + /** + * Only valid for response obtained from http.ClientRequest. + */ + statusMessage?: string; + socket: net.Socket; + } + /** + * @deprecated Use IncomingMessage + */ + export interface ClientResponse extends IncomingMessage { } + + export interface AgentOptions { + /** + * Keep sockets around in a pool to be used by other requests in the future. Default = false + */ + keepAlive?: boolean; + /** + * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. + * Only relevant if keepAlive is set to true. + */ + keepAliveMsecs?: number; + /** + * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity + */ + maxSockets?: number; + /** + * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. + */ + maxFreeSockets?: number; + } + + export class Agent { + maxSockets: number; + sockets: any; + requests: any; + + constructor(opts?: AgentOptions); + + /** + * Destroy any sockets that are currently in use by the agent. + * It is usually not necessary to do this. However, if you are using an agent with KeepAlive enabled, + * then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise, + * sockets may hang open for quite a long time before the server terminates them. + */ + destroy(): void; + } + + export var METHODS: string[]; + + export var STATUS_CODES: { + [errorCode: number]: string; + [errorCode: string]: string; + }; + export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) =>void ): Server; + export function createClient(port?: number, host?: string): any; + export function request(options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + export function get(options: any, callback?: (res: IncomingMessage) => void): ClientRequest; + export var globalAgent: Agent; +} + +declare module "cluster" { + import * as child from "child_process"; + import * as events from "events"; + + export interface ClusterSettings { + exec?: string; + args?: string[]; + silent?: boolean; + } + + export interface Address { + address: string; + port: number; + addressType: string; + } + + export class Worker extends events.EventEmitter { + id: string; + process: child.ChildProcess; + suicide: boolean; + send(message: any, sendHandle?: any): void; + kill(signal?: string): void; + destroy(signal?: string): void; + disconnect(): void; + isConnected(): boolean; + isDead(): boolean; + } + + export var settings: ClusterSettings; + export var isMaster: boolean; + export var isWorker: boolean; + export function setupMaster(settings?: ClusterSettings): void; + export function fork(env?: any): Worker; + export function disconnect(callback?: Function): void; + export var worker: Worker; + export var workers: { + [index: string]: Worker + }; + + // Event emitter + export function addListener(event: string, listener: Function): void; + export function on(event: "disconnect", listener: (worker: Worker) => void): void; + export function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): void; + export function on(event: "fork", listener: (worker: Worker) => void): void; + export function on(event: "listening", listener: (worker: Worker, address: any) => void): void; + export function on(event: "message", listener: (worker: Worker, message: any) => void): void; + export function on(event: "online", listener: (worker: Worker) => void): void; + export function on(event: "setup", listener: (settings: any) => void): void; + export function on(event: string, listener: Function): any; + export function once(event: string, listener: Function): void; + export function removeListener(event: string, listener: Function): void; + export function removeAllListeners(event?: string): void; + export function setMaxListeners(n: number): void; + export function listeners(event: string): Function[]; + export function emit(event: string, ...args: any[]): boolean; +} + +declare module "zlib" { + import * as stream from "stream"; + export interface ZlibOptions { chunkSize?: number; windowBits?: number; level?: number; memLevel?: number; strategy?: number; dictionary?: any; } + + export interface Gzip extends stream.Transform { } + export interface Gunzip extends stream.Transform { } + export interface Deflate extends stream.Transform { } + export interface Inflate extends stream.Transform { } + export interface DeflateRaw extends stream.Transform { } + export interface InflateRaw extends stream.Transform { } + export interface Unzip extends stream.Transform { } + + export function createGzip(options?: ZlibOptions): Gzip; + export function createGunzip(options?: ZlibOptions): Gunzip; + export function createDeflate(options?: ZlibOptions): Deflate; + export function createInflate(options?: ZlibOptions): Inflate; + export function createDeflateRaw(options?: ZlibOptions): DeflateRaw; + export function createInflateRaw(options?: ZlibOptions): InflateRaw; + export function createUnzip(options?: ZlibOptions): Unzip; + + export function deflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function deflateSync(buf: Buffer, options?: ZlibOptions): any; + export function deflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function deflateRawSync(buf: Buffer, options?: ZlibOptions): any; + export function gzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function gzipSync(buf: Buffer, options?: ZlibOptions): any; + export function gunzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function gunzipSync(buf: Buffer, options?: ZlibOptions): any; + export function inflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function inflateSync(buf: Buffer, options?: ZlibOptions): any; + export function inflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function inflateRawSync(buf: Buffer, options?: ZlibOptions): any; + export function unzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function unzipSync(buf: Buffer, options?: ZlibOptions): any; + + // Constants + export var Z_NO_FLUSH: number; + export var Z_PARTIAL_FLUSH: number; + export var Z_SYNC_FLUSH: number; + export var Z_FULL_FLUSH: number; + export var Z_FINISH: number; + export var Z_BLOCK: number; + export var Z_TREES: number; + export var Z_OK: number; + export var Z_STREAM_END: number; + export var Z_NEED_DICT: number; + export var Z_ERRNO: number; + export var Z_STREAM_ERROR: number; + export var Z_DATA_ERROR: number; + export var Z_MEM_ERROR: number; + export var Z_BUF_ERROR: number; + export var Z_VERSION_ERROR: number; + export var Z_NO_COMPRESSION: number; + export var Z_BEST_SPEED: number; + export var Z_BEST_COMPRESSION: number; + export var Z_DEFAULT_COMPRESSION: number; + export var Z_FILTERED: number; + export var Z_HUFFMAN_ONLY: number; + export var Z_RLE: number; + export var Z_FIXED: number; + export var Z_DEFAULT_STRATEGY: number; + export var Z_BINARY: number; + export var Z_TEXT: number; + export var Z_ASCII: number; + export var Z_UNKNOWN: number; + export var Z_DEFLATED: number; + export var Z_NULL: number; +} + +declare module "os" { + export interface CpuInfo { + model: string; + speed: number; + times: { + user: number; + nice: number; + sys: number; + idle: number; + irq: number; + }; + } + + export interface NetworkInterfaceInfo { + address: string; + netmask: string; + family: string; + mac: string; + internal: boolean; + } + + export function tmpdir(): string; + export function homedir(): string; + export function endianness(): string; + export function hostname(): string; + export function type(): string; + export function platform(): string; + export function arch(): string; + export function release(): string; + export function uptime(): number; + export function loadavg(): number[]; + export function totalmem(): number; + export function freemem(): number; + export function cpus(): CpuInfo[]; + export function networkInterfaces(): {[index: string]: NetworkInterfaceInfo[]}; + export var EOL: string; +} + +declare module "https" { + import * as tls from "tls"; + import * as events from "events"; + import * as http from "http"; + + export interface ServerOptions { + pfx?: any; + key?: any; + passphrase?: string; + cert?: any; + ca?: any; + crl?: any; + ciphers?: string; + honorCipherOrder?: boolean; + requestCert?: boolean; + rejectUnauthorized?: boolean; + NPNProtocols?: any; + SNICallback?: (servername: string) => any; + } + + export interface RequestOptions extends http.RequestOptions { + pfx?: any; + key?: any; + passphrase?: string; + cert?: any; + ca?: any; + ciphers?: string; + rejectUnauthorized?: boolean; + secureProtocol?: string; + } + + export interface Agent extends http.Agent { } + + export interface AgentOptions extends http.AgentOptions { + maxCachedSessions?: number; + } + + export var Agent: { + new (options?: AgentOptions): Agent; + }; + export interface Server extends tls.Server { } + export function createServer(options: ServerOptions, requestListener?: Function): Server; + export function request(options: RequestOptions, callback?: (res: http.IncomingMessage) =>void ): http.ClientRequest; + export function get(options: RequestOptions, callback?: (res: http.IncomingMessage) =>void ): http.ClientRequest; + export var globalAgent: Agent; +} + +declare module "punycode" { + export function decode(string: string): string; + export function encode(string: string): string; + export function toUnicode(domain: string): string; + export function toASCII(domain: string): string; + export var ucs2: ucs2; + interface ucs2 { + decode(string: string): number[]; + encode(codePoints: number[]): string; + } + export var version: any; +} + +declare module "repl" { + import * as stream from "stream"; + import * as events from "events"; + + export interface ReplOptions { + prompt?: string; + input?: NodeJS.ReadableStream; + output?: NodeJS.WritableStream; + terminal?: boolean; + eval?: Function; + useColors?: boolean; + useGlobal?: boolean; + ignoreUndefined?: boolean; + writer?: Function; + } + export function start(options: ReplOptions): events.EventEmitter; +} + +declare module "readline" { + import * as events from "events"; + import * as stream from "stream"; + + export interface Key { + sequence?: string; + name?: string; + ctrl?: boolean; + meta?: boolean; + shift?: boolean; + } + + export interface ReadLine extends events.EventEmitter { + setPrompt(prompt: string): void; + prompt(preserveCursor?: boolean): void; + question(query: string, callback: (answer: string) => void): void; + pause(): ReadLine; + resume(): ReadLine; + close(): void; + write(data: string|Buffer, key?: Key): void; + } + + export interface Completer { + (line: string): CompleterResult; + (line: string, callback: (err: any, result: CompleterResult) => void): any; + } + + export interface CompleterResult { + completions: string[]; + line: string; + } + + export interface ReadLineOptions { + input: NodeJS.ReadableStream; + output?: NodeJS.WritableStream; + completer?: Completer; + terminal?: boolean; + historySize?: number; + } + + export function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer, terminal?: boolean): ReadLine; + export function createInterface(options: ReadLineOptions): ReadLine; + + export function cursorTo(stream: NodeJS.WritableStream, x: number, y: number): void; + export function moveCursor(stream: NodeJS.WritableStream, dx: number|string, dy: number|string): void; + export function clearLine(stream: NodeJS.WritableStream, dir: number): void; + export function clearScreenDown(stream: NodeJS.WritableStream): void; +} + +declare module "vm" { + export interface Context { } + export interface ScriptOptions { + filename?: string; + lineOffset?: number; + columnOffset?: number; + displayErrors?: boolean; + timeout?: number; + cachedData?: Buffer; + produceCachedData?: boolean; + } + export interface RunningScriptOptions { + filename?: string; + lineOffset?: number; + columnOffset?: number; + displayErrors?: boolean; + timeout?: number; + } + export class Script { + constructor(code: string, options?: ScriptOptions); + runInContext(contextifiedSandbox: Context, options?: RunningScriptOptions): any; + runInNewContext(sandbox?: Context, options?: RunningScriptOptions): any; + runInThisContext(options?: RunningScriptOptions): any; + } + export function createContext(sandbox?: Context): Context; + export function isContext(sandbox: Context): boolean; + export function runInContext(code: string, contextifiedSandbox: Context, options?: RunningScriptOptions): any; + export function runInDebugContext(code: string): any; + export function runInNewContext(code: string, sandbox?: Context, options?: RunningScriptOptions): any; + export function runInThisContext(code: string, options?: RunningScriptOptions): any; +} + +declare module "child_process" { + import * as events from "events"; + import * as stream from "stream"; + + export interface ChildProcess extends events.EventEmitter { + stdin: stream.Writable; + stdout: stream.Readable; + stderr: stream.Readable; + stdio: [stream.Writable, stream.Readable, stream.Readable]; + pid: number; + kill(signal?: string): void; + send(message: any, sendHandle?: any): void; + disconnect(): void; + unref(): void; + } + + export interface SpawnOptions { + cwd?: string; + env?: any; + stdio?: any; + detached?: boolean; + uid?: number; + gid?: number; + shell?: boolean | string; + } + export function spawn(command: string, args?: string[], options?: SpawnOptions): ChildProcess; + + export interface ExecOptions { + cwd?: string; + env?: any; + shell?: string; + timeout?: number; + maxBuffer?: number; + killSignal?: string; + uid?: number; + gid?: number; + } + export interface ExecOptionsWithStringEncoding extends ExecOptions { + encoding: BufferEncoding; + } + export interface ExecOptionsWithBufferEncoding extends ExecOptions { + encoding: string; // specify `null`. + } + export function exec(command: string, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; + export function exec(command: string, options: ExecOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; + // usage. child_process.exec("tsc", {encoding: null as string}, (err, stdout, stderr) => {}); + export function exec(command: string, options: ExecOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; + export function exec(command: string, options: ExecOptions, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; + + export interface ExecFileOptions { + cwd?: string; + env?: any; + timeout?: number; + maxBuffer?: number; + killSignal?: string; + uid?: number; + gid?: number; + } + export interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { + encoding: BufferEncoding; + } + export interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { + encoding: string; // specify `null`. + } + export function execFile(file: string, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; + export function execFile(file: string, options?: ExecFileOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; + // usage. child_process.execFile("file.sh", {encoding: null as string}, (err, stdout, stderr) => {}); + export function execFile(file: string, options?: ExecFileOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; + export function execFile(file: string, options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; + export function execFile(file: string, args?: string[], callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; + export function execFile(file: string, args?: string[], options?: ExecFileOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; + // usage. child_process.execFile("file.sh", ["foo"], {encoding: null as string}, (err, stdout, stderr) => {}); + export function execFile(file: string, args?: string[], options?: ExecFileOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; + export function execFile(file: string, args?: string[], options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; + + export interface ForkOptions { + cwd?: string; + env?: any; + execPath?: string; + execArgv?: string[]; + silent?: boolean; + uid?: number; + gid?: number; + } + export function fork(modulePath: string, args?: string[], options?: ForkOptions): ChildProcess; + + export interface SpawnSyncOptions { + cwd?: string; + input?: string | Buffer; + stdio?: any; + env?: any; + uid?: number; + gid?: number; + timeout?: number; + killSignal?: string; + maxBuffer?: number; + encoding?: string; + shell?: boolean | string; + } + export interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { + encoding: BufferEncoding; + } + export interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { + encoding: string; // specify `null`. + } + export interface SpawnSyncReturns { + pid: number; + output: string[]; + stdout: T; + stderr: T; + status: number; + signal: string; + error: Error; + } + export function spawnSync(command: string): SpawnSyncReturns; + export function spawnSync(command: string, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + export function spawnSync(command: string, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + export function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; + export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptions): SpawnSyncReturns; + + export interface ExecSyncOptions { + cwd?: string; + input?: string | Buffer; + stdio?: any; + env?: any; + shell?: string; + uid?: number; + gid?: number; + timeout?: number; + killSignal?: string; + maxBuffer?: number; + encoding?: string; + } + export interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { + encoding: BufferEncoding; + } + export interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { + encoding: string; // specify `null`. + } + export function execSync(command: string): Buffer; + export function execSync(command: string, options?: ExecSyncOptionsWithStringEncoding): string; + export function execSync(command: string, options?: ExecSyncOptionsWithBufferEncoding): Buffer; + export function execSync(command: string, options?: ExecSyncOptions): Buffer; + + export interface ExecFileSyncOptions { + cwd?: string; + input?: string | Buffer; + stdio?: any; + env?: any; + uid?: number; + gid?: number; + timeout?: number; + killSignal?: string; + maxBuffer?: number; + encoding?: string; + } + export interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { + encoding: BufferEncoding; + } + export interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { + encoding: string; // specify `null`. + } + export function execFileSync(command: string): Buffer; + export function execFileSync(command: string, options?: ExecFileSyncOptionsWithStringEncoding): string; + export function execFileSync(command: string, options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; + export function execFileSync(command: string, options?: ExecFileSyncOptions): Buffer; + export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptionsWithStringEncoding): string; + export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; + export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptions): Buffer; +} + +declare module "url" { + export interface Url { + href?: string; + protocol?: string; + auth?: string; + hostname?: string; + port?: string; + host?: string; + pathname?: string; + search?: string; + query?: string | any; + slashes?: boolean; + hash?: string; + path?: string; + } + + export function parse(urlStr: string, parseQueryString?: boolean , slashesDenoteHost?: boolean ): Url; + export function format(url: Url): string; + export function resolve(from: string, to: string): string; +} + +declare module "dns" { + export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) =>void ): string; + export function lookup(domain: string, callback: (err: Error, address: string, family: number) =>void ): string; + export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolve(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolve4(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolve6(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolveMx(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolveTxt(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; + export function reverse(ip: string, callback: (err: Error, domains: string[]) =>void ): string[]; +} + +declare module "net" { + import * as stream from "stream"; + + export interface Socket extends stream.Duplex { + // Extended base methods + write(buffer: Buffer): boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + write(str: string, encoding?: string, fd?: string): boolean; + + connect(port: number, host?: string, connectionListener?: Function): void; + connect(path: string, connectionListener?: Function): void; + bufferSize: number; + setEncoding(encoding?: string): void; + write(data: any, encoding?: string, callback?: Function): void; + destroy(): void; + pause(): void; + resume(): void; + setTimeout(timeout: number, callback?: Function): void; + setNoDelay(noDelay?: boolean): void; + setKeepAlive(enable?: boolean, initialDelay?: number): void; + address(): { port: number; family: string; address: string; }; + unref(): void; + ref(): void; + + remoteAddress: string; + remoteFamily: string; + remotePort: number; + localAddress: string; + localPort: number; + bytesRead: number; + bytesWritten: number; + + // Extended base methods + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + end(data?: any, encoding?: string): void; + } + + export var Socket: { + new (options?: { fd?: string; type?: string; allowHalfOpen?: boolean; }): Socket; + }; + + export interface ListenOptions { + port?: number; + host?: string; + backlog?: number; + path?: string; + exclusive?: boolean; + } + + export interface Server extends Socket { + listen(port: number, hostname?: string, backlog?: number, listeningListener?: Function): Server; + listen(port: number, hostname?: string, listeningListener?: Function): Server; + listen(port: number, backlog?: number, listeningListener?: Function): Server; + listen(port: number, listeningListener?: Function): Server; + listen(path: string, backlog?: number, listeningListener?: Function): Server; + listen(path: string, listeningListener?: Function): Server; + listen(handle: any, backlog?: number, listeningListener?: Function): Server; + listen(handle: any, listeningListener?: Function): Server; + listen(options: ListenOptions, listeningListener?: Function): Server; + close(callback?: Function): Server; + address(): { port: number; family: string; address: string; }; + getConnections(cb: (error: Error, count: number) => void): void; + ref(): Server; + unref(): Server; + maxConnections: number; + connections: number; + } + export function createServer(connectionListener?: (socket: Socket) =>void ): Server; + export function createServer(options?: { allowHalfOpen?: boolean; }, connectionListener?: (socket: Socket) =>void ): Server; + export function connect(options: { port: number, host?: string, localAddress? : string, localPort? : string, family? : number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; + export function connect(port: number, host?: string, connectionListener?: Function): Socket; + export function connect(path: string, connectionListener?: Function): Socket; + export function createConnection(options: { port: number, host?: string, localAddress? : string, localPort? : string, family? : number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; + export function createConnection(port: number, host?: string, connectionListener?: Function): Socket; + export function createConnection(path: string, connectionListener?: Function): Socket; + export function isIP(input: string): number; + export function isIPv4(input: string): boolean; + export function isIPv6(input: string): boolean; +} + +declare module "dgram" { + import * as events from "events"; + + interface RemoteInfo { + address: string; + port: number; + size: number; + } + + interface AddressInfo { + address: string; + family: string; + port: number; + } + + export function createSocket(type: string, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + + interface Socket extends events.EventEmitter { + send(buf: Buffer, offset: number, length: number, port: number, address: string, callback?: (error: Error, bytes: number) => void): void; + bind(port: number, address?: string, callback?: () => void): void; + close(): void; + address(): AddressInfo; + setBroadcast(flag: boolean): void; + setMulticastTTL(ttl: number): void; + setMulticastLoopback(flag: boolean): void; + addMembership(multicastAddress: string, multicastInterface?: string): void; + dropMembership(multicastAddress: string, multicastInterface?: string): void; + } +} + +declare module "fs" { + import * as stream from "stream"; + import * as events from "events"; + + interface Stats { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + dev: number; + ino: number; + mode: number; + nlink: number; + uid: number; + gid: number; + rdev: number; + size: number; + blksize: number; + blocks: number; + atime: Date; + mtime: Date; + ctime: Date; + birthtime: Date; + } + + interface FSWatcher extends events.EventEmitter { + close(): void; + } + + export interface ReadStream extends stream.Readable { + close(): void; + } + export interface WriteStream extends stream.Writable { + close(): void; + bytesWritten: number; + } + + /** + * Asynchronous rename. + * @param oldPath + * @param newPath + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function rename(oldPath: string, newPath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + /** + * Synchronous rename + * @param oldPath + * @param newPath + */ + export function renameSync(oldPath: string, newPath: string): void; + export function truncate(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function truncate(path: string, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function truncateSync(path: string, len?: number): void; + export function ftruncate(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function ftruncate(fd: number, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function ftruncateSync(fd: number, len?: number): void; + export function chown(path: string, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function chownSync(path: string, uid: number, gid: number): void; + export function fchown(fd: number, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function fchownSync(fd: number, uid: number, gid: number): void; + export function lchown(path: string, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function lchownSync(path: string, uid: number, gid: number): void; + export function chmod(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function chmod(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function chmodSync(path: string, mode: number): void; + export function chmodSync(path: string, mode: string): void; + export function fchmod(fd: number, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function fchmod(fd: number, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function fchmodSync(fd: number, mode: number): void; + export function fchmodSync(fd: number, mode: string): void; + export function lchmod(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function lchmod(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function lchmodSync(path: string, mode: number): void; + export function lchmodSync(path: string, mode: string): void; + export function stat(path: string, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; + export function lstat(path: string, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; + export function fstat(fd: number, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; + export function statSync(path: string): Stats; + export function lstatSync(path: string): Stats; + export function fstatSync(fd: number): Stats; + export function link(srcpath: string, dstpath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function linkSync(srcpath: string, dstpath: string): void; + export function symlink(srcpath: string, dstpath: string, type?: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function symlinkSync(srcpath: string, dstpath: string, type?: string): void; + export function readlink(path: string, callback?: (err: NodeJS.ErrnoException, linkString: string) => any): void; + export function readlinkSync(path: string): string; + export function realpath(path: string, callback?: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; + export function realpath(path: string, cache: {[path: string]: string}, callback: (err: NodeJS.ErrnoException, resolvedPath: string) =>any): void; + export function realpathSync(path: string, cache?: { [path: string]: string }): string; + /* + * Asynchronous unlink - deletes the file specified in {path} + * + * @param path + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function unlink(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + /* + * Synchronous unlink - deletes the file specified in {path} + * + * @param path + */ + export function unlinkSync(path: string): void; + /* + * Asynchronous rmdir - removes the directory specified in {path} + * + * @param path + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function rmdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + /* + * Synchronous rmdir - removes the directory specified in {path} + * + * @param path + */ + export function rmdirSync(path: string): void; + /* + * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param path + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function mkdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + /* + * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param path + * @param mode + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function mkdir(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + /* + * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param path + * @param mode + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function mkdir(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + /* + * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param path + * @param mode + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function mkdirSync(path: string, mode?: number): void; + /* + * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param path + * @param mode + * @param callback No arguments other than a possible exception are given to the completion callback. + */ + export function mkdirSync(path: string, mode?: string): void; + /* + * Asynchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * + * @param prefix + * @param callback The created folder path is passed as a string to the callback's second parameter. + */ + export function mkdtemp(prefix: string, callback?: (err: NodeJS.ErrnoException, folder: string) => void): void; + /* + * Synchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * + * @param prefix + * @returns Returns the created folder path. + */ + export function mkdtempSync(prefix: string): string; + export function readdir(path: string, callback?: (err: NodeJS.ErrnoException, files: string[]) => void): void; + export function readdirSync(path: string): string[]; + export function close(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function closeSync(fd: number): void; + export function open(path: string, flags: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; + export function open(path: string, flags: string, mode: number, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; + export function open(path: string, flags: string, mode: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; + export function openSync(path: string, flags: string, mode?: number): number; + export function openSync(path: string, flags: string, mode?: string): number; + export function utimes(path: string, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function utimes(path: string, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function utimesSync(path: string, atime: number, mtime: number): void; + export function utimesSync(path: string, atime: Date, mtime: Date): void; + export function futimes(fd: number, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function futimes(fd: number, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function futimesSync(fd: number, atime: number, mtime: number): void; + export function futimesSync(fd: number, atime: Date, mtime: Date): void; + export function fsync(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function fsyncSync(fd: number): void; + export function write(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; + export function write(fd: number, buffer: Buffer, offset: number, length: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; + export function write(fd: number, data: any, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; + export function write(fd: number, data: any, offset: number, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; + export function write(fd: number, data: any, offset: number, encoding: string, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; + export function writeSync(fd: number, buffer: Buffer, offset: number, length: number, position?: number): number; + export function writeSync(fd: number, data: any, position?: number, enconding?: string): number; + export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: Buffer) => void): void; + export function readSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number; + /* + * Asynchronous readFile - Asynchronously reads the entire contents of a file. + * + * @param fileName + * @param encoding + * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. + */ + export function readFile(filename: string, encoding: string, callback: (err: NodeJS.ErrnoException, data: string) => void): void; + /* + * Asynchronous readFile - Asynchronously reads the entire contents of a file. + * + * @param fileName + * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer. + * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. + */ + export function readFile(filename: string, options: { encoding: string; flag?: string; }, callback: (err: NodeJS.ErrnoException, data: string) => void): void; + /* + * Asynchronous readFile - Asynchronously reads the entire contents of a file. + * + * @param fileName + * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer. + * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. + */ + export function readFile(filename: string, options: { flag?: string; }, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + /* + * Asynchronous readFile - Asynchronously reads the entire contents of a file. + * + * @param fileName + * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. + */ + export function readFile(filename: string, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + /* + * Synchronous readFile - Synchronously reads the entire contents of a file. + * + * @param fileName + * @param encoding + */ + export function readFileSync(filename: string, encoding: string): string; + /* + * Synchronous readFile - Synchronously reads the entire contents of a file. + * + * @param fileName + * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer. + */ + export function readFileSync(filename: string, options: { encoding: string; flag?: string; }): string; + /* + * Synchronous readFile - Synchronously reads the entire contents of a file. + * + * @param fileName + * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer. + */ + export function readFileSync(filename: string, options?: { flag?: string; }): Buffer; + export function writeFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void; + export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; + export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; + export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void; + export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void; + export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; + export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; + export function appendFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void; + export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void; + export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void; + export function watchFile(filename: string, listener: (curr: Stats, prev: Stats) => void): void; + export function watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: (curr: Stats, prev: Stats) => void): void; + export function unwatchFile(filename: string, listener?: (curr: Stats, prev: Stats) => void): void; + export function watch(filename: string, listener?: (event: string, filename: string) => any): FSWatcher; + export function watch(filename: string, options: { persistent?: boolean; }, listener?: (event: string, filename: string) => any): FSWatcher; + export function exists(path: string, callback?: (exists: boolean) => void): void; + export function existsSync(path: string): boolean; + /** Constant for fs.access(). File is visible to the calling process. */ + export var F_OK: number; + /** Constant for fs.access(). File can be read by the calling process. */ + export var R_OK: number; + /** Constant for fs.access(). File can be written by the calling process. */ + export var W_OK: number; + /** Constant for fs.access(). File can be executed by the calling process. */ + export var X_OK: number; + /** Tests a user's permissions for the file specified by path. */ + export function access(path: string, callback: (err: NodeJS.ErrnoException) => void): void; + export function access(path: string, mode: number, callback: (err: NodeJS.ErrnoException) => void): void; + /** Synchronous version of fs.access. This throws if any accessibility checks fail, and does nothing otherwise. */ + export function accessSync(path: string, mode ?: number): void; + export function createReadStream(path: string, options?: { + flags?: string; + encoding?: string; + fd?: number; + mode?: number; + autoClose?: boolean; + }): ReadStream; + export function createWriteStream(path: string, options?: { + flags?: string; + encoding?: string; + fd?: number; + mode?: number; + }): WriteStream; +} + +declare module "path" { + + /** + * A parsed path object generated by path.parse() or consumed by path.format(). + */ + export interface ParsedPath { + /** + * The root of the path such as '/' or 'c:\' + */ + root: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base: string; + /** + * The file extension (if any) such as '.html' + */ + ext: string; + /** + * The file name without extension (if any) such as 'index' + */ + name: string; + } + + /** + * Normalize a string path, reducing '..' and '.' parts. + * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. + * + * @param p string path to normalize. + */ + export function normalize(p: string): string; + /** + * Join all arguments together and normalize the resulting path. + * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. + * + * @param paths string paths to join. + */ + export function join(...paths: any[]): string; + /** + * Join all arguments together and normalize the resulting path. + * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. + * + * @param paths string paths to join. + */ + export function join(...paths: string[]): string; + /** + * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. + * + * Starting from leftmost {from} paramter, resolves {to} to an absolute path. + * + * If {to} isn't already absolute, {from} arguments are prepended in right to left order, until an absolute path is found. If after using all {from} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory. + * + * @param pathSegments string paths to join. Non-string arguments are ignored. + */ + export function resolve(...pathSegments: any[]): string; + /** + * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. + * + * @param path path to test. + */ + export function isAbsolute(path: string): boolean; + /** + * Solve the relative path from {from} to {to}. + * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. + * + * @param from + * @param to + */ + export function relative(from: string, to: string): string; + /** + * Return the directory name of a path. Similar to the Unix dirname command. + * + * @param p the path to evaluate. + */ + export function dirname(p: string): string; + /** + * Return the last portion of a path. Similar to the Unix basename command. + * Often used to extract the file name from a fully qualified path. + * + * @param p the path to evaluate. + * @param ext optionally, an extension to remove from the result. + */ + export function basename(p: string, ext?: string): string; + /** + * Return the extension of the path, from the last '.' to end of string in the last portion of the path. + * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string + * + * @param p the path to evaluate. + */ + export function extname(p: string): string; + /** + * The platform-specific file separator. '\\' or '/'. + */ + export var sep: string; + /** + * The platform-specific file delimiter. ';' or ':'. + */ + export var delimiter: string; + /** + * Returns an object from a path string - the opposite of format(). + * + * @param pathString path to evaluate. + */ + export function parse(pathString: string): ParsedPath; + /** + * Returns a path string from an object - the opposite of parse(). + * + * @param pathString path to evaluate. + */ + export function format(pathObject: ParsedPath): string; + + export module posix { + export function normalize(p: string): string; + export function join(...paths: any[]): string; + export function resolve(...pathSegments: any[]): string; + export function isAbsolute(p: string): boolean; + export function relative(from: string, to: string): string; + export function dirname(p: string): string; + export function basename(p: string, ext?: string): string; + export function extname(p: string): string; + export var sep: string; + export var delimiter: string; + export function parse(p: string): ParsedPath; + export function format(pP: ParsedPath): string; + } + + export module win32 { + export function normalize(p: string): string; + export function join(...paths: any[]): string; + export function resolve(...pathSegments: any[]): string; + export function isAbsolute(p: string): boolean; + export function relative(from: string, to: string): string; + export function dirname(p: string): string; + export function basename(p: string, ext?: string): string; + export function extname(p: string): string; + export var sep: string; + export var delimiter: string; + export function parse(p: string): ParsedPath; + export function format(pP: ParsedPath): string; + } +} + +declare module "string_decoder" { + export interface NodeStringDecoder { + write(buffer: Buffer): string; + detectIncompleteChar(buffer: Buffer): number; + } + export var StringDecoder: { + new (encoding: string): NodeStringDecoder; + }; +} + +declare module "tls" { + import * as crypto from "crypto"; + import * as net from "net"; + import * as stream from "stream"; + + var CLIENT_RENEG_LIMIT: number; + var CLIENT_RENEG_WINDOW: number; + + export interface TlsOptions { + host?: string; + port?: number; + pfx?: any; //string or buffer + key?: any; //string or buffer + passphrase?: string; + cert?: any; + ca?: any; //string or buffer + crl?: any; //string or string array + ciphers?: string; + honorCipherOrder?: any; + requestCert?: boolean; + rejectUnauthorized?: boolean; + NPNProtocols?: any; //array or Buffer; + SNICallback?: (servername: string) => any; + } + + export interface ConnectionOptions { + host?: string; + port?: number; + socket?: net.Socket; + pfx?: string | Buffer + key?: string | Buffer + passphrase?: string; + cert?: string | Buffer + ca?: (string | Buffer)[]; + rejectUnauthorized?: boolean; + NPNProtocols?: (string | Buffer)[]; + servername?: string; + } + + export interface Server extends net.Server { + close(): Server; + address(): { port: number; family: string; address: string; }; + addContext(hostName: string, credentials: { + key: string; + cert: string; + ca: string; + }): void; + maxConnections: number; + connections: number; + } + + export interface ClearTextStream extends stream.Duplex { + authorized: boolean; + authorizationError: Error; + getPeerCertificate(): any; + getCipher: { + name: string; + version: string; + }; + address: { + port: number; + family: string; + address: string; + }; + remoteAddress: string; + remotePort: number; + } + + export interface SecurePair { + encrypted: any; + cleartext: any; + } + + export interface SecureContextOptions { + pfx?: string | Buffer; + key?: string | Buffer; + passphrase?: string; + cert?: string | Buffer; + ca?: string | Buffer; + crl?: string | string[] + ciphers?: string; + honorCipherOrder?: boolean; + } + + export interface SecureContext { + context: any; + } + + export function createServer(options: TlsOptions, secureConnectionListener?: (cleartextStream: ClearTextStream) =>void ): Server; + export function connect(options: TlsOptions, secureConnectionListener?: () =>void ): ClearTextStream; + export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream; + export function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream; + export function createSecurePair(credentials?: crypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; + export function createSecureContext(details: SecureContextOptions): SecureContext; +} + +declare module "crypto" { + export interface CredentialDetails { + pfx: string; + key: string; + passphrase: string; + cert: string; + ca: string | string[]; + crl: string | string[]; + ciphers: string; + } + export interface Credentials { context?: any; } + export function createCredentials(details: CredentialDetails): Credentials; + export function createHash(algorithm: string): Hash; + export function createHmac(algorithm: string, key: string): Hmac; + export function createHmac(algorithm: string, key: Buffer): Hmac; + export interface Hash { + update(data: any, input_encoding?: string): Hash; + digest(encoding: 'buffer'): Buffer; + digest(encoding: string): any; + digest(): Buffer; + } + export interface Hmac extends NodeJS.ReadWriteStream { + update(data: any, input_encoding?: string): Hmac; + digest(encoding: 'buffer'): Buffer; + digest(encoding: string): any; + digest(): Buffer; + } + export function createCipher(algorithm: string, password: any): Cipher; + export function createCipheriv(algorithm: string, key: any, iv: any): Cipher; + export interface Cipher extends NodeJS.ReadWriteStream { + update(data: Buffer): Buffer; + update(data: string, input_encoding: "utf8"|"ascii"|"binary"): Buffer; + update(data: Buffer, input_encoding: any, output_encoding: "binary"|"base64"|"hex"): string; + update(data: string, input_encoding: "utf8"|"ascii"|"binary", output_encoding: "binary"|"base64"|"hex"): string; + final(): Buffer; + final(output_encoding: string): string; + setAutoPadding(auto_padding: boolean): void; + getAuthTag(): Buffer; + } + export function createDecipher(algorithm: string, password: any): Decipher; + export function createDecipheriv(algorithm: string, key: any, iv: any): Decipher; + export interface Decipher extends NodeJS.ReadWriteStream { + update(data: Buffer): Buffer; + update(data: string, input_encoding: "binary"|"base64"|"hex"): Buffer; + update(data: Buffer, input_encoding: any, output_encoding: "utf8"|"ascii"|"binary"): string; + update(data: string, input_encoding: "binary"|"base64"|"hex", output_encoding: "utf8"|"ascii"|"binary"): string; + final(): Buffer; + final(output_encoding: string): string; + setAutoPadding(auto_padding: boolean): void; + setAuthTag(tag: Buffer): void; + } + export function createSign(algorithm: string): Signer; + export interface Signer extends NodeJS.WritableStream { + update(data: any): void; + sign(private_key: string, output_format: string): string; + } + export function createVerify(algorith: string): Verify; + export interface Verify extends NodeJS.WritableStream { + update(data: any): void; + verify(object: string, signature: string, signature_format?: string): boolean; + } + export function createDiffieHellman(prime_length: number): DiffieHellman; + export function createDiffieHellman(prime: number, encoding?: string): DiffieHellman; + export interface DiffieHellman { + generateKeys(encoding?: string): string; + computeSecret(other_public_key: string, input_encoding?: string, output_encoding?: string): string; + getPrime(encoding?: string): string; + getGenerator(encoding: string): string; + getPublicKey(encoding?: string): string; + getPrivateKey(encoding?: string): string; + setPublicKey(public_key: string, encoding?: string): void; + setPrivateKey(public_key: string, encoding?: string): void; + } + export function getDiffieHellman(group_name: string): DiffieHellman; + export function pbkdf2(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number, callback: (err: Error, derivedKey: Buffer) => any): void; + export function pbkdf2(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number, digest: string, callback: (err: Error, derivedKey: Buffer) => any): void; + export function pbkdf2Sync(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number) : Buffer; + export function pbkdf2Sync(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number, digest: string) : Buffer; + export function randomBytes(size: number): Buffer; + export function randomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void; + export function pseudoRandomBytes(size: number): Buffer; + export function pseudoRandomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void; + export interface RsaPublicKey { + key: string; + padding?: any; + } + export interface RsaPrivateKey { + key: string; + passphrase?: string, + padding?: any; + } + export function publicEncrypt(public_key: string|RsaPublicKey, buffer: Buffer): Buffer + export function privateDecrypt(private_key: string|RsaPrivateKey, buffer: Buffer): Buffer +} + +declare module "stream" { + import * as events from "events"; + + export class Stream extends events.EventEmitter { + pipe(destination: T, options?: { end?: boolean; }): T; + } + + export interface ReadableOptions { + highWaterMark?: number; + encoding?: string; + objectMode?: boolean; + } + + export class Readable extends events.EventEmitter implements NodeJS.ReadableStream { + readable: boolean; + constructor(opts?: ReadableOptions); + _read(size: number): void; + read(size?: number): any; + setEncoding(encoding: string): void; + pause(): void; + resume(): void; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: T): void; + unshift(chunk: any): void; + wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; + push(chunk: any, encoding?: string): boolean; + } + + export interface WritableOptions { + highWaterMark?: number; + decodeStrings?: boolean; + objectMode?: boolean; + } + + export class Writable extends events.EventEmitter implements NodeJS.WritableStream { + writable: boolean; + constructor(opts?: WritableOptions); + _write(chunk: any, encoding: string, callback: Function): void; + write(chunk: any, cb?: Function): boolean; + write(chunk: any, encoding?: string, cb?: Function): boolean; + end(): void; + end(chunk: any, cb?: Function): void; + end(chunk: any, encoding?: string, cb?: Function): void; + } + + export interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean; + } + + // Note: Duplex extends both Readable and Writable. + export class Duplex extends Readable implements NodeJS.ReadWriteStream { + writable: boolean; + constructor(opts?: DuplexOptions); + _write(chunk: any, encoding: string, callback: Function): void; + write(chunk: any, cb?: Function): boolean; + write(chunk: any, encoding?: string, cb?: Function): boolean; + end(): void; + end(chunk: any, cb?: Function): void; + end(chunk: any, encoding?: string, cb?: Function): void; + } + + export interface TransformOptions extends ReadableOptions, WritableOptions {} + + // Note: Transform lacks the _read and _write methods of Readable/Writable. + export class Transform extends events.EventEmitter implements NodeJS.ReadWriteStream { + readable: boolean; + writable: boolean; + constructor(opts?: TransformOptions); + _transform(chunk: any, encoding: string, callback: Function): void; + _flush(callback: Function): void; + read(size?: number): any; + setEncoding(encoding: string): void; + pause(): void; + resume(): void; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: T): void; + unshift(chunk: any): void; + wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; + push(chunk: any, encoding?: string): boolean; + write(chunk: any, cb?: Function): boolean; + write(chunk: any, encoding?: string, cb?: Function): boolean; + end(): void; + end(chunk: any, cb?: Function): void; + end(chunk: any, encoding?: string, cb?: Function): void; + } + + export class PassThrough extends Transform {} +} + +declare module "util" { + export interface InspectOptions { + showHidden?: boolean; + depth?: number; + colors?: boolean; + customInspect?: boolean; + } + + export function format(format: any, ...param: any[]): string; + export function debug(string: string): void; + export function error(...param: any[]): void; + export function puts(...param: any[]): void; + export function print(...param: any[]): void; + export function log(string: string): void; + export function inspect(object: any, showHidden?: boolean, depth?: number, color?: boolean): string; + export function inspect(object: any, options: InspectOptions): string; + export function isArray(object: any): boolean; + export function isRegExp(object: any): boolean; + export function isDate(object: any): boolean; + export function isError(object: any): boolean; + export function inherits(constructor: any, superConstructor: any): void; + export function debuglog(key:string): (msg:string,...param: any[])=>void; +} + +declare module "assert" { + function internal (value: any, message?: string): void; + namespace internal { + export class AssertionError implements Error { + name: string; + message: string; + actual: any; + expected: any; + operator: string; + generatedMessage: boolean; + + constructor(options?: {message?: string; actual?: any; expected?: any; + operator?: string; stackStartFunction?: Function}); + } + + export function fail(actual?: any, expected?: any, message?: string, operator?: string): void; + export function ok(value: any, message?: string): void; + export function equal(actual: any, expected: any, message?: string): void; + export function notEqual(actual: any, expected: any, message?: string): void; + export function deepEqual(actual: any, expected: any, message?: string): void; + export function notDeepEqual(acutal: any, expected: any, message?: string): void; + export function strictEqual(actual: any, expected: any, message?: string): void; + export function notStrictEqual(actual: any, expected: any, message?: string): void; + export function deepStrictEqual(actual: any, expected: any, message?: string): void; + export function notDeepStrictEqual(actual: any, expected: any, message?: string): void; + export var throws: { + (block: Function, message?: string): void; + (block: Function, error: Function, message?: string): void; + (block: Function, error: RegExp, message?: string): void; + (block: Function, error: (err: any) => boolean, message?: string): void; + }; + + export var doesNotThrow: { + (block: Function, message?: string): void; + (block: Function, error: Function, message?: string): void; + (block: Function, error: RegExp, message?: string): void; + (block: Function, error: (err: any) => boolean, message?: string): void; + }; + + export function ifError(value: any): void; + } + + export = internal; +} + +declare module "tty" { + import * as net from "net"; + + export function isatty(fd: number): boolean; + export interface ReadStream extends net.Socket { + isRaw: boolean; + setRawMode(mode: boolean): void; + isTTY: boolean; + } + export interface WriteStream extends net.Socket { + columns: number; + rows: number; + isTTY: boolean; + } +} + +declare module "domain" { + import * as events from "events"; + + export class Domain extends events.EventEmitter implements NodeJS.Domain { + run(fn: Function): void; + add(emitter: events.EventEmitter): void; + remove(emitter: events.EventEmitter): void; + bind(cb: (err: Error, data: any) => any): any; + intercept(cb: (data: any) => any): any; + dispose(): void; + } + + export function create(): Domain; +} + +declare module "constants" { + export var E2BIG: number; + export var EACCES: number; + export var EADDRINUSE: number; + export var EADDRNOTAVAIL: number; + export var EAFNOSUPPORT: number; + export var EAGAIN: number; + export var EALREADY: number; + export var EBADF: number; + export var EBADMSG: number; + export var EBUSY: number; + export var ECANCELED: number; + export var ECHILD: number; + export var ECONNABORTED: number; + export var ECONNREFUSED: number; + export var ECONNRESET: number; + export var EDEADLK: number; + export var EDESTADDRREQ: number; + export var EDOM: number; + export var EEXIST: number; + export var EFAULT: number; + export var EFBIG: number; + export var EHOSTUNREACH: number; + export var EIDRM: number; + export var EILSEQ: number; + export var EINPROGRESS: number; + export var EINTR: number; + export var EINVAL: number; + export var EIO: number; + export var EISCONN: number; + export var EISDIR: number; + export var ELOOP: number; + export var EMFILE: number; + export var EMLINK: number; + export var EMSGSIZE: number; + export var ENAMETOOLONG: number; + export var ENETDOWN: number; + export var ENETRESET: number; + export var ENETUNREACH: number; + export var ENFILE: number; + export var ENOBUFS: number; + export var ENODATA: number; + export var ENODEV: number; + export var ENOENT: number; + export var ENOEXEC: number; + export var ENOLCK: number; + export var ENOLINK: number; + export var ENOMEM: number; + export var ENOMSG: number; + export var ENOPROTOOPT: number; + export var ENOSPC: number; + export var ENOSR: number; + export var ENOSTR: number; + export var ENOSYS: number; + export var ENOTCONN: number; + export var ENOTDIR: number; + export var ENOTEMPTY: number; + export var ENOTSOCK: number; + export var ENOTSUP: number; + export var ENOTTY: number; + export var ENXIO: number; + export var EOPNOTSUPP: number; + export var EOVERFLOW: number; + export var EPERM: number; + export var EPIPE: number; + export var EPROTO: number; + export var EPROTONOSUPPORT: number; + export var EPROTOTYPE: number; + export var ERANGE: number; + export var EROFS: number; + export var ESPIPE: number; + export var ESRCH: number; + export var ETIME: number; + export var ETIMEDOUT: number; + export var ETXTBSY: number; + export var EWOULDBLOCK: number; + export var EXDEV: number; + export var WSAEINTR: number; + export var WSAEBADF: number; + export var WSAEACCES: number; + export var WSAEFAULT: number; + export var WSAEINVAL: number; + export var WSAEMFILE: number; + export var WSAEWOULDBLOCK: number; + export var WSAEINPROGRESS: number; + export var WSAEALREADY: number; + export var WSAENOTSOCK: number; + export var WSAEDESTADDRREQ: number; + export var WSAEMSGSIZE: number; + export var WSAEPROTOTYPE: number; + export var WSAENOPROTOOPT: number; + export var WSAEPROTONOSUPPORT: number; + export var WSAESOCKTNOSUPPORT: number; + export var WSAEOPNOTSUPP: number; + export var WSAEPFNOSUPPORT: number; + export var WSAEAFNOSUPPORT: number; + export var WSAEADDRINUSE: number; + export var WSAEADDRNOTAVAIL: number; + export var WSAENETDOWN: number; + export var WSAENETUNREACH: number; + export var WSAENETRESET: number; + export var WSAECONNABORTED: number; + export var WSAECONNRESET: number; + export var WSAENOBUFS: number; + export var WSAEISCONN: number; + export var WSAENOTCONN: number; + export var WSAESHUTDOWN: number; + export var WSAETOOMANYREFS: number; + export var WSAETIMEDOUT: number; + export var WSAECONNREFUSED: number; + export var WSAELOOP: number; + export var WSAENAMETOOLONG: number; + export var WSAEHOSTDOWN: number; + export var WSAEHOSTUNREACH: number; + export var WSAENOTEMPTY: number; + export var WSAEPROCLIM: number; + export var WSAEUSERS: number; + export var WSAEDQUOT: number; + export var WSAESTALE: number; + export var WSAEREMOTE: number; + export var WSASYSNOTREADY: number; + export var WSAVERNOTSUPPORTED: number; + export var WSANOTINITIALISED: number; + export var WSAEDISCON: number; + export var WSAENOMORE: number; + export var WSAECANCELLED: number; + export var WSAEINVALIDPROCTABLE: number; + export var WSAEINVALIDPROVIDER: number; + export var WSAEPROVIDERFAILEDINIT: number; + export var WSASYSCALLFAILURE: number; + export var WSASERVICE_NOT_FOUND: number; + export var WSATYPE_NOT_FOUND: number; + export var WSA_E_NO_MORE: number; + export var WSA_E_CANCELLED: number; + export var WSAEREFUSED: number; + export var SIGHUP: number; + export var SIGINT: number; + export var SIGILL: number; + export var SIGABRT: number; + export var SIGFPE: number; + export var SIGKILL: number; + export var SIGSEGV: number; + export var SIGTERM: number; + export var SIGBREAK: number; + export var SIGWINCH: number; + export var SSL_OP_ALL: number; + export var SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; + export var SSL_OP_CIPHER_SERVER_PREFERENCE: number; + export var SSL_OP_CISCO_ANYCONNECT: number; + export var SSL_OP_COOKIE_EXCHANGE: number; + export var SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; + export var SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; + export var SSL_OP_EPHEMERAL_RSA: number; + export var SSL_OP_LEGACY_SERVER_CONNECT: number; + export var SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; + export var SSL_OP_MICROSOFT_SESS_ID_BUG: number; + export var SSL_OP_MSIE_SSLV2_RSA_PADDING: number; + export var SSL_OP_NETSCAPE_CA_DN_BUG: number; + export var SSL_OP_NETSCAPE_CHALLENGE_BUG: number; + export var SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; + export var SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; + export var SSL_OP_NO_COMPRESSION: number; + export var SSL_OP_NO_QUERY_MTU: number; + export var SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; + export var SSL_OP_NO_SSLv2: number; + export var SSL_OP_NO_SSLv3: number; + export var SSL_OP_NO_TICKET: number; + export var SSL_OP_NO_TLSv1: number; + export var SSL_OP_NO_TLSv1_1: number; + export var SSL_OP_NO_TLSv1_2: number; + export var SSL_OP_PKCS1_CHECK_1: number; + export var SSL_OP_PKCS1_CHECK_2: number; + export var SSL_OP_SINGLE_DH_USE: number; + export var SSL_OP_SINGLE_ECDH_USE: number; + export var SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; + export var SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; + export var SSL_OP_TLS_BLOCK_PADDING_BUG: number; + export var SSL_OP_TLS_D5_BUG: number; + export var SSL_OP_TLS_ROLLBACK_BUG: number; + export var ENGINE_METHOD_DSA: number; + export var ENGINE_METHOD_DH: number; + export var ENGINE_METHOD_RAND: number; + export var ENGINE_METHOD_ECDH: number; + export var ENGINE_METHOD_ECDSA: number; + export var ENGINE_METHOD_CIPHERS: number; + export var ENGINE_METHOD_DIGESTS: number; + export var ENGINE_METHOD_STORE: number; + export var ENGINE_METHOD_PKEY_METHS: number; + export var ENGINE_METHOD_PKEY_ASN1_METHS: number; + export var ENGINE_METHOD_ALL: number; + export var ENGINE_METHOD_NONE: number; + export var DH_CHECK_P_NOT_SAFE_PRIME: number; + export var DH_CHECK_P_NOT_PRIME: number; + export var DH_UNABLE_TO_CHECK_GENERATOR: number; + export var DH_NOT_SUITABLE_GENERATOR: number; + export var NPN_ENABLED: number; + export var RSA_PKCS1_PADDING: number; + export var RSA_SSLV23_PADDING: number; + export var RSA_NO_PADDING: number; + export var RSA_PKCS1_OAEP_PADDING: number; + export var RSA_X931_PADDING: number; + export var RSA_PKCS1_PSS_PADDING: number; + export var POINT_CONVERSION_COMPRESSED: number; + export var POINT_CONVERSION_UNCOMPRESSED: number; + export var POINT_CONVERSION_HYBRID: number; + export var O_RDONLY: number; + export var O_WRONLY: number; + export var O_RDWR: number; + export var S_IFMT: number; + export var S_IFREG: number; + export var S_IFDIR: number; + export var S_IFCHR: number; + export var S_IFLNK: number; + export var O_CREAT: number; + export var O_EXCL: number; + export var O_TRUNC: number; + export var O_APPEND: number; + export var F_OK: number; + export var R_OK: number; + export var W_OK: number; + export var X_OK: number; + export var UV_UDP_REUSEADDR: number; +} diff --git a/node/node.d.ts b/node/node.d.ts index a9d4709a91..d34bd65b1d 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -1,11 +1,11 @@ -// Type definitions for Node.js v4.x +// Type definitions for Node.js v6.x // Project: http://nodejs.org/ // Definitions by: Microsoft TypeScript , DefinitelyTyped // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /************************************************ * * -* Node.js v4.x API * +* Node.js v6.x API * * * ************************************************/ From e653cba45e4fde8bd631dc8eeaf12c0696717ced Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Sat, 14 May 2016 18:03:44 +0100 Subject: [PATCH 057/402] Type definitions and tests for generic-functions (#9309) * Create generic-functions.d.ts * Create genetic-functions-tests.ts * Update generic-functions.d.ts --- generic-functions/generic-functions.d.ts | 15 +++++++++++++++ generic-functions/genetic-functions-tests.ts | 16 ++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 generic-functions/generic-functions.d.ts create mode 100644 generic-functions/genetic-functions-tests.ts diff --git a/generic-functions/generic-functions.d.ts b/generic-functions/generic-functions.d.ts new file mode 100644 index 0000000000..d25ebde7cc --- /dev/null +++ b/generic-functions/generic-functions.d.ts @@ -0,0 +1,15 @@ +// Type definitions for generic-functions +// Project: https://github.com/stpettersens/generic-functions +// Definitions by: Sam Saint-Pettersen +// Definitions: https://github.com/definitelytyped/DefinitelyTyped + +declare module "generic-functions" { + function strcmp(str1: string, str2: string): boolean; + function icstrcmp(str1: string, str2: string): boolean; + function strendswith(str: string, suffix: string): boolean; + function icstrendswith(str: string, suffix: string): boolean; + function endswithdot(str: string): string; + function println(message: string): void; + function printlns(message: string[]): void; + function objGetKeyByValue(object: Object, value: any): string; +} diff --git a/generic-functions/genetic-functions-tests.ts b/generic-functions/genetic-functions-tests.ts new file mode 100644 index 0000000000..d3dc53665a --- /dev/null +++ b/generic-functions/genetic-functions-tests.ts @@ -0,0 +1,16 @@ +/// + +import g = require('generic-functions'); + +var tvShow: Object = { + seasons: 2, + show: "Better Call Saul" +}; + +console.log(g.strcmp("foo", "foo")); // => true +console.log(g.icstrcmp("BAR", "bar")); // => true +console.log(g.strendswith("file.pdf", "pdf")); // => true +console.log(g.icstrendswith("file.PDF", "pdf")); // => true +console.log(g.endswithdot("file.pdf")); // => ".pdf" +console.log(g.objGetKeyByValue(tvShow, 2)); // => "seasons" +console.log(g.objGetKeyByValue(tvShow, "Better Call Saul")); // => "show" From aa3428bea8460de571d8c7de88d2bd83a0ee6f63 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=C4=93teris=20=C5=85ikiforovs?= Date: Sat, 14 May 2016 20:04:59 +0300 Subject: [PATCH 058/402] ssh2: some options were not optional in ConnectConfig (#9310) --- ssh2/ssh2-tests.ts | 9 +++++++++ ssh2/ssh2.d.ts | 4 ++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/ssh2/ssh2-tests.ts b/ssh2/ssh2-tests.ts index d41f146dd0..da3195062d 100644 --- a/ssh2/ssh2-tests.ts +++ b/ssh2/ssh2-tests.ts @@ -293,6 +293,15 @@ conn.on('ready', () => { password: 'honk' }); +// ConnectConfig + +const sshconfig: ssh2.ConnectConfig = { + host: 'localhost', + port: 22, + username: 'ubuntu', + password: 'password' +}; + // // # Server Examples // diff --git a/ssh2/ssh2.d.ts b/ssh2/ssh2.d.ts index bae9ac653a..9e9e010825 100644 --- a/ssh2/ssh2.d.ts +++ b/ssh2/ssh2.d.ts @@ -109,7 +109,7 @@ declare module "ssh2" { * @description Try keyboard-interactive user authentication if primary user authentication method fails. * If you set this to `true`, you need to handle the `keyboard-interactive` event. */ - tryKeyboard: boolean; + tryKeyboard?: boolean; /** * @description How often (in milliseconds) to send SSH-level keepalive packets to the server * (in a similar way as OpenSSH's ServerAliveInterval config option). Set to 0 to disable. @@ -145,7 +145,7 @@ declare module "ssh2" { /** * @description Set this to a function that receives a single string argument to get detailed (local) debug information. */ - debug: (information: string) => any; + debug?: (information: string) => any; } interface ExecOption { From 5d6115f046550714a28caa3555f47a1aec114fe5 Mon Sep 17 00:00:00 2001 From: John Gouigouix Date: Sat, 14 May 2016 19:06:50 +0200 Subject: [PATCH 059/402] slick carousel 1.6.0 (#9311) * Update with stream * Update the slick carousel 1.6.0 --- slick-carousel/slick-carousel-tests.ts | 10 +++++-- slick-carousel/slick-carousel.d.ts | 38 +++++++++++++++++++++++++- tmp/tmp.d.ts | 2 +- 3 files changed, 46 insertions(+), 4 deletions(-) diff --git a/slick-carousel/slick-carousel-tests.ts b/slick-carousel/slick-carousel-tests.ts index 0279f5131e..761da66d9d 100644 --- a/slick-carousel/slick-carousel-tests.ts +++ b/slick-carousel/slick-carousel-tests.ts @@ -191,15 +191,17 @@ $("#diaporama").slick({ arrows: true, asNavFor: "#slideshow", appendArrows: "", + appendDots: "", prevArrow: "", nextArrow: "", centerMode: false, centerPadding: "50px", cssEase: "ease", - customPaging: (slider, i) => { + customPaging: (slider: any, i: number) => { return "customPaging slider " + slider + " customPaging index " + i; }, dots: false, + dotsClass: 'slick-dots', draggable: true, fade: false, focusOnSelect: false, @@ -209,6 +211,7 @@ $("#diaporama").slick({ initialSlide: 0, lazyLoad: "ondemand", mobileFirst: false, + pauseOnFocus: true, pauseOnHover: true, pauseOnDotsHover: false, respondTo: "window", @@ -224,8 +227,11 @@ $("#diaporama").slick({ touchMove: true, touchThreshold: 5, useCSS: true, + useTransform: true, variableWidth: false, vertical: false, verticalSwiping: false, - rtl: false + rtl: false, + waitForAnimate: true, + zIndex: 1000 }); diff --git a/slick-carousel/slick-carousel.d.ts b/slick-carousel/slick-carousel.d.ts index c006926f38..7f470c34a0 100644 --- a/slick-carousel/slick-carousel.d.ts +++ b/slick-carousel/slick-carousel.d.ts @@ -1,4 +1,4 @@ -// Type definitions for stick 1.5.8 +// Type definitions for stick 1.6.0 // Project: http://kenwheeler.github.io/slick/ // Definitions by: John Gouigouix // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -49,6 +49,12 @@ interface JQuerySlickOptions { */ appendArrows?: any; + /** + * Change where the navigation dots are attached (Selector, htmlString, Array, Element, jQuery object) + * Default: $(element) + */ + appendDots?: any; + /** * Allows you to select a node or customize the HTML for the "Previous" arrow. * Default: @@ -91,6 +97,12 @@ interface JQuerySlickOptions { */ dots?: boolean; + /** + * Class for slide indicator dots container + * Default: 'slick-dots' + */ + dotsClass?: string; + /** * Enable mouse dragging * Default: true @@ -145,6 +157,12 @@ interface JQuerySlickOptions { */ mobileFirst?: boolean; + /** + * Pause Autoplay On Focus + * Default: true + */ + pauseOnFocus?: boolean; + /** * Pause Autoplay On Hover * Default: true @@ -237,6 +255,12 @@ interface JQuerySlickOptions { */ useCSS?: boolean; + /** + * Enable/Disable CSS Transforms + * Default: true + */ + useTransform?: boolean; + /** * Variable width slides. * Default: false @@ -261,6 +285,18 @@ interface JQuerySlickOptions { */ rtl?: boolean; + /** + * Change the slider's direction to become right-to-left + * Default: false + */ + waitForAnimate?: boolean; + + /** + * Set the zIndex values for slides, useful for IE9 and lower + * Default: 1000 + */ + zIndex?: number; + } diff --git a/tmp/tmp.d.ts b/tmp/tmp.d.ts index eb8e24ca1a..02cff78e6f 100644 --- a/tmp/tmp.d.ts +++ b/tmp/tmp.d.ts @@ -1,4 +1,4 @@ -// Type definitions for tmp v0.0.28 +// Type definitions for tmp v0.0.28 // Project: https://www.npmjs.com/package/tmp // Definitions by: Jared Klopper // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From ead4281ec850b6af1178afc656a91d33e9f8aa73 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=C4=93teris=20=C5=85ikiforovs?= Date: Sat, 14 May 2016 20:12:32 +0300 Subject: [PATCH 060/402] Reflux (#9308) * reflux: add ListenerMixin * reflux: allow Reflux.createAction() `options` argument is optional. Readme says: "Create an action by calling Reflux.createAction with an optional options object." --- reflux/reflux-tests.ts | 5 +++++ reflux/reflux.d.ts | 4 +++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/reflux/reflux-tests.ts b/reflux/reflux-tests.ts index f626c2900b..d129c09a20 100644 --- a/reflux/reflux-tests.ts +++ b/reflux/reflux-tests.ts @@ -43,6 +43,7 @@ Reflux.createAction({ children: ["progressed", "completed", "failed"] }); +var action = Reflux.createAction(); var actions = Reflux.createActions(["fireBall", "magicMissile"]); @@ -57,3 +58,7 @@ var Store = Reflux.createStore({ // bzzzzapp! } }); + +var ReactComponent = { + mixins: [Reflux.ListenerMixin] +}; \ No newline at end of file diff --git a/reflux/reflux.d.ts b/reflux/reflux.d.ts index f7395b175e..b2d96dd621 100644 --- a/reflux/reflux.d.ts +++ b/reflux/reflux.d.ts @@ -47,7 +47,7 @@ declare module RefluxCore { function createStore(definition: StoreDefinition): Store; - function createAction(definition: ActionsDefinition): any; + function createAction(definition?: ActionsDefinition): any; function createActions(definition: ActionsDefinition): any; function createActions(definitions: string[]): any; @@ -55,6 +55,8 @@ declare module RefluxCore { function connect(store: Store, key?: string):void; function listenTo(store: Store, handler: string):void; function setState(state: any):void; + + function ListenerMixin(): any; } declare module "reflux" { From bdce9fb56090e82f9d79fe9383c7e296d26f1ab2 Mon Sep 17 00:00:00 2001 From: Eduardo Date: Sat, 14 May 2016 19:13:11 +0200 Subject: [PATCH 061/402] Added definition for daterangepicker. (#9316) * Added definition for daterangepicker. * Rename daterangepicker-test.ts to daterangepicker-tests.ts --- daterangepicker/daterangepicker-tests.ts | 59 ++++++++++ daterangepicker/daterangepicker.d.ts | 142 +++++++++++++++++++++++ 2 files changed, 201 insertions(+) create mode 100644 daterangepicker/daterangepicker-tests.ts create mode 100644 daterangepicker/daterangepicker.d.ts diff --git a/daterangepicker/daterangepicker-tests.ts b/daterangepicker/daterangepicker-tests.ts new file mode 100644 index 0000000000..e8d55f4f8e --- /dev/null +++ b/daterangepicker/daterangepicker-tests.ts @@ -0,0 +1,59 @@ +/// + +function tests_simple() { + $('#daterange').daterangepicker(); + $('input[name="daterange"]').daterangepicker({ + timePicker: true, + timePickerIncrement: 30, + locale: { + format: 'MM/DD/YYYY h:mm A' + } + }); + + $('#reportrange').daterangepicker({ + ranges: { + 'Today': [moment(), moment()], + 'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], + 'Last 7 Days': [moment().subtract(6, 'days'), moment()], + 'Last 30 Days': [moment().subtract(29, 'days'), moment()], + 'This Month': [moment().startOf('month'), moment().endOf('month')], + 'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')] + } + }); + + $('input[name="datefilter"]').on('apply.daterangepicker', function (ev, picker) { + $(this).val(picker.startDate.format('MM/DD/YYYY') + ' - ' + picker.endDate.format('MM/DD/YYYY')); + }); + + + $('input[name="datefilter"]').on('cancel.daterangepicker', function (ev, picker) { + $(this).val(''); + }); + + $('#demo').daterangepicker({ + "startDate": "05/06/2016", + "endDate": "05/12/2016" + }, function (start: string, end: string, label: string) { + console.log("New date range selected: ' + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD') + ' (predefined range: ' + label + ')"); + }); + + $(function() { + + function cb(start: moment.Moment, end: moment.Moment) { + $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY')); + } + cb(moment().subtract(29, 'days'), moment()); + + $('#reportrange').daterangepicker({ + ranges: { + 'Today': [moment(), moment()], + 'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], + 'Last 7 Days': [moment().subtract(6, 'days'), moment()], + 'Last 30 Days': [moment().subtract(29, 'days'), moment()], + 'This Month': [moment().startOf('month'), moment().endOf('month')], + 'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')] + } + }, cb); + +}); +} diff --git a/daterangepicker/daterangepicker.d.ts b/daterangepicker/daterangepicker.d.ts new file mode 100644 index 0000000000..6d24c0bd42 --- /dev/null +++ b/daterangepicker/daterangepicker.d.ts @@ -0,0 +1,142 @@ +// Type definitions for Date Range Picker v2.1.19 +// Project: http://www.daterangepicker.com/ +// Definitions by: SirMartin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +interface JQuery { + daterangepicker(settings?: daterangepicker.Settings): JQuery; + daterangepicker(settings?: daterangepicker.Settings, callback?: (start?: string | Date | moment.Moment, end?: string | Date | moment.Moment, label?: string) => any): JQuery; +} + +declare module daterangepicker { + + interface DatepickerEventObject extends JQueryEventObject { + date: Date; + format(format?: string): string; + } + + interface Settings { + /** + * The start of the initially selected date range + */ + startDate?: string | moment.Moment | Date; + /** + * The end of the initially selected date range + */ + endDate?: string | moment.Moment | Date; + /** + * The earliest date a user may select + */ + minDate?: string | moment.Moment | Date; + /** + * The latest date a user may select + */ + maxDate?: string | moment.Moment | Date; + /** + * The maximum span between the selected start and end dates. Can have any property you can add to a moment object (i.e. days, months) + */ + dateLimit?: any; + /** + * Show year and month select boxes above calendars to jump to a specific month and year + */ + showDropdowns?: boolean; + /** + * Show localized week numbers at the start of each week on the calendars + */ + showWeekNumbers?: boolean; + /** + * Show ISO week numbers at the start of each week on the calendars + */ + showISOWeekNumbers?: boolean; + /** + * Allow selection of dates with times, not just dates + */ + timePicker?: boolean; + /** + * Increment of the minutes selection list for times (i.e. 30 to allow only selection of times ending in 0 or 30) + */ + timePickerIncrement?: number; + /** + * Use 24- hour instead of 12- hour times, removing the AM/ PM selection. + */ + timePicker24Hour?: boolean; + /** + * Show seconds in the timePicker. + */ + timePickerSeconds?: boolean; + /** + * Set predefined date ranges the user can select from.Each key is the label for the range, and its value an array with two dates representing the bounds of the range. + */ + ranges?: any; + /** + * (string: 'left'/'right'/'center') Whether the picker appears aligned to the left, to the right, or centered under the HTML element it's attached to + */ + opens?: string; + /** + * (string: 'down' or 'up') Whether the picker appears below (default) or above the HTML element it's attached to + */ + drops?: string; + /** + * CSS class names that will be added to all buttons in the picker + */ + buttonClasses?: string[]; + /** + * CSS class string that will be added to the apply button + */ + applyClass?: string; + /** + * CSS class string that will be added to the cancel button + */ + cancelClass?: string; + /** + * Allows you to provide localized strings for buttons and labels, customize the date display format, and change the first day of week for the calendars. + */ + locale?: Locale; + /** + * Show only a single calendar to choose one date, instead of a range picker with two calendars; the start and end dates provided to your callback will be the same single date chosen. + */ + singleDatePicker?: boolean; + /** + * Hide the apply and cancel buttons, and automatically apply a new date range as soon as two dates or a predefined range is selected. + */ + autoApply?: boolean; + /** + * When enabled, the two calendars displayed will always be for two sequential months (i.e.January and February), and both will be advanced when clicking the left or right arrows above the calendars.When disabled, the two calendars can be individually advanced and display any month/ year. + */ + linkedCalendars?: boolean; + /** + * jQuery selector of the parent element that the date range picker will be added to, if not provided this will be 'body' + */ + parentEl?: string; + /** + * A function that is passed each date in the two calendars before they are displayed, and may return true or false to indicate whether that date should be available for selection or not. + */ + isInvalidDate?(startDate: string | moment.Moment | Date, endDate?: string | moment.Moment | Date): boolean; + /** + * Indicates whether the date range picker should automatically update the value of an < input > element it's attached to at initialization and when the selected dates change. + */ + autoUpdateInput?: boolean; + /** + * Normally, if you use the ranges option to specify pre- defined date ranges, calendars for choosing a custom date range are not shown until the user clicks "Custom Range".When this option is set to true, the calendars for choosing a custom date range are always shown instead. + */ + alwaysShowCalendars?: boolean; + } + + interface Locale { + /** + * Text for cancel label. + */ + cancelLabel?: string; + /** + * Text for apply label. + */ + applyLabel?: string; + /** + * Format of the date string. example: 'YYYY-MM-DD' + */ + format?: string; + } +} \ No newline at end of file From adfe4a9c78f885426cfdf4298f0b33763f3cbe08 Mon Sep 17 00:00:00 2001 From: Tom Wanzek Date: Sat, 14 May 2016 13:19:29 -0400 Subject: [PATCH 062/402] D3 enter (#9318) * Added empty() and size() methods to interface Enter. As per D3 API these methods are defined on the enter selection. * Added test function testEnterSizeEmpty() for .enter().empty() and .enter.size() methods. --- d3/d3-tests.ts | 14 ++++++++++++++ d3/d3.d.ts | 3 +++ 2 files changed, 17 insertions(+) diff --git a/d3/d3-tests.ts b/d3/d3-tests.ts index c9027b0889..7991dcaa03 100644 --- a/d3/d3-tests.ts +++ b/d3/d3-tests.ts @@ -2706,3 +2706,17 @@ function testMultiUtcFormat() { ["%Y", function() { return true; }] ]); } + +function testEnterSizeEmpty() { + + var selectionSize: number, + emptyStatus: boolean; + + var newNodes = d3.selectAll('.test') + .data(['1', '2', '3']) + .enter(); + + emptyStatus = newNodes.empty(); + selectionSize = newNodes.size(); + +} \ No newline at end of file diff --git a/d3/d3.d.ts b/d3/d3.d.ts index c80a922f1f..85a1b70f82 100644 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -415,6 +415,9 @@ declare namespace d3 { select(name: (datum: Datum, index: number, outerIndex: number) => EventTarget): Selection; call(func: (selection: Enter, ...args: any[]) => any, ...args: any[]): Enter; + + empty(): boolean; + size(): number; } } From 53ed90b6e7779cc64cc72bc20e17f54405d67064 Mon Sep 17 00:00:00 2001 From: Leo Liang Date: Sun, 15 May 2016 01:20:51 +0800 Subject: [PATCH 063/402] result in Client.query() callback has the same type with result object in Query end event. (#9307) --- pg/pg-tests.ts | 1 + pg/pg.d.ts | 6 +++--- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/pg/pg-tests.ts b/pg/pg-tests.ts index 99d1fac9ba..559c6183fc 100644 --- a/pg/pg-tests.ts +++ b/pg/pg-tests.ts @@ -35,6 +35,7 @@ client.connect((err) => { if (err) { return console.error("Error running query", err); } + console.log(result.rowCount); console.log(result.rows[0]["theTime"]); client.end(); return null; diff --git a/pg/pg.d.ts b/pg/pg.d.ts index 64a92d96b9..592d782610 100644 --- a/pg/pg.d.ts +++ b/pg/pg.d.ts @@ -40,13 +40,13 @@ declare module "pg" { } export interface QueryResult { + command: string; + rowCount: number; + oid: number; rows: any[]; } export interface ResultBuilder extends QueryResult { - command: string; - rowCount: number; - oid: number; addRow(row: any): void; } From 2c530936fe68f4a82fb1214212ab96a8d1996b9c Mon Sep 17 00:00:00 2001 From: Jason Killian Date: Sat, 14 May 2016 13:21:02 -0400 Subject: [PATCH 064/402] Add `openOnFocus` prop to typings (#9319) See https://github.com/JedWatson/react-select#further-options for prop details --- react-select/react-select.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/react-select/react-select.d.ts b/react-select/react-select.d.ts index 546f5e2ada..5e671b0cd8 100644 --- a/react-select/react-select.d.ts +++ b/react-select/react-select.d.ts @@ -244,6 +244,11 @@ declare namespace ReactSelect { * @default false */ openAfterFocus?: boolean; + /** + * open the options menu when the input gets focus (requires searchable = true) + * @default false + */ + openOnFocus?: boolean; /** * option component to render in dropdown */ From 933f68a564d0cb1a609fff365630593daaf5fa82 Mon Sep 17 00:00:00 2001 From: Jeroen Date: Sat, 14 May 2016 19:28:09 +0200 Subject: [PATCH 065/402] Adds extend to QUnit typings (#9322) Note that the second parameter (mixin) of this method is documented on the website as being of type string, but both the qunit source code and examples on the same documentation page tell us it's actually of type any. --- qunit/qunit-tests.ts | 33 ++++++++++++++++++++++++++++++++- qunit/qunit.d.ts | 12 ++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/qunit/qunit-tests.ts b/qunit/qunit-tests.ts index 20285e8022..5c56a428b9 100644 --- a/qunit/qunit-tests.ts +++ b/qunit/qunit-tests.ts @@ -1636,4 +1636,35 @@ function testAfterDone() { ok(i); } }); -} \ No newline at end of file +} + +// Example QUnit.extend call taken from: http://api.qunitjs.com/QUnit.extend/ +QUnit.test( "QUnit.extend", function( assert ) { + var base = { + a: 1, + b: 2, + z: 3 + }; + QUnit.extend( base, { + b: 2.5, + c: 3, + z: undefined + } ); + + // Change from documentation example to satisfy tsc: + var newBase = base; + + assert.equal( newBase.a, 1, "Unspecified values are not modified" ); + assert.equal( newBase.b, 2.5, "Existing values are updated" ); + assert.equal( newBase.c, 3, "New values are defined" ); + assert.ok( !( "z" in newBase ), "Values specified as `undefined` are removed" ); +}); + +// Example QUnit.extend usage taken from: http://stackoverflow.com/a/33439774/419956 +QUnit.extend(QUnit.assert, { + matches: function (actual, regex, message) { + var success = !!regex && !!actual && (new RegExp(regex)).test(actual); + var expected = "String matching /" + regex.toString() + "/"; + this.push(success, actual, expected, message); + } +}); \ No newline at end of file diff --git a/qunit/qunit.d.ts b/qunit/qunit.d.ts index a176712d75..a2a87e2860 100644 --- a/qunit/qunit.d.ts +++ b/qunit/qunit.d.ts @@ -469,6 +469,18 @@ interface QUnitStatic extends QUnitAssert { * @depricated since version 1.16 */ expect(amount: number): any; + + /** + * Copy the properties defined by the mixin object into the target object. + * + * This method will modify the target object to contain the "own" properties defined + * by the mixin. If the mixin object specifies the value of any attribute as undefined, + * this property will instead be removed from the target object. + * + * @param target An object whose properties are to be modified + * @param mixin An object describing which properties should be modified + */ + extend(target: any, mixin: any): any; /** * Group related tests under a single label. From c4dab8a05b805de039a1c72f7fdff857b654ad10 Mon Sep 17 00:00:00 2001 From: Piotr Laszczkowski Date: Sat, 14 May 2016 19:29:27 +0200 Subject: [PATCH 066/402] Update definitions for Handsontable - add hooks to options interface (#9325) * Add type definitions for Handsontable * Update definitions for Handsontable * Add Hooks to Options interface --- handsontable/handsontable-tests.ts | 82 ++++++++++++++++++++++++++++ handsontable/handsontable.d.ts | 86 +++++++++++++++++++++++++++++- 2 files changed, 167 insertions(+), 1 deletion(-) diff --git a/handsontable/handsontable-tests.ts b/handsontable/handsontable-tests.ts index 25ec4dee0f..318038967a 100644 --- a/handsontable/handsontable-tests.ts +++ b/handsontable/handsontable-tests.ts @@ -120,6 +120,88 @@ function test_HandsontableInit() { visibleRows: 123, width: 1232, wordWrap: true, + + // Hooks + afterAutofillApplyValues: function() {}, + afterCellMetaReset: function() {}, + afterChange: function() {}, + afterChangesObserved: function() {}, + afterColumnMove: function() {}, + afterColumnResize: function() {}, + afterColumnSort: function() {}, + afterContextMenuDefaultOptions: function() {}, + afterContextMenuHide: function() {}, + afterContextMenuShow: function() {}, + afterCopyLimit: function() {}, + afterCreateCol: function() {}, + afterCreateRow: function() {}, + afterDeselect: function() {}, + afterDestroy: function() {}, + afterDocumentKeyDown: function() {}, + afterFilter: function() {}, + afterGetCellMeta: function() {}, + afterGetColHeader: function() {}, + afterGetColumnHeaderRenderers: function() {}, + afterGetRowHeader: function() {}, + afterGetRowHeaderRenderers: function() {}, + afterInit: function() {}, + afterLoadData: function() {}, + afterMomentumScroll: function() {}, + afterOnCellCornerMouseDown: function() {}, + afterOnCellMouseDown: function() {}, + afterOnCellMouseOver: function() {}, + afterRemoveCol: function() {}, + afterRemoveRow: function() {}, + afterRender: function() {}, + afterRenderer: function() {}, + afterRowMove: function() {}, + afterRowResize: function() {}, + afterScrollHorizontally: function() {}, + afterScrollVertically: function() {}, + afterSelection: function() {}, + afterSelectionByProp: function() {}, + afterSelectionEnd: function() {}, + afterSelectionEndByProp: function() {}, + afterSetCellMeta: function() {}, + afterUpdateSettings: function() {}, + afterValidate: function() {}, + beforeAutofill: function() {}, + beforeCellAlignment: function() {}, + beforeChange: function() {}, + beforeChangeRender: function() {}, + beforeColumnMove: function() {}, + beforeColumnResize: function() {}, + beforeColumnSort: function() {}, + beforeDrawBorders: function() {}, + beforeFilter: function() {}, + beforeGetCellMeta: function() {}, + beforeInit: function() {}, + beforeInitWalkontable: function() {}, + beforeKeyDown: function() {}, + beforeOnCellMouseDown: function() {}, + beforeRemoveCol: function() {}, + beforeRemoveRow: function() {}, + beforeRender: function() {}, + beforeRenderer: function() {}, + beforeRowMove: function() {}, + beforeRowResize: function() {}, + beforeSetRangeEnd: function() {}, + beforeStretchingColumnWidth: function() {}, + beforeTouchScroll: function() {}, + beforeValidate: function() {}, + construct: function() {}, + init: function() {}, + modifyCol: function() {}, + modifyColHeader: function() {}, + modifyColWidth: function() {}, + modifyCopyableRange: function() {}, + modifyRow: function() {}, + modifyRowHeader: function() {}, + modifyRowHeight: function() {}, + persistentStateLoad: function() {}, + persistentStateReset: function() {}, + persistentStateSave: function() {}, + unmodifyCol: function() {} }); } diff --git a/handsontable/handsontable.d.ts b/handsontable/handsontable.d.ts index 9c7f87aaa3..790eb4b087 100644 --- a/handsontable/handsontable.d.ts +++ b/handsontable/handsontable.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Handsontable 0.24.1 +// Type definitions for Handsontable 0.24.3 // Project: https://handsontable.com/ // Definitions by: Handsoncode sp. z o.o. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\ @@ -124,6 +124,88 @@ declare namespace ht { wordWrap?: boolean; isEmptyCol?: (col: number) => boolean; isEmptyRow?: (row: number) => boolean; + + // hooks + afterAutofillApplyValues?: (startArea: any[], entireArea: any[]) => void; + afterCellMetaReset?: () => void; + afterChange?: (changes: any[], source: string) => void; + afterChangesObserved?: () => void; + afterColumnMove?: (startColumn: number, endColumn: number) => void; + afterColumnResize?: (currentColumn: number, newSize: number, isDoubleClick: boolean) => void; + afterColumnSort?: (column: number, order: boolean) => void; + afterContextMenuDefaultOptions?: (predefinedItems: any[]) => void; + afterContextMenuHide?: (context: Object) => void; + afterContextMenuShow?: (context: Object) => void; + afterCopyLimit?: (selectedRows: number, selectedColumnds: number, copyRowsLimit: number, copyColumnsLimit: number) => void; + afterCreateCol?: (index: number, amount: number) => void; + afterCreateRow?: (index: number, amount: number) => void; + afterDeselect?: () => void; + afterDestroy?: () => void; + afterDocumentKeyDown?: (event: Event) => void; + afterFilter?: (formulasStack: any[]) => void; + afterGetCellMeta?: (row: number, col: number, cellProperties: Object) => void; + afterGetColHeader?: (col: number, TH: Element) => void; + afterGetColumnHeaderRenderers?: (array: any[]) => void; + afterGetRowHeader?: (row: number, TH: Element) => void; + afterGetRowHeaderRenderers?: (array: any[]) => void; + afterInit?: () => void; + afterLoadData?: (firstTime: boolean) => void; + afterMomentumScroll?: () => void; + afterOnCellCornerMouseDown?: (event: Object) => void; + afterOnCellMouseDown?: (event: Object, coords: Object, TD: Element) => void; + afterOnCellMouseOver?: (event: Object, coords: Object, TD: Element) => void; + afterRemoveCol?: (index: number, amount: number) => void; + afterRemoveRow?: (index: number, amount: number) => void; + afterRender?: (isForced: boolean) => void; + afterRenderer?: (TD: Element, row: number, col: number, prop: string|number, value: string, cellProperties: Object) => void; + afterRowMove?: (startRow: number, endRow: number) => void; + afterRowResize?: (currentRow: number, newSize: number, isDoubleClick: boolean) => void; + afterScrollHorizontally?: () => void; + afterScrollVertically?: () => void; + afterSelection?: (r: number, c: number, r2: number, c2: number) => void; + afterSelectionByProp?: (r: number, p: string, r2: number, p2: string) => void; + afterSelectionEnd?: (r: number, c: number, r2: number, c2: number) => void; + afterSelectionEndByProp?: (r: number, p: string, r2: number, p2: string) => void; + afterSetCellMeta?: (row: number, col: number, key: string, value: any) => void; + afterUpdateSettings?: () => void; + afterValidate?: (isValid: boolean, value: any, row: number, prop: string|number, source: string) => void|boolean; + beforeAutofill?: (start: Object, end: Object, data: any[]) => void; + beforeCellAlignment?: (stateBefore: any, range: any, type: string, alignmentClass: string) => void; + beforeChange?: (changes: any[], source: string) => void; + beforeChangeRender?: (changes: any[], source: string) => void; + beforeColumnMove?: (startColumn: number, endColumn: number) => void; + beforeColumnResize?: (currentColumn: number, newSize: number, isDoubleClick: boolean) => void; + beforeColumnSort?: (column: number, order: boolean) => void; + beforeDrawBorders?: (corners: any[], borderClassName: string) => void; + beforeFilter?: (formulasStack: any[]) => void; + beforeGetCellMeta?: (row: number, col: number, cellProperties: Object) => void; + beforeInit?: () => void; + beforeInitWalkontable?: (walkontableConfig: Object) => void; + beforeKeyDown?: (event: Event) => void; + beforeOnCellMouseDown?: (event: Event, coords: Object, TD: Element) => void; + beforeRemoveCol?: (index: number, amount: number, logicalCols?: any[]) => void; + beforeRemoveRow?: (index: number, amount: number, logicalRows?: any[]) => void; + beforeRender?: (isForced: boolean) => void; + beforeRenderer?: (TD: Element, row: number, col: number, prop: string|number, value: string, cellProperties: Object) => void; + beforeRowMove?: (startRow: number, endRow: number) => void; + beforeRowResize?: (currentRow: number, newSize: number, isDoubleClick: boolean) => any; + beforeSetRangeEnd?: (coords: any[]) => void; + beforeStretchingColumnWidth?: (stretchedWidth: number, column: number) => void; + beforeTouchScroll?: () => void; + beforeValidate?: (value: any, row: number, prop: string|number, source: string) => void; + construct?: () => void; + init?: () => void; + modifyCol?: (col: number) => void; + modifyColHeader?: (column: number) => void; + modifyColWidth?: (width: number, col: number) => void; + modifyCopyableRange?: (copyableRanges: any[]) => void; + modifyRow?: (row: number) => void; + modifyRowHeader?: (row: number) => void; + modifyRowHeight?: (height: number, row: number) => void; + persistentStateLoad?: (key: string, valuePlaceholder: Object) => void; + persistentStateReset?: (key: string) => void; + persistentStateSave?: (key: string, value: any) => void; + unmodifyCol?: (col: number) => void; } interface Methods { addHook(key: string, callback: Function|any[]): void; @@ -203,6 +285,8 @@ declare namespace ht { validateCells(callback: Function): void; } } + + declare var Handsontable: { new (element: Element, options: ht.Options): ht.Methods; }; From c1101451fd398393619cf15371c9c67499374f4e Mon Sep 17 00:00:00 2001 From: Simon de Lang Date: Sat, 14 May 2016 19:30:19 +0200 Subject: [PATCH 067/402] Add definitions for escodegen (#9326) --- escodegen/escodegen-tests.ts | 54 +++++++++++++ escodegen/escodegen.d.ts | 149 +++++++++++++++++++++++++++++++++++ 2 files changed, 203 insertions(+) create mode 100644 escodegen/escodegen-tests.ts create mode 100644 escodegen/escodegen.d.ts diff --git a/escodegen/escodegen-tests.ts b/escodegen/escodegen-tests.ts new file mode 100644 index 0000000000..247ea2e02d --- /dev/null +++ b/escodegen/escodegen-tests.ts @@ -0,0 +1,54 @@ +/// + +import * as escodegen from 'escodegen'; + +let emptyIndentOptions: escodegen.IndentOptions = {}; +let indentOptions: escodegen.IndentOptions = { + style: ' ', + base: 0, + adjustMultilineComment: true +}; + +let emptyFormatOptions: escodegen.FormatOptions = {}; +let formatOptions: escodegen.FormatOptions = { + indent: indentOptions, + newline: '\n', + space: ' ', + json: true, + renumber: true, + hexadecimal: true, + quotes: 'single', + escapeless: true, + compact: true, + parentheses: true, + semicolons: true, + safeConcatenation: true, + preserveBlankLines: true + } + +let emptyMozillaOptions: escodegen.MozillaOptions = {}; +let mozillaOptions: escodegen.MozillaOptions = { + starlessGenerator: true, + parenthesizedComprehensionBlock: true, + comprehensionExpressionStartsWithAssignment: true +} + +let emptyGenerateOptions: escodegen.GenerateOptions = {}; +let generateOptions: escodegen.GenerateOptions = { + format: formatOptions, + moz: mozillaOptions, + parse: () => {}, + comment: true, + sourceMap: " ", + sourceMapWithCode: true, + sourceContent: " ", + sourceCode: " ", + sourceMapRoot: " ", + directive: true, + file: " ", + verbatim: " " +}; + +let myCode: string = escodegen.generate({}, generateOptions); + +let ast: any = escodegen.attachComments({}, {}, {}); diff --git a/escodegen/escodegen.d.ts b/escodegen/escodegen.d.ts new file mode 100644 index 0000000000..dac9311c6b --- /dev/null +++ b/escodegen/escodegen.d.ts @@ -0,0 +1,149 @@ +// Type definitions for escodegen +// Project: https://github.com/estools/escodegen +// Definitions by: Simon de Lang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'escodegen' { + + export interface FormatOptions { + /** + * The indent options + */ + indent?: IndentOptions; + /** + * New line string. Default is '\n'. + */ + newline?: string; + /** + * White space string. Default is standard ' ' (\x20). + */ + space?: string; + /** + * Enforce JSON format of numeric and string literals. This option takes precedence over option.format.hexadecimal and option.format.quotes. Default is false. + */ + json?: boolean; + /** + * Try to generate shorter numeric literals than toString() (9.8.1). Default is false. + */ + renumber?: boolean; + /** + * Generate hexadecimal a numeric literal if it is shorter than its equivalents. Requires option.format.renumber. Default is false. + */ + hexadecimal?: boolean; + /** + * Delimiter to use for string literals. Accepted values are: 'single', 'double', and 'auto'. When 'auto' is specified, escodegen selects a delimiter that results in a shorter literal. Default is 'single'. + */ + quotes?: string; + /** + * Escape as few characters in string literals as necessary. Default is false. + */ + escapeless?: boolean; + /** + * Do not include superfluous whitespace characters and line terminators. Default is false. + */ + compact?: boolean; + /** + * Preserve parentheses in new expressions that have no arguments. Default is true. + */ + parentheses?: boolean; + /** + * Preserve semicolons at the end of blocks and programs. Default is true. + */ + semicolons?: boolean; + safeConcatenation?: boolean; + preserveBlankLines?: boolean; + } + + export interface IndentOptions { + /** + * Indent string. Default is 4 spaces (' '). + */ + style?: string; + /** + * Base indent level. Default is 0. + */ + base?: number; + /** + * Adjust the indentation of multiline comments to keep asterisks vertically aligned. Default is false. + */ + adjustMultilineComment?: boolean; + } + + export interface MozillaOptions { + /** + * Default: false + */ + starlessGenerator?: boolean; + /** + * Default: false + */ + parenthesizedComprehensionBlock?: boolean; + /** + * Default: false + */ + comprehensionExpressionStartsWithAssignment?: boolean; + } + + export interface GenerateOptions { + /** + * The format options + */ + format?: FormatOptions; + moz?: MozillaOptions; + /** + * Mozilla Parser API compatible parse function, e.g., the parse function exported by esprima. If it is provided, generator tries to use the 'raw' representation. See esprima raw information. Default is null. + */ + parse?: Function; + /** + * If comments are attached to AST, escodegen is going to emit comments to output code. Default is false. + */ + comment?: boolean; + /** + * sourceMap is the source maps's source filename, that's a name that will show up in the browser debugger for the generated source (if source-maps is enabled). + * If a non-empty string value is provided, generate a source map. + */ + sourceMap?: string; + /** + * . If sourceMapWithCode is true generator returns output hash, where output.map is a source-map representation, which can be serialized as output.map.toString(). output.code is a string with generated JS code (note that it's not going to have //@ sourceMappingURL comment in it). + */ + sourceMapWithCode?: boolean; + /** + * Optionally option.sourceContent string can be passed (which represents original source of the file, for example it could be a source of coffeescript from which JS is being generated), if provided generated source map will have original source embedded in it. + */ + sourceContent?: string; + sourceCode?: string; + /** + * Optionally option.sourceMapRoot can be provided, in which case option.sourceMap will be treated as relative to it. For more information about source map itself, see source map library document, V3 draft and HTML5Rocks introduction. Default is undefined + * sourceMapRoot is the source root for the source map (see the Mozilla documentation). If sourceMapWithCode is truthy, an object is returned from generate() of the form: { code: .. , map: .. }. If file is provided, it will be used as file property of generated source map. + */ + sourceMapRoot?: string; + /** + * Recognize DirectiveStatement and distinguish it from ExpressionStatement. Default: false + */ + directive?: boolean; + /** + * If file is provided, it will be used as file property of generated source map. + */ + file?: string; + /** + * Providing verbatim code generation option to Expression nodes. + * verbatim option is provided by user as string. When generating Expression code, + * looking up node[option.verbatim] value and dump it instead of normal code generation. + * + * @example + * + */ + verbatim?: string; + } + + /** + * Produces given Abstract Syntax Tree as javascript code + * @param ast The Abstract Syntax Tree to generate code from + * @param options The generation options + */ + export function generate(ast: any, options?: GenerateOptions): string; + /** + * Attaching the comments is needed to keep the comments and to allow blank lines to be preserved. + */ + export function attachComments(ast: any, comments: any, tokens: any): any; +} From a9b1e55740c92322e3b8ce100865b2704c589461 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=B3bert=20Kiss?= Date: Sat, 14 May 2016 19:33:58 +0200 Subject: [PATCH 068/402] Model.save method is more common if the type of value is any instead of string (#9314) --- bookshelf/bookshelf.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bookshelf/bookshelf.d.ts b/bookshelf/bookshelf.d.ts index cf70220840..08340d09ba 100644 --- a/bookshelf/bookshelf.d.ts +++ b/bookshelf/bookshelf.d.ts @@ -104,7 +104,7 @@ declare module 'bookshelf' { query() : knex.QueryBuilder; refresh(options? : FetchOptions) : Promise; resetQuery() : T; - save(key? : string, val? : string, options? : SaveOptions) : Promise; + save(key? : string, val? : any, options? : SaveOptions) : Promise; save(attrs? : {[key : string] : any}, options? : SaveOptions) : Promise; through>(interim : typeof Model, throughForeignKey? : string, otherKey? : string) : R | Collection; where(properties : {[key : string] : any}) : T; From acdc2d397ce53133deda238a55b4148c6cfdc901 Mon Sep 17 00:00:00 2001 From: Marian Palkus Date: Sat, 14 May 2016 19:34:14 +0200 Subject: [PATCH 069/402] Add definitions for redux-mock-store (#9328) * Add definitions for redux-mock-store. * Fix definitions of redux-mock-store and updated tests. * Remove trailing empty line. --- redux-mock-store/redux-mock-store-tests.ts | 43 ++++++++++++++++++++++ redux-mock-store/redux-mock-store.d.ts | 24 ++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 redux-mock-store/redux-mock-store-tests.ts create mode 100644 redux-mock-store/redux-mock-store.d.ts diff --git a/redux-mock-store/redux-mock-store-tests.ts b/redux-mock-store/redux-mock-store-tests.ts new file mode 100644 index 0000000000..1b0a53968b --- /dev/null +++ b/redux-mock-store/redux-mock-store-tests.ts @@ -0,0 +1,43 @@ +/// + +import configureStore from 'redux-mock-store'; + +// Redux store API tests +// The following test are taken from ../redux/redux-tests.ts +function counter(state: any, action: any) { + if (!state) { + state = 0; + } + switch (action.type) { + case 'INCREMENT': + return state + 1; + case 'DECREMENT': + return state - 1; + default: + return state; + } +} + +function loggingMiddleware() { + return (next: Redux.Dispatch) => (action: any) => { + console.log(action.type); + next(action); + }; +} + +const storeMock = configureStore([loggingMiddleware]); +const initialState = 0 +let store = storeMock(initialState); + + +store.subscribe(() => { + // ... +}); + +store.dispatch({ type: 'INCREMENT' }); + + +// Additional mock store API tests +var actions: Array = store.getActions(); + +store.clearActions(); \ No newline at end of file diff --git a/redux-mock-store/redux-mock-store.d.ts b/redux-mock-store/redux-mock-store.d.ts new file mode 100644 index 0000000000..770603826a --- /dev/null +++ b/redux-mock-store/redux-mock-store.d.ts @@ -0,0 +1,24 @@ +// Type definitions for Redux Mock Store v0.0.6 +// Project: https://github.com/arnaudbenard/redux-mock-store +// Definitions by: Marian Palkus , Cap3 +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module 'redux-mock-store' { + import * as Redux from 'redux' + + function createMockStore(middlewares?:Redux.Middleware[]):mockStore + + type mockStore = (state?:T) => IStore; + + type IStore = { + dispatch(action: any):any + getState():T + getActions():Object[] + clearActions():void + subscribe(listener: Function):Function + } + + export default createMockStore +} \ No newline at end of file From 3644ba6e4f6f4421001fc73d795d684384abb2c7 Mon Sep 17 00:00:00 2001 From: Markus Wagner Date: Sat, 14 May 2016 19:37:38 +0200 Subject: [PATCH 070/402] Update log4javascript.d.ts (#9324) Method getEffectiveAppenders() added see https://sourceforge.net/projects/log4javascript/files/1.4.13/log4javascript-1.4.13.zip/download, file log4javascript_uncompressed.js, line 540 --- log4javascript/log4javascript.d.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/log4javascript/log4javascript.d.ts b/log4javascript/log4javascript.d.ts index 460e17c91f..d22e666e8f 100644 --- a/log4javascript/log4javascript.d.ts +++ b/log4javascript/log4javascript.d.ts @@ -1,4 +1,4 @@ -// Type definitions for log4javascript v1.4.10 +// Type definitions for log4javascript v1.4.13 // Project: http://log4javascript.org/ // Definitions by: Markus Wagner // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -126,6 +126,11 @@ declare namespace log4javascript { */ removeAllAppenders(): void; + /** + * Returns all appenders which will log a message. + */ + getEffectiveAppenders(): Appender[]; + /** * Sets the level. Log messages of a lower level than level will not be logged. Default value is DEBUG. */ From ccf227b5a84601e2ab3461896603416a410bd212 Mon Sep 17 00:00:00 2001 From: Max Battcher Date: Sat, 14 May 2016 13:42:38 -0400 Subject: [PATCH 071/402] Add explicit string types to GeoJson definition (#9333) * Add explicit string types to GeoJson definition The type names for each interface are explicit in the GeoJson spec and this uses recent TypeScript support for string valued types to make this much more obvious and to check this for us. * Add explicit type hints to turf tests Shape-based inferencing in Typescript does not currently appear to support string literal types in TS 1.8. --- geojson/geojson.d.ts | 9 +++++++++ turf/turf-tests.ts | 16 ++++++++-------- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/geojson/geojson.d.ts b/geojson/geojson.d.ts index d77de1fe86..4b4c2b56cf 100644 --- a/geojson/geojson.d.ts +++ b/geojson/geojson.d.ts @@ -36,6 +36,7 @@ declare namespace GeoJSON { */ export interface Point extends GeometryObject { + type: 'Point' coordinates: Position } @@ -44,6 +45,7 @@ declare namespace GeoJSON { */ export interface MultiPoint extends GeometryObject { + type: 'MultiPoint' coordinates: Position[] } @@ -52,6 +54,7 @@ declare namespace GeoJSON { */ export interface LineString extends GeometryObject { + type: 'LineString' coordinates: Position[] } @@ -60,6 +63,7 @@ declare namespace GeoJSON { */ export interface MultiLineString extends GeometryObject { + type: 'MultiLineString' coordinates: Position[][] } @@ -68,6 +72,7 @@ declare namespace GeoJSON { */ export interface Polygon extends GeometryObject { + type: 'Polygon' coordinates: Position[][] } @@ -76,6 +81,7 @@ declare namespace GeoJSON { */ export interface MultiPolygon extends GeometryObject { + type: 'MultiPolygon' coordinates: Position[][][] } @@ -84,6 +90,7 @@ declare namespace GeoJSON { */ export interface GeometryCollection extends GeoJsonObject { + type: 'GeometryCollection' geometries: GeometryObject[]; } @@ -92,6 +99,7 @@ declare namespace GeoJSON { */ export interface Feature extends GeoJsonObject { + type: 'Feature' geometry: T; properties: any; id?: string; @@ -102,6 +110,7 @@ declare namespace GeoJSON { */ export interface FeatureCollection extends GeoJsonObject { + type: 'FeatureCollection' features: Feature[]; } diff --git a/turf/turf-tests.ts b/turf/turf-tests.ts index d0fc95ba18..e671035892 100644 --- a/turf/turf-tests.ts +++ b/turf/turf-tests.ts @@ -4,7 +4,7 @@ // Tests data initialisation /////////////////////////////////////////// -var point1 = { +var point1: GeoJSON.Feature = { "type": "Feature", "properties": {}, "geometry": { @@ -13,7 +13,7 @@ var point1 = { } }; -var point2 = { +var point2: GeoJSON.Feature = { "type": "Feature", "properties": {}, "geometry": { @@ -22,7 +22,7 @@ var point2 = { } }; -var line = { +var line: GeoJSON.Feature = { "type": "Feature", "properties": {}, "geometry": { @@ -38,7 +38,7 @@ var line = { } }; -var polygons = { +var polygons: GeoJSON.FeatureCollection = { "type": "FeatureCollection", "features": [ { @@ -71,7 +71,7 @@ var polygons = { ] }; -var polygon1 = { +var polygon1: GeoJSON.Feature = { "type": "Feature", "properties": {}, "geometry": { @@ -86,7 +86,7 @@ var polygon1 = { } }; -var polygon2 = { +var polygon2: GeoJSON.Feature = { "type": "Feature", "properties": { "fill": "#00f" @@ -106,7 +106,7 @@ var polygon2 = { } } -var features = { +var features: GeoJSON.FeatureCollection = { "type": "FeatureCollection", "features": [ { @@ -197,7 +197,7 @@ var features = { ] }; -var triangle = { +var triangle: GeoJSON.Feature = { "type": "Feature", "properties": { "a": 11, From da5d70b6cbae24ee6f53a51f34b32f6d81b31deb Mon Sep 17 00:00:00 2001 From: Andrey Lipatkin Date: Sat, 14 May 2016 20:43:37 +0300 Subject: [PATCH 072/402] Feature/add jquery visible definition (#9251) * Added definition for jquery-visible library * Added EOL for last lines of jquery-visible definition and test files * Renaming definition to df-visible in order to match package name in bower --- df-visible/df-visible-tests.ts | 35 ++++++++++++++++++++++++++++++++++ df-visible/df-visible.d.ts | 16 ++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 df-visible/df-visible-tests.ts create mode 100644 df-visible/df-visible.d.ts diff --git a/df-visible/df-visible-tests.ts b/df-visible/df-visible-tests.ts new file mode 100644 index 0000000000..c5a8f1bf2b --- /dev/null +++ b/df-visible/df-visible-tests.ts @@ -0,0 +1,35 @@ +/// + +// https://github.com/customd/jquery-visible/blob/master/examples/demo-basic.html +$(function(){ + + // Add the spans to the container element. + $('#container dt').each(function(){ $(this).append(''); }); + + // Trigger the + $('#detect').on('click',function(){ + + // Select the detection type. + var detectPartial = $('#detect_type').val() == 'partial'; + + // Loop over each container, and check if it's visible. + $('#container dt').each(function(){ + + // Is this element visible onscreen? + var visible = $(this).visible( detectPartial ); + + // Set the visible status into the span. + $(this).find('span').text( visible ? 'Onscreen' : 'Offscreen' ).toggleClass('visible',visible); + }); + }); +}); + +// https://www.customd.com/articles/13/checking-if-an-element-is-visible-on-screen-using-jquery +// Check both vertical, and horizontal at once +$('#element').visible(true, false, 'both'); + +// Check only horizontal +$('#element').visible(true, false, 'horizontal'); + +// Check only vertical +$('#element').visible(true, false, 'vertical'); diff --git a/df-visible/df-visible.d.ts b/df-visible/df-visible.d.ts new file mode 100644 index 0000000000..24de14b71e --- /dev/null +++ b/df-visible/df-visible.d.ts @@ -0,0 +1,16 @@ +// Type definitions for jquery-visible +// Project: https://github.com/customd/jquery-visible +// Definitions by: Andrey Lipatkin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +interface JQuery { + /** + * Gets the value of a setting. + * @param details Which setting to consider. + * @param callback The callback parameter should be a function that looks like this: + * function(object details) {...}; + */ + visible(partial?: boolean, hidden?: boolean, direction?: string): boolean; +} From bb5d8ea26cc18a5c956ee836266b6d6b972340c9 Mon Sep 17 00:00:00 2001 From: Tanguy Krotoff Date: Sat, 14 May 2016 19:43:57 +0200 Subject: [PATCH 073/402] Improve bookshelf.d.ts and tests (#9297) * Switch to ES6 imports * Add attributes and length * Various improvements + add more tests - Fix destroy() - Fix detach() - Fix map() - Add NotFoundError, NoRowsUpdatedError and NoRowsDeletedError on Model * serialize() and toJSON() should return Object/Object[] instead of any * Fix map() * More tests taken from Bookshelf website + various fixes - Fix Bookshelf.transaction return type - Add id attribute on ModelBase - Improve ModelBase.parse() - Fix Model.query() - Add a constructor to CollectionBase - Fix CollectionBase.map() - Fix Collection.attach() - Fix Collection.query() - Add Collection.EmptyError - Fix LoadOptions and FetchOptions withRelated * No need to specify Knex.QueryBuilder * toJSON(): Object/Object[] is too restrictive, revert back to any/any[] * Model.through() returns R, Collection.through() returns Collection --- bookshelf/bookshelf-tests.ts | 1286 +++++++++++++++++++++++++++++++++- bookshelf/bookshelf.d.ts | 88 ++- knex/knex-tests.ts | 8 +- knex/knex.d.ts | 2 +- 4 files changed, 1327 insertions(+), 57 deletions(-) diff --git a/bookshelf/bookshelf-tests.ts b/bookshelf/bookshelf-tests.ts index 92758e143a..5d6080b99a 100644 --- a/bookshelf/bookshelf-tests.ts +++ b/bookshelf/bookshelf-tests.ts @@ -1,17 +1,52 @@ /// /// +/// +/// import * as Knex from 'knex'; import * as Bookshelf from 'bookshelf'; +import * as assert from 'assert'; +import * as express from 'express'; + + +/** + * The examples/tests below follow Bookshelf documentation chapter after chapter: http://bookshelfjs.org/ + */ + + +/* Installation, see http://bookshelfjs.org/#installation */ var knex = Knex({ - client: 'sqlite3', + client: 'mysql', connection: { - filename: ':memory:', - }, + host : '127.0.0.1', + user : 'your_database_user', + password : 'your_database_password', + database : 'myapp_test', + charset : 'utf8' + } }); -// Examples +var bookshelf = Bookshelf(knex); + +{ + class User extends bookshelf.Model { + get tableName() { return 'users'; } + } + + // In a file named something like bookshelf.js + const dbConfig: Knex.Config = {}; + var knex = Knex(dbConfig); + + // elsewhere, to use the bookshelf client: + var bookshelf = Bookshelf(knex); + + class Post extends bookshelf.Model { + // ... + } +} + +/* Examples, see http://bookshelfjs.org/#examples */ var bookshelf = Bookshelf(knex); @@ -20,14 +55,14 @@ bookshelf.plugin(['virtuals']); class User extends bookshelf.Model { get tableName() { return 'users'; } - messages() : Bookshelf.Collection { - return this.hasMany(Posts); + messages(): Bookshelf.Collection { + return this.hasMany(Post); } } -class Posts extends bookshelf.Model { +class Post extends bookshelf.Model { get tableName() { return 'messages'; } - tags() : Bookshelf.Collection { + tags(): Bookshelf.Collection { return this.belongsToMany(Tag); } } @@ -36,67 +71,1256 @@ class Tag extends bookshelf.Model { get tableName() { return 'tags'; } } -new User({}).where('id', 1).fetch({withRelated: ['posts.tags']}) +new User().where('id', 1).fetch({withRelated: ['posts.tags']}) .then(user => { - console.log(user.related('posts').toJSON()); + const posts = user.related('posts'); + console.log(posts.toJSON()); }).catch(err => { console.error(err); }); +/* Plugins, see http://bookshelfjs.org/#plugins */ -// Associations +/* Support, see http://bookshelfjs.org/#support */ + +/* F.A.Q., see http://bookshelfjs.org/#faq*/ + +/* Associations, see http://bookshelfjs.org/#associations */ + +/* One-to-one, see http://bookshelfjs.org/#one-to-one */ class Book extends bookshelf.Model { get tableName() { return 'books'; } - summary() { + summary(): Summary { return this.hasOne(Summary); } - pages() { - return this.hasMany(Pages); + pages(): Bookshelf.Collection { + return this.hasMany(Page); } - authors() { + authors(): Bookshelf.Collection { return this.belongsToMany(Author); } } class Summary extends bookshelf.Model { get tableName() { return 'summaries'; } - book() : Book { + book(): Book { return this.belongsTo(Book); } } -class Pages extends bookshelf.Model { +exports.up = (knex: Knex) => { + return knex.schema.createTable('books', table => { + table.increments('id').primary(); + table.string('name'); + }).createTable('summaries', table => { + table.increments('id').primary(); + table.string('details'); + table.integer('book_id').unique().references('books.id'); + }); +}; + +exports.down = (knex: Knex) => { + return knex.schema.dropTable('books') + .dropTable('summaries'); +}; + +/* One-to-many, see http://bookshelfjs.org/#one-to-many */ + +class Page extends bookshelf.Model { get tableName() { return 'pages'; } - book() { + book(): Book { return this.belongsTo(Book); } } +exports.up = (knex: Knex) => { + return knex.schema.createTable('books', table => { + table.increments('id').primary(); + table.string('name'); + }).createTable('pages', table => { + table.increments('id').primary(); + table.string('content'); + table.integer('book_id').references('books.id') + }); +}; + +exports.down = (knex: Knex) => { + return knex.schema.dropTable('books') + .dropTable('pages'); +}; + +/* Many-to-many, see http://bookshelfjs.org/#many-to-many */ + class Author extends bookshelf.Model { - get tableName() { return 'author'; } + get tableName() { return 'authors'; } books() { return this.belongsToMany(Book); } } -class Site extends bookshelf.Model { - get tableName() { return 'sites'; } - photo() { - return this.morphOne(Photo, 'imageable'); +exports.up = (knex: Knex) => { + return knex.schema.createTable('books', table => { + table.increments('id').primary(); + table.string('name'); + }).createTable('authors', table => { + table.increments('id').primary(); + table.string('name'); + }).createTable('authors_books', table => { + table.integer('author_id').references('authors.id'); + table.integer('book_id').references('books.id'); + }); +}; + +exports.down = (knex: Knex) => { + return knex.schema.dropTable('books') + .dropTable('authors') + .dropTable('authors_books'); +}; + +/* Polymorphic, see http://bookshelfjs.org/#polymorphic */ + +{ + class Site extends bookshelf.Model { + get tableName() { return 'sites'; } + photo(): Photo { + return this.morphOne(Photo, 'imageable'); + } + } + + class Post extends bookshelf.Model { + get tableName() { return 'posts'; } + photos(): Bookshelf.Collection { + return this.morphMany(Photo, 'imageable'); + } + } + + class Photo extends bookshelf.Model { + get tableName() { return 'photos'; } + imageable(): Photo { + return this.morphTo('imageable', Site, Post); + } } } -class Post extends bookshelf.Model { - get tableName() { return 'posts'; } - photos() { - return this.morphMany(Photo, 'imageable'); +/* Bookshelf, see http://bookshelfjs.org/#section-Bookshelf */ + +/* Construction, see http://bookshelfjs.org/#Bookshelf-subsection-construction */ + +/* new Bookshelf(), see http://bookshelfjs.org/#Bookshelf */ + +/* Members, see http://bookshelfjs.org/#Bookshelf-subsection-members */ + +/* bookshelf.knex, see http://bookshelfjs.org/#Bookshelf-instance-knex */ + +/* Methods, see http://bookshelfjs.org/#Bookshelf-subsection-methods */ + +/* bookshelf.transaction(), see http://bookshelfjs.org/#Bookshelf-instance-transaction */ + +class Library extends bookshelf.Model { + get tableName() { return 'libraries'; } + + relatedBooks(): Bookshelf.Collection { + return > this.related('books'); } } -class Photo extends bookshelf.Model { - get tableName() { return 'photos'; } - imageable() { - return this.morphTo('imageable', Site, Post); +bookshelf.transaction(t => { + return new Library({name: 'Old Books'}) + .save(null, {transacting: t}) + .tap(model => { + return Promise.map([ + {title: 'Canterbury Tales'}, + {title: 'Moby Dick'}, + {title: 'Hamlet'} + ], info => { + // Some validation could take place here. + return new Book(info).save({'shelf_id': model.id}, {transacting: t}); + }); + }); +}).then(library => { + console.log(library.relatedBooks().pluck('title')); +}).catch(err => { + console.error(err); +}); + +/* Type definitions */ + +/* transactionCallback(), see http://bookshelfjs.org/#Bookshelf~transactionCallback */ + +/* Model, see http://bookshelfjs.org/#section-Model */ + +/* Construction, see http://bookshelfjs.org/#Model-subsection-construction */ + +/* new Model(), see http://bookshelfjs.org/#Model */ + +{ + new Book({ + title: "One Thousand and One Nights", + author: "Scheherazade" + }); + + class Book extends bookshelf.Model { + get tableName() { return 'documents'; } + + constructor(json: Object) { + super(json); + + this.on('saving', (model, attrs, options) => { + options.query.where('type', '=', 'book'); + }); + } } } + +/* model.initialize(), see http://bookshelfjs.org/#Model-instance-initialize */ + +/* Static, see http://bookshelfjs.org/#Model-subsection-static */ + +/* Model.collection(), see http://bookshelfjs.org/#Model-static-collection */ + +class Customer extends bookshelf.Model { + get tableName() { return 'customers'; } +} +Customer.collection().fetch().then(collection => { + // ... +}); + +/* Model.count(), see http://bookshelfjs.org/#Model-static-count */ + +/* Model.extend(), see http://bookshelfjs.org/#Model-static-extend */ + +class Account extends bookshelf.Model { + get tableName() { return 'accounts'; } +} +{ + var checkit = require('checkit'); + var bcrypt = Promise.promisifyAll(require('bcrypt')); + + class Customer extends bookshelf.Model { + get tableName() { return 'customers'; } + + initialize() { + this.on('saving', this.validateSave); + } + + validateSave() { + let rules: any; + return checkit(rules).run(this.attributes); + } + + account() { + return this.belongsTo(Account); + } + + static login(email: string, password: string): Promise { + if (!email || !password) throw new Error('Email and password are both required'); + return new this({email: email.toLowerCase().trim()}).fetch({require: true}).tap(customer => { + return bcrypt.compareAsync(password, customer.get('password')) + .then((res: boolean) => { + if (!res) throw new Error('Invalid password'); + }); + }); + } + } + + const email = 'email'; + const password = 'password'; + Customer.login(email, password) + .then(customer => { + console.log(customer.omit('password')); + }).catch(Customer.NotFoundError, () => { + console.log({error: email + ' not found'}); + }).catch(err => { + console.error(err); + }); +} + +/* Model.fetchAll(), see http://bookshelfjs.org/#Model-static-fetchAll */ + +/* Model.forge(), see http://bookshelfjs.org/#Model-static-forge */ + +/* Members, see http://bookshelfjs.org/#Model-subsection-members */ + +/* model.hasTimestamps, see http://bookshelfjs.org/#Model-instance-hasTimestamps */ + +/* model.idAttribute, see http://bookshelfjs.org/#Model-instance-idAttribute */ + +/* model.tableName, see http://bookshelfjs.org/#Model-instance-tableName */ + +class Television extends bookshelf.Model { + get tableName() { return 'televisions'; } +} + +/* Methods, see http://bookshelfjs.org/#Model-subsection-methods */ + +/* model.belongsTo(), see http://bookshelfjs.org/#Model-instance-belongsTo */ + +{ + class Book extends bookshelf.Model { + get tableName() { return 'books'; } + author(): Author { + return this.belongsTo(Author); + } + } + + // select * from `books` where id = 1 + // select * from `authors` where id = book.author_id + new Book().where({id: 1}).fetch({withRelated: ['author']}).then(book => { + console.log(JSON.stringify(book.related('author'))); + }); +} + +/* model.belongsToMany(), see http://bookshelfjs.org/#Model-instance-belongsToMany */ + +{ + class Account extends bookshelf.Model { + get tableName() { return 'accounts'; } + } + + class User extends bookshelf.Model { + get tableName() { return 'users'; } + allAccounts() { + return this.belongsToMany(Account); + } + adminAccounts() { + return this.belongsToMany(Account).query({where: {access: 'admin'}}); + } + viewAccounts() { + return this.belongsToMany(Account).query({where: {access: 'readonly'}}); + } + } + + class Doctor extends bookshelf.Model { + patients(): Bookshelf.Collection { + return this.belongsToMany(Patient).through(Appointment); + } + } + + class Appointment extends bookshelf.Model { + patient(): Patient { + return this.belongsTo(Patient); + } + doctor(): Doctor { + return this.belongsTo(Doctor); + } + } + + class Patient extends bookshelf.Model { + doctors(): Bookshelf.Collection { + return this.belongsToMany(Doctor).through(Appointment); + } + } +} + +/* model.clear(), see http://bookshelfjs.org/#Model-instance-clear */ + +/* model.clone(), see http://bookshelfjs.org/#Model-instance-clone */ + +/* model.count(), see http://bookshelfjs.org/#Model-instance-count */ + +class Duck extends bookshelf.Model { +} +new Duck().where('color', 'blue').count('name') + .then(count => { + //... + }); + +/* model.destroy(), see http://bookshelfjs.org/#Model-instance-destroy */ +new User({id: 1}) + .destroy() + .then(model => { + // ... + }); + +/* model.escape(), see http://bookshelfjs.org/#Model-instance-escape */ + +/* model.fetch(), see http://bookshelfjs.org/#Model-instance-fetch */ + +// select * from `books` where `ISBN-13` = '9780440180296' +new Book({'ISBN-13': '9780440180296'}) + .fetch() + .then(model => { + // outputs 'Slaughterhouse Five' + console.log(model.get('title')); + }); +{ + class Edition extends bookshelf.Model {} + class Chapter extends bookshelf.Model {} + class Genre extends bookshelf.Model {} + + class Book extends bookshelf.Model { + get tableName() { return 'books'; } + editions() { + return this.hasMany(Edition); + } + chapters() { + return this.hasMany(Chapter); + } + genre() { + return this.belongsTo(Genre); + } + } + + new Book({'ISBN-13': '9780440180296'}).fetch({ + withRelated: [ + 'genre', 'editions', + { chapters: query => query.orderBy('chapter_number') } + ] + }).then(book => { + console.log(book.related('genre').toJSON()); + console.log(book.related('editions').toJSON()); + console.log(book.toJSON()); + }); +} + +/* model.fetchAll(), see http://bookshelfjs.org/#Model-instance-fetchAll */ + +/* model.format(), see http://bookshelfjs.org/#Model-instance-format */ + +/* model.get(), see http://bookshelfjs.org/#Model-instance-get */ +const note = new bookshelf.Model(); +note.get("title"); + +/* model.has(), see http://bookshelfjs.org/#Model-instance-has */ + +/* model.hasChanged(), see http://bookshelfjs.org/#Model-instance-hasChanged */ + +/* model.hasMany(), see http://bookshelfjs.org/#Model-instance-hasMany */ + +{ + class Author extends bookshelf.Model { + get tableName() { return 'authors'; } + + books() { + return this.hasMany(Book); + } + } + + // select * from `authors` where id = 1 + // select * from `books` where author_id = 1 + new Author().where({id: 1}).fetch({withRelated: ['books']}).then(author => { + console.log(JSON.stringify(author.related('books'))); + }); +} + +/* model.hasOne(), see http://bookshelfjs.org/#Model-instance-hasOne */ + +{ + class Record extends bookshelf.Model { + get tableName() { return 'health_records'; } + } + + class Patient extends bookshelf.Model { + get tableName() { return 'patients'; } + record(): Record { + return this.hasOne(Record); + } + } + + // select * from `health_records` where `patient_id` = 1; + const record = new Patient({id: 1}).related('record'); + record.fetch().then(model => { + // ... + }); + + // alternatively, if you don't need the relation loaded on the patient's relations hash: + new Patient({id: 1}).record().fetch().then(model => { + // ... + }); +} + +/* model.isNew(), see http://bookshelfjs.org/#Model-instance-isNew */ + +var modelA = new bookshelf.Model(); +modelA.isNew(); // true + +var modelB = new bookshelf.Model({id: 1}); +modelB.isNew(); // false + +/* model.load(), see http://bookshelfjs.org/#Model-instance-load */ +class Posts extends bookshelf.Collection {} +new Posts().fetch().then(collection => { + collection.at(0) + .load(['author', 'content', 'comments.tags']) + .then(model => { + JSON.stringify(model); + }); +}); +/* +{ + title: 'post title', + author: {...}, + content: {...}, + comments: [ + {tags: [...]}, {tags: [...]} + ] +} +*/ + +/* model.morphMany(), see http://bookshelfjs.org/#Model-instance-morphMany */ + +class Photo extends bookshelf.Model {} +{ + class Post extends bookshelf.Model { + get tableName() { return 'posts'; } + photos() { + return this.morphMany(Photo, 'imageable'); + } + } +} +{ + class Post extends bookshelf.Model { + get tableName() { return 'posts'; } + photos() { + return this.morphMany(Photo, 'imageable', ["ImageableType", "ImageableId"]); + } + } +} + +/* model.morphOne(), see http://bookshelfjs.org/#Model-instance-morphOne */ + +{ + class Site extends bookshelf.Model { + get tableName() { return 'sites'; } + photo() { + return this.morphOne(Photo, 'imageable'); + } + } +} +{ + class Site extends bookshelf.Model { + get tableName() { return 'sites'; } + photo() { + return this.morphOne(Photo, 'imageable', ["ImageableType", "ImageableId"]); + } + } +} + +/* model.morphTo(), see http://bookshelfjs.org/#Model-instance-morphTo */ + +class Site extends bookshelf.Model {} +{ + class Photo extends bookshelf.Model { + get tableName() { return 'photos'; } + imageable() { + return this.morphTo('imageable', Site, Post); + } + } +} +{ + class Photo extends bookshelf.Model { + get tableName() { return 'photos'; } + imageable() { + return this.morphTo('imageable', ["ImageableType", "ImageableId"], Site, Post); + } + } +} + +/* model.off(), see http://bookshelfjs.org/#Model-instance-off */ + +const customer = new Customer(); +const ship = new bookshelf.Model(); +customer.off('fetched fetching'); +ship.off(); // This will remove all event listeners + +/* model.on(), see http://bookshelfjs.org/#Model-instance-on */ + +customer.on('fetching', (model, columns) => { + // Do something before the data is fetched from the database +}); + +/* model.once(), see http://bookshelfjs.org/#Model-instance-once */ + +/* model.parse(), see http://bookshelfjs.org/#Model-instance-parse */ + +// Example of a "parse" to convert snake_case to camelCase, using `underscore.string` +customer.parse = attrs => { + return _.reduce(<_.Dictionary> attrs, (memo, val, key) => { + (<_.Dictionary> memo)[_.camelCase(key)] = val; + return memo; + }, {}); +}; + +/* model.previous(), see http://bookshelfjs.org/#Model-instance-previous */ + +/* model.previousAttributes(), see http://bookshelfjs.org/#Model-instance-previousAttributes */ + +/* model.query(), see http://bookshelfjs.org/#Model-instance-query */ + +const model = new bookshelf.Model(); +model + .query('where', 'other_id', '=', '5') + .fetch() + .then(model => { + // ... + }); + +model + .query({where: {other_id: '5'}, orWhere: {key: 'value'}}) + .fetch() + .then(model => { + // ... + }); + +model.query(qb => { + qb.where('other_person', 'LIKE', '%Demo').orWhere('other_id', '>', 10); +}).fetch() + .then(model => { + // ... + }); + +let qb = model.query(); +qb.where({id: 1}).select().then(resp => { + // ... +}); + +/* model.refresh(), see http://bookshelfjs.org/#Model-instance-refresh */ + +/* model.related(), see http://bookshelfjs.org/#Model-instance-related */ +class Trip extends bookshelf.Model {} +class Trips extends bookshelf.Collection {} +new Photo({id: 1}).fetch({ + withRelated: ['account'] +}).then(photo => { + if (photo) { + var account = photo.related('account'); + if (account.id) { + return ( account.related('trips')).fetch(); + } + } +}); + +/* model.resetQuery(), see http://bookshelfjs.org/#Model-instance-resetQuery */ + +/* model.save(), see http://bookshelfjs.org/#Model-instance-save */ + +new Post({name: 'New Article'}).save().then(model => { + // ... +}); +// update authors set "bio" = 'Short user bio' where "id" = 1 +new Author({id: 1, first_name: 'User'}) + .save({bio: 'Short user bio'}, {patch: true}) + .then(model => { + // ... + }); + +// Save with no arguments +bookshelf.Model.forge({id: 5, firstName: "John", lastName: "Smith"}).save().then(() => { + //... +}); + +// Or add attributes during save +bookshelf.Model.forge({id: 5}).save({firstName: "John", lastName: "Smith"}).then(() => { + //... +}); + +// Or, if you prefer, for a single attribute +bookshelf.Model.forge({id: 5}).save('name', 'John Smith').then(() => { + //... +}); + +/* model.serialize(), see http://bookshelfjs.org/#Model-instance-serialize */ + +var artist = new bookshelf.Model({ + firstName: "Wassily", + lastName: "Kandinsky" +}); + +artist.set({birthday: "December 16, 1866"}); + +console.log(JSON.stringify(artist)); +// {firstName: "Wassily", lastName: "Kandinsky", birthday: "December 16, 1866"} + +/* model.set(), see http://bookshelfjs.org/#Model-instance-set */ + +customer.set({first_name: "Joe", last_name: "Customer"}); +customer.set("telephone", "555-555-1212"); + +/* model.through(), see http://bookshelfjs.org/#Model-instance-through */ + +{ + class Book extends bookshelf.Model { + get tableName() { return 'books'; } + + // Find all paragraphs associated with this book, by + // passing through the "Chapter" model. + paragraphs(): Paragraphs { + return this.hasMany(Paragraph).through(Chapter); + } + + chapters(): Chapters { + return this.hasMany(Chapter); + } + } + + class Chapter extends bookshelf.Model { + get tableName() { return 'chapters'; } + + paragraphs(): Bookshelf.Collection { + return this.hasMany(Paragraph); + } + } + + class Chapters extends bookshelf.Collection { + } + + class Paragraph extends bookshelf.Model { + get tableName() { return 'paragraphs'; } + + chapter(): Chapter { + return this.belongsTo(Chapter); + } + + // A reverse relation, where we can get the book from the chapter. + book(): Book { + return this.belongsTo(Book).through(Chapter); + } + } + + class Paragraphs extends bookshelf.Collection { + } +} + +/* model.timestamp(), see http://bookshelfjs.org/#Model-instance-timestamp */ + +/* model.toJSON(), see http://bookshelfjs.org/#Model-instance-toJSON */ + +// TODO No example provided on Bookshelf website + +{ + interface UserJson { + name: string; + } + + class User extends bookshelf.Model { + get tableName() { return 'users'; } + + toJSON(): UserJson { + return super.toJSON(); + } + + fetchAll(): Promise { + return super.fetchAll(); + } + } + + class Users extends bookshelf.Collection { + toJSON(): UserJson[] { + return super.toJSON(); + } + } + + new User({id: 1}).fetch().then(user => { + const userJson = user.toJSON(); + console.log('User name:', userJson.name); + }); + + new User({name: 'John'}).fetchAll().then(users => { + const usersJson = users.toJSON(); + console.log('First user name:', usersJson[0].name); + }); +} + +/* model.trigger(), see http://bookshelfjs.org/#Model-instance-trigger */ + +ship.trigger('fetched'); + +/* model.triggerThen(), see http://bookshelfjs.org/#Model-instance-triggerThen */ + +/* model.unset(), see http://bookshelfjs.org/#Model-instance-unset */ + +/* model.where(), see http://bookshelfjs.org/#Model-instance-where */ + +model.where('favorite_color', '<>', 'green').fetch().then(() => { + //... +}); +// or +model.where('favorite_color', 'red').fetch().then(() => { + //... +}); +// or +model.where({favorite_color: 'red', shoe_size: 12}).fetch().then(() => { + //... +}); + +/* Lodash methods, see http://bookshelfjs.org/#Model-subsection-lodash-methods */ + +/* invert(), see http://lodash.com/docs/#invert */ + +/* keys(), see http://lodash.com/docs/#keys */ + +/* omit(), see http://lodash.com/docs/#omit */ + +/* pairs(), see http://lodash.com/docs/#pairs */ + +/* pick(), see http://lodash.com/docs/#pick */ + +/* values(), see http://lodash.com/docs/#values */ + +/* Events, see http://bookshelfjs.org/#Model-subsection-events */ + +/* model.on("created"), see http://bookshelfjs.org/#Model-event-created */ + +/* model.on("creating"), see http://bookshelfjs.org/#Model-event-creating */ + +/* model.on("destroyed"), see http://bookshelfjs.org/#Model-event-destroyed */ + +/* model.on("destroying"), see http://bookshelfjs.org/#Model-event-destroying */ + +/* model.on("fetched"), see http://bookshelfjs.org/#Model-event-fetched */ + +/* model.on("fetching"), see http://bookshelfjs.org/#Model-event-fetching */ + +/* model.on("saved"), see http://bookshelfjs.org/#Model-event-saved */ + +/* model.on("saving"), see http://bookshelfjs.org/#Model-event-saving */ + +/* model.on("updated"), see http://bookshelfjs.org/#Model-event-updated */ + +/* model.on("updating"), see http://bookshelfjs.org/#Model-event-updating */ + +/* new Model.NoRowsDeletedError(), see http://bookshelfjs.org/#Model-static-NoRowsDeletedError */ + +// TODO No example provided on Bookshelf website + +new User({id: 1}).destroy({require: true}) +.then(user => { + console.log(user.toJSON()); +}) +.catch(User.NoRowsDeletedError, () => { + console.log('User not found'); +}) +.catch(error => { + console.log('Internal error:', error); +}); + +/* new Model.NoRowsUpdatedError(), see http://bookshelfjs.org/#Model-static-NoRowsUpdatedError */ + +// TODO No example provided on Bookshelf website + +new User({id: 1}).save({}, {patch: true, require: true}) +.then(user => { + console.log(user.toJSON()); +}) +.catch(User.NoRowsUpdatedError, () => { + console.log('User not updated'); +}) +.catch(error => { + console.log('Internal error:', error); +}); + +/* new Model.NotFoundError(), see http://bookshelfjs.org/#Model-static-NotFoundError */ + +// TODO No example provided on Bookshelf website + +new User({id: 1}).fetch({require: true}) +.then(user => { + console.log(user.toJSON()); +}) +.catch(User.NotFoundError, () => { + console.log('User not found'); +}) +.catch(error => { + console.log('Internal error:', error); +}); + +/* Collection, see http://bookshelfjs.org/#section-Collection */ + +/* Construction, see http://bookshelfjs.org/#Collection-subsection-construction */ + +/* new Collection(), see http://bookshelfjs.org/#Collection */ + +class Tab extends bookshelf.Model { +} +const tab1 = new Tab(); +const tab2 = new Tab(); +const tab3 = new Tab(); +class TabSet extends bookshelf.Collection { +} +let tabs = new TabSet([tab1, tab2, tab3]); + +/* collection.initialize(), see http://bookshelfjs.org/#Collection-instance-initialize */ + +/* Static, see http://bookshelfjs.org/#Collection-subsection-static */ + +/* Collection.extend(), see http://bookshelfjs.org/#Collection-static-extend */ + +/* Collection.forge(), see http://bookshelfjs.org/#Collection-static-forge */ + +class Accounts extends bookshelf.Collection { + model: Account +} + +var accounts = Accounts.forge([ + {name: 'Person1'}, + {name: 'Person2'} +]); + +Promise.all(accounts.invoke('save')).then(() => { + // collection models should now be saved... +}); + +/* Methods, see http://bookshelfjs.org/#Collection-subsection-methods */ + +/* collection.add(), see http://bookshelfjs.org/#Collection-instance-add */ + +const ships = new bookshelf.Collection; + +ships.add([ + {name: "Flying Dutchman"}, + {name: "Black Pearl"} +]); + +/* collection.at(), see http://bookshelfjs.org/#Collection-instance-at */ + +/* collection.attach(), see http://bookshelfjs.org/#Collection-instance-attach */ + +{ + class Admin extends bookshelf.Model { + } + class Site extends bookshelf.Model { + admins() { + return this.hasMany(Admin); + } + } + var admin1 = new Admin({username: 'user1', password: 'test'}); + var admin2 = new Admin({username: 'user2', password: 'test'}); + + Promise.all([admin1.save(), admin2.save()]) + .then(() => { + return Promise.all([ + new Site({id: 1}).admins().attach([admin1, admin2]), + new Site({id: 2}).admins().attach(admin2) + ]); + }); +} + +/* collection.clone(), see http://bookshelfjs.org/#Collection-instance-clone */ + +/* collection.count(), see http://bookshelfjs.org/#Collection-instance-count */ + +class Shareholder extends bookshelf.Model {} +class Company extends bookshelf.Model { + shareholders() { + return this.hasMany(Shareholder); + } +} + +// select count(*) from shareholders where company_id = 1 and share > 0.1; +Company.forge({id:1}) + .shareholders() + .query('where', 'share', '>', '0.1') + .count() + .then(count => { + assert(count === 3); + }); + +/* collection.create(), see http://bookshelfjs.org/#Collection-instance-create */ + +class Student extends bookshelf.Model {} + +function get(req: express.Request, res: express.Response) { + // FIXME Support proposed ES Rest/Spread properties https://github.com/Microsoft/TypeScript/issues/2103 + //const { courses, ...attributes } = req.body; + const { courses, attributes } = req.body; + + Student.forge(attributes).save().tap(student => + Promise.map(courses, course => (> student.related('courses')).create(course)) + ).then(student => + res.status(200).send(student) + ).catch(error => + res.status(500).send(error.message) + ); +} + +/* collection.detach(), see http://bookshelfjs.org/#Collection-instance-detach */ + +/* collection.fetch(), see http://bookshelfjs.org/#Collection-instance-fetch */ + +/* collection.fetchOne(), see http://bookshelfjs.org/#Collection-instance-fetchOne */ + +{ + class Site extends bookshelf.Model { + authors() { + return this.hasMany(Author); + } + } + + // select * from authors where site_id = 1 and id = 2 limit 1; + new Site({id: 1}) + .authors() + .query({where: {id: 2}}) + .fetchOne() + .then(model => { + // ... + }); +} + +/* collection.findWhere(), see http://bookshelfjs.org/#Collection-instance-findWhere */ + +/* collection.get(), see http://bookshelfjs.org/#Collection-instance-get */ + +const library = new bookshelf.Collection(); +const book = library.get(110); + +/* collection.invokeThen(), see http://bookshelfjs.org/#Collection-instance-invokeThen */ + +const options = {}; +const collection = new bookshelf.Collection(); +collection.invokeThen('save', null, options).then(() => { + // ... all models in the collection have been saved +}); + +collection.invokeThen('destroy', options).then(() => { + // ... all models in the collection have been destroyed +}); + +/* collection.load(), see http://bookshelfjs.org/#Collection-instance-load */ + +/* collection.off(), see http://bookshelfjs.org/#Collection-instance-off */ + +ships.off('fetched') // Remove the 'fetched' event listener + +/* collection.on(), see http://bookshelfjs.org/#Collection-instance-on */ + +ships.on('fetched', (collection, response) => { + // Do something after the data has been fetched from the database +}) + +/* collection.once(), see http://bookshelfjs.org/#Collection-instance-once */ + +/* collection.parse(), see http://bookshelfjs.org/#Collection-instance-parse */ + +/* collection.pluck(), see http://bookshelfjs.org/#Collection-instance-pluck */ + +/* collection.pop(), see http://bookshelfjs.org/#Collection-instance-pop */ + +/* collection.push(), see http://bookshelfjs.org/#Collection-instance-push */ + +/* collection.query(), see http://bookshelfjs.org/#Collection-instance-query */ + +{ + let qb = collection.query(); + qb.where({id: 1}).select().then(resp => { + // ... + }); + + collection.query(qb => { + qb.where('id', '>', 5).andWhere('first_name', '=', 'Test'); + }).fetch() + .then(collection => { + // ... + }); + + collection + .query('where', 'other_id', '=', '5') + .fetch() + .then(collection => { + // ... + }); +} + +/* collection.reduceThen(), see http://bookshelfjs.org/#Collection-instance-reduceThen */ + +/* collection.remove(), see http://bookshelfjs.org/#Collection-instance-remove */ + +/* collection.reset(), see http://bookshelfjs.org/#Collection-instance-reset */ + +/* collection.resetQuery(), see http://bookshelfjs.org/#Collection-instance-resetQuery */ + +/* collection.serialize(), see http://bookshelfjs.org/#Collection-instance-serialize */ + +/* collection.set(), see http://bookshelfjs.org/#Collection-instance-set */ + +class BandMember extends bookshelf.Model {} +const eddie = new BandMember(); +const alex = new BandMember(); +const stone = new BandMember(); +const roth = new BandMember(); +const hagar = new BandMember(); +var vanHalen = new bookshelf.Collection([eddie, alex, stone, roth]); +vanHalen.set([eddie, alex, stone, hagar]); + +/* collection.shift(), see http://bookshelfjs.org/#Collection-instance-shift */ + +/* collection.slice(), see http://bookshelfjs.org/#Collection-instance-slice */ + +/* collection.through(), see http://bookshelfjs.org/#Collection-instance-through */ + +/* collection.toJSON(), see http://bookshelfjs.org/#Collection-instance-toJSON */ + +/* collection.trigger(), see http://bookshelfjs.org/#Collection-instance-trigger */ + +ships.trigger('fetched'); + +/* collection.triggerThen(), see http://bookshelfjs.org/#Collection-instance-triggerThen */ + +/* collection.unshift(), see http://bookshelfjs.org/#Collection-instance-unshift */ + +/* collection.updatePivot(), see http://bookshelfjs.org/#Collection-instance-updatePivot */ + +/* collection.where(), see http://bookshelfjs.org/#Collection-instance-where */ + +/* collection.withPivot(), see http://bookshelfjs.org/#Collection-instance-withPivot */ + +{ + class Comment extends bookshelf.Model {} + class Tag extends bookshelf.Model { + comments() { + return this.belongsToMany(Comment).withPivot(['created_at', 'order']); + } + } +} + +/* Lodash methods, see http://bookshelfjs.org/#Collection-subsection-lodash-methods */ + +/* all(), see http://lodash.com/docs/#all */ + +/* any(), see http://lodash.com/docs/#any */ + +/* chain(), see http://lodash.com/docs/#chain */ + +/* collect(), see http://lodash.com/docs/#collect */ + +/* contains(), see http://lodash.com/docs/#contains */ + +/* countBy(), see http://lodash.com/docs/#countBy */ + +/* detect(), see http://lodash.com/docs/#detect */ + +/* difference(), see http://lodash.com/docs/#difference */ + +/* drop(), see http://lodash.com/docs/#drop */ + +/* each(), see http://lodash.com/docs/#each */ + +/* every(), see http://lodash.com/docs/#every */ + +/* filter(), see http://lodash.com/docs/#filter */ + +/* find(), see http://lodash.com/docs/#find */ + +/* first(), see http://lodash.com/docs/#first */ + +/* foldl(), see http://lodash.com/docs/#foldl */ + +/* foldr(), see http://lodash.com/docs/#foldr */ + +/* forEach(), see http://lodash.com/docs/#forEach */ + +/* groupBy(), see http://lodash.com/docs/#groupBy */ + +/* head(), see http://lodash.com/docs/#head */ + +/* include(), see http://lodash.com/docs/#include */ + +/* indexOf(), see http://lodash.com/docs/#indexOf */ + +/* initial(), see http://lodash.com/docs/#initial */ + +/* inject(), see http://lodash.com/docs/#inject */ + +/* invoke(), see http://lodash.com/docs/#invoke */ + +/* isEmpty(), see http://lodash.com/docs/#isEmpty */ + +/* last(), see http://lodash.com/docs/#last */ + +/* lastIndexOf(), see http://lodash.com/docs/#lastIndexOf */ + +/* map(), see http://lodash.com/docs/#map */ + +// TODO No example provided on Bookshelf website + +{ + class Author extends bookshelf.Model { + get tableName() { return 'author'; } + books() { + return this.belongsToMany(Book); + } + relatedBooks() { + return > this.related('books'); + } + } + new Author({id: 1}).fetch({require: true, withRelated: ['books']}) + .then(author => { + const books = author.relatedBooks(); + const booksJson = books.map(book => book.toJSON()); + }); + + class AuthorOutput { + constructor(bookJson: Object) {} + } + + new Author({id: 1}).fetch({require: true, withRelated: ['books']}) + .then(author => { + const books = author.relatedBooks(); + const booksOutput = books.map(book => new AuthorOutput(book.toJSON())); + }); +} + +/* max(), see http://lodash.com/docs/#max */ + +/* min(), see http://lodash.com/docs/#min */ + +/* reduce(), see http://lodash.com/docs/#reduce */ + +/* reduceRight(), see http://lodash.com/docs/#reduceRight */ + +/* reject(), see http://lodash.com/docs/#reject */ + +/* rest(), see http://lodash.com/docs/#rest */ + +/* select(), see http://lodash.com/docs/#select */ + +/* shuffle(), see http://lodash.com/docs/#shuffle */ + +/* size(), see http://lodash.com/docs/#size */ + +/* some(), see http://lodash.com/docs/#some */ + +/* sortBy(), see http://lodash.com/docs/#sortBy */ + +/* tail(), see http://lodash.com/docs/#tail */ + +/* take(), see http://lodash.com/docs/#take */ + +/* toArray(), see http://lodash.com/docs/#toArray */ + +/* without(), see http://lodash.com/docs/#without */ + +/* Events, see http://bookshelfjs.org/#Collection-subsection-events */ + +/* collection.on("fetched"), see http://bookshelfjs.org/#Collection-event-fetched */ + +/* new Collection.EmptyError(), see http://bookshelfjs.org/#Collection-static-EmptyError */ + +// TODO No example provided on Bookshelf website + +class Users extends bookshelf.Collection { +} +new User({name: 'John'}).fetchAll({require: true}) +.then(users => { + console.log(users.toJSON()); +}) +.catch(Users.EmptyError, () => { + console.log('No user found'); +}) +.catch(error => { + console.log('Internal error:', error); +}); + +/* Events, see http://bookshelfjs.org/#section-Events */ + +/* new Events(), see http://bookshelfjs.org/#Events */ + +/* events.off(), see http://bookshelfjs.org/#Events-instance-off */ + +/* events.on(), see http://bookshelfjs.org/#Events-instance-on */ + +/* events.once(), see http://bookshelfjs.org/#Events-instance-once */ + +/* events.trigger(), see http://bookshelfjs.org/#Events-instance-trigger */ + +/* events.triggerThen(), see http://bookshelfjs.org/#Events-instance-triggerThen */ diff --git a/bookshelf/bookshelf.d.ts b/bookshelf/bookshelf.d.ts index 08340d09ba..0ca3a1ebcd 100644 --- a/bookshelf/bookshelf.d.ts +++ b/bookshelf/bookshelf.d.ts @@ -6,23 +6,25 @@ /// /// /// +/// declare module 'bookshelf' { - import knex = require('knex'); - import Promise = require('bluebird'); - import Lodash = require('lodash'); + import * as Knex from 'knex'; + import * as Promise from 'bluebird'; + import * as Lodash from 'lodash'; + import * as createError from 'create-error'; interface Bookshelf extends Bookshelf.Events { VERSION : string; - knex : knex; + knex : Knex; Model : typeof Bookshelf.Model; Collection : typeof Bookshelf.Collection; plugin(name: string | string[] | Function, options?: any) : Bookshelf; - transaction(callback : (transaction : knex.Transaction) => T) : Promise; + transaction(callback : (transaction : Knex.Transaction) => T) : T; } - function Bookshelf(knex : knex) : Bookshelf; + function Bookshelf(knex : Knex) : Bookshelf; namespace Bookshelf { abstract class Events { @@ -44,6 +46,13 @@ declare module 'bookshelf' { /** If overriding, must use a getter instead of a plain property. */ idAttribute : string; + // See https://github.com/tgriesser/bookshelf/blob/0.9.4/src/base/model.js#L178 + // See https://github.com/tgriesser/bookshelf/blob/0.9.4/src/base/model.js#L213 + id : any; + + // See https://github.com/tgriesser/bookshelf/blob/0.9.4/src/base/model.js#L28 + attributes : any; + constructor(attributes? : any, options? : ModelOptions); clear() : T; @@ -54,7 +63,7 @@ declare module 'bookshelf' { has(attribute : string) : boolean; hasChanged(attribute? : string) : boolean; isNew() : boolean; - parse(response : any) : any; + parse(response : Object) : Object; previousAttributes() : any; previous(attribute : string) : any; related>(relation : string) : R | Collection; @@ -88,7 +97,7 @@ declare module 'bookshelf' { belongsTo>(target : {new(...args : any[]) : R}, foreignKey? : string) : R; belongsToMany>(target : {new(...args : any[]) : R}, table? : string, foreignKey? : string, otherKey? : string) : Collection; count(column? : string, options? : SyncOptions) : Promise; - destroy(options? : SyncOptions) : Promise; + destroy(options? : DestroyOptions) : Promise; fetch(options? : FetchOptions) : Promise; fetchAll(options? : FetchAllOptions) : Promise>; hasMany>(target : {new(...args : any[]) : R}, foreignKey? : string) : Collection; @@ -98,20 +107,35 @@ declare module 'bookshelf' { morphOne>(target : {new(...args : any[]) : R}, name? : string, columnNames? : string[], morphValue? : string) : R; morphTo(name : string, columnNames? : string[], ...target : typeof Model[]) : T; morphTo(name : string, ...target : typeof Model[]) : T; + + // Declaration order matters otherwise TypeScript gets confused between query() and query(...query: string[]) + query() : Knex.QueryBuilder; + query(callback : (qb : Knex.QueryBuilder) => void) : T; query(...query : string[]) : T; query(query : {[key : string] : any}) : T; - query(callback : (qb : knex.QueryBuilder) => void) : T; - query() : knex.QueryBuilder; + refresh(options? : FetchOptions) : Promise; resetQuery() : T; save(key? : string, val? : any, options? : SaveOptions) : Promise; save(attrs? : {[key : string] : any}, options? : SaveOptions) : Promise; - through>(interim : typeof Model, throughForeignKey? : string, otherKey? : string) : R | Collection; + through>(interim : typeof Model, throughForeignKey? : string, otherKey? : string) : R; where(properties : {[key : string] : any}) : T; where(key : string, operatorOrValue : string|number|boolean, valueIfOperator? : string|number|boolean) : T; + + // See https://github.com/tgriesser/bookshelf/blob/0.9.4/src/errors.js + // See https://github.com/tgriesser/bookshelf/blob/0.9.4/src/model.js#L1280 + static NotFoundError: createError.Error; + static NoRowsUpdatedError: createError.Error; + static NoRowsDeletedError: createError.Error; } abstract class CollectionBase> extends Events { + // See https://github.com/tgriesser/bookshelf/blob/0.9.4/src/base/collection.js#L573 + length : number; + + // See https://github.com/tgriesser/bookshelf/blob/0.9.4/src/base/collection.js#L21 + constructor(models? : T[], options? : CollectionOptions); + add(models : T[]|{[key : string] : any}[], options? : CollectionAddOptions) : Collection; at(index : number) : T; clone() : Collection; @@ -127,11 +151,11 @@ declare module 'bookshelf' { remove(model : T, options? : EventOptions) : T; remove(model : T[], options? : EventOptions) : T[]; reset(model : any[], options? : CollectionAddOptions) : T[]; - serialize(options? : SerializeOptions) : any; + serialize(options? : SerializeOptions) : any[]; set(models : T[]|{[key : string] : any}[], options? : CollectionSetOptions) : Collection; shift(options? : EventOptions) : void; slice(begin? : number, end? : number) : void; - toJSON(options? : SerializeOptions) : any; + toJSON(options? : SerializeOptions) : any[]; unshift(model : any, options? : CollectionAddOptions) : void; where(match : {[key : string] : any}, firstOnly : boolean) : T|Collection; @@ -177,8 +201,13 @@ declare module 'bookshelf' { keys() : string[]; last() : T; lastIndexOf(value : any, fromIndex? : number) : number; - map(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T[]; - map(predicate? : R) : T[]; + + // See https://github.com/DefinitelyTyped/DefinitelyTyped/blob/1ec3d51/lodash/lodash-3.10.d.ts#L7119 + // See https://github.com/Microsoft/TypeScript/blob/v1.8.10/lib/lib.core.es7.d.ts#L1122 + map(predicate? : Lodash.ListIterator|string, thisArg? : any) : U[]; + map(predicate? : Lodash.DictionaryIterator|string, thisArg? : any) : U[]; + map(predicate? : string) : U[]; + max(predicate? : Lodash.ListIterator|string, thisArg? : any) : T; max(predicate? : R) : T; min(predicate? : Lodash.ListIterator|string, thisArg? : any) : T; @@ -208,20 +237,27 @@ declare module 'bookshelf' { /** @deprecated should use `new` objects instead. */ static forge(attributes? : any, options? : ModelOptions) : T; - attach(ids : any[], options? : SyncOptions) : Promise>; + attach(ids : any|any[], options? : SyncOptions) : Promise>; count(column? : string, options? : SyncOptions) : Promise; create(model : {[key : string] : any}, options? : CollectionCreateOptions) : Promise; detach(ids : any[], options? : SyncOptions) : Promise; + detach(options? : SyncOptions) : Promise; fetchOne(options? : CollectionFetchOneOptions) : Promise; load(relations : string|string[], options? : SyncOptions) : Promise>; + + // Declaration order matters otherwise TypeScript gets confused between query() and query(...query: string[]) + query() : Knex.QueryBuilder; + query(callback : (qb : Knex.QueryBuilder) => void) : Collection; query(...query : string[]) : Collection; query(query : {[key : string] : any}) : Collection; - query(callback : (qb : knex.QueryBuilder) => void) : Collection; - query() : knex.QueryBuilder; + resetQuery() : Collection; - through>(interim : typeof Model, throughForeignKey? : string, otherKey? : string) : R | Collection; + through>(interim : typeof Model, throughForeignKey? : string, otherKey? : string) : Collection; updatePivot(attributes : any, options? : PivotOptions) : Promise; withPivot(columns : string[]) : Collection; + + // See https://github.com/tgriesser/bookshelf/blob/0.9.4/src/collection.js#L389 + static EmptyError: createError.Error; } interface ModelOptions { @@ -231,13 +267,17 @@ declare module 'bookshelf' { } interface LoadOptions extends SyncOptions { - withRelated: string|any|any[]; + withRelated : (string|WithRelatedQuery)[]; } interface FetchOptions extends SyncOptions { require? : boolean; columns? : string|string[]; - withRelated? : string|any|any[]; + withRelated? : (string|WithRelatedQuery)[]; + } + + interface WithRelatedQuery { + [index : string] : (query : Knex.QueryBuilder) => Knex.QueryBuilder; } interface FetchAllOptions extends SyncOptions { @@ -251,6 +291,10 @@ declare module 'bookshelf' { require? : boolean; } + interface DestroyOptions extends SyncOptions { + require? : boolean; + } + interface SerializeOptions { shallow? : boolean; omitPivot? : boolean; @@ -265,7 +309,7 @@ declare module 'bookshelf' { } interface SyncOptions { - transacting? : knex.Transaction; + transacting? : Knex.Transaction; debug? : boolean; } diff --git a/knex/knex-tests.ts b/knex/knex-tests.ts index 1d4961d9ea..410139f4b6 100644 --- a/knex/knex-tests.ts +++ b/knex/knex-tests.ts @@ -1,8 +1,10 @@ /// + /// -import Knex = require('knex'); -import _ = require('lodash'); -'use strict'; + +import * as Knex from 'knex'; +import * as _ from 'lodash'; + // Initializing the Library var knex = Knex({ client: 'sqlite3', diff --git a/knex/knex.d.ts b/knex/knex.d.ts index 47a5e6ad72..b9c4a9ca12 100644 --- a/knex/knex.d.ts +++ b/knex/knex.d.ts @@ -302,7 +302,7 @@ declare module "knex" { interface SchemaBuilder extends Promise { createTable(tableName: string, callback: (tableBuilder: CreateTableBuilder) => any): SchemaBuilder; renameTable(oldTableName: string, newTableName: string): Promise; - dropTable(tableName: string): Promise; + dropTable(tableName: string): SchemaBuilder; hasTable(tableName: string): Promise; hasColumn(tableName: string, columnName: string): Promise; table(tableName: string, callback: (tableBuilder: AlterTableBuilder) => any): Promise; From 6d46dce92eadc51f944c07400dbb3c85a44dc00a Mon Sep 17 00:00:00 2001 From: Tristan Geraets Date: Sat, 14 May 2016 19:48:53 +0200 Subject: [PATCH 074/402] Update meteor.d.ts (#9323) Missing property Meteor.isTest added, this flag is missing from the official docs as well but referenced in the [guide](http://guide.meteor.com/v1.3/testing.html#test-modes) --- meteor/meteor.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/meteor/meteor.d.ts b/meteor/meteor.d.ts index fc89e8b4a4..7f17984e2d 100644 --- a/meteor/meteor.d.ts +++ b/meteor/meteor.d.ts @@ -582,6 +582,7 @@ declare namespace Meteor { var isDevelopment: boolean; var isProduction: boolean; var isServer: boolean; + var isTest: boolean; function loggingIn(): boolean; function loginWith(options?: { requestPermissions?: string[]; From 672b7b71d1e2d4ffb6587d1144bdaf901ea77d24 Mon Sep 17 00:00:00 2001 From: Gael Magnan de bornier Date: Sat, 14 May 2016 19:51:31 +0200 Subject: [PATCH 075/402] New version on Joi, now the v9 is available. (#9335) --- joi/joi-6.5.0-tests.ts | 774 ++++++++++++++++++++++++++++++++++++++++ joi/joi-6.5.0.d.ts | 778 +++++++++++++++++++++++++++++++++++++++++ joi/joi-tests.ts | 23 +- joi/joi.d.ts | 101 +++++- 4 files changed, 1672 insertions(+), 4 deletions(-) create mode 100644 joi/joi-6.5.0-tests.ts create mode 100644 joi/joi-6.5.0.d.ts diff --git a/joi/joi-6.5.0-tests.ts b/joi/joi-6.5.0-tests.ts new file mode 100644 index 0000000000..a00543fe4e --- /dev/null +++ b/joi/joi-6.5.0-tests.ts @@ -0,0 +1,774 @@ +/// +/// + +import Joi = require('joi'); + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var x: any = null; +var value: any = null; +var num: number = 0; +var str: string = ''; +var bool: boolean = false; +var exp: RegExp = null; +var obj: Object = null; +var date: Date = null; +var bin: NodeBuffer = null; +var err: Error = null; +var func: Function = null; + +var anyArr: any[] = []; +var numArr: number[] = []; +var strArr: string[] = []; +var boolArr: boolean[] = []; +var expArr: RegExp[] = []; +var objArr: Object[] = []; +var bufArr: NodeBuffer[] = []; +var errArr: Error[] = []; +var funcArr: Function[] = []; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var schema: Joi.Schema = null; + +var anySchema: Joi.AnySchema = null; +var numSchema: Joi.NumberSchema = null; +var strSchema: Joi.StringSchema = null; +var arrSchema: Joi.ArraySchema = null; +var boolSchema: Joi.BooleanSchema = null; +var binSchema: Joi.BinarySchema = null; +var dateSchema: Joi.DateSchema = null; +var funcSchema: Joi.FunctionSchema = null; +var objSchema: Joi.ObjectSchema = null; +var altSchema: Joi.AlternativesSchema = null; + +var schemaArr: Joi.Schema[] = []; + +var ref: Joi.Reference = null; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var validOpts: Joi.ValidationOptions = null; + +validOpts = {abortEarly: bool}; +validOpts = {convert: bool}; +validOpts = {allowUnknown: bool}; +validOpts = {skipFunctions: bool}; +validOpts = {stripUnknown: bool}; +validOpts = {language: bool}; +validOpts = {presence: str}; +validOpts = {context: obj}; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var renOpts: Joi.RenameOptions = null; + +renOpts = {alias: bool}; +renOpts = {multiple: bool}; +renOpts = {override: bool}; +renOpts = {ignoreUndefined: bool}; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var emailOpts: Joi.EmailOptions = null; + +emailOpts = {errorLevel: num}; +emailOpts = {errorLevel: bool}; +emailOpts = {tldWhitelist: strArr}; +emailOpts = {tldWhitelist: obj}; +emailOpts = {minDomainAtoms: num}; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var ipOpts: Joi.IpOptions = null; + +ipOpts = {version: str}; +ipOpts = {version: strArr}; +ipOpts = {cidr: str}; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var uriOpts: Joi.UriOptions = null; + +uriOpts = {scheme: str}; +uriOpts = {scheme: exp}; +uriOpts = {scheme: strArr}; +uriOpts = {scheme: expArr}; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var whenOpts: Joi.WhenOptions = null; + +whenOpts = {is: x}; +whenOpts = {is: schema, then: schema}; +whenOpts = {is: schema, otherwise: schema}; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var refOpts: Joi.ReferenceOptions = null; + +refOpts = {separator: str}; +refOpts = {contextPrefix: str}; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var validErr: Joi.ValidationError = null; +var validErrItem: Joi.ValidationErrorItem; + +validErrItem= { + message: str, + type: str, + path: str +}; + +validErrItem = { + message: str, + type: str, + path: str, + options: validOpts +}; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +schema = anySchema; +schema = numSchema; +schema = strSchema; +schema = arrSchema; +schema = boolSchema; +schema = binSchema; +schema = dateSchema; +schema = funcSchema; +schema = objSchema; + +schema = ref; + +anySchema = anySchema; +anySchema = numSchema; +anySchema = strSchema; +anySchema = arrSchema; +anySchema = boolSchema; +anySchema = binSchema; +anySchema = dateSchema; +anySchema = funcSchema; +anySchema = objSchema; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var schemaMap: Joi.SchemaMap = null; + +schemaMap = { + a: numSchema, + b: strSchema +}; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +anySchema = Joi.any(); + +namespace common { + anySchema = anySchema.allow(x); + anySchema = anySchema.allow(x, x); + anySchema = anySchema.allow([x, x, x]); + anySchema = anySchema.valid(x); + anySchema = anySchema.valid(x, x); + anySchema = anySchema.valid([x, x, x]); + anySchema = anySchema.only(x); + anySchema = anySchema.only(x, x); + anySchema = anySchema.only([x, x, x]); + anySchema = anySchema.equal(x); + anySchema = anySchema.equal(x, x); + anySchema = anySchema.equal([x, x, x]); + anySchema = anySchema.invalid(x); + anySchema = anySchema.invalid(x, x); + anySchema = anySchema.invalid([x, x, x]); + anySchema = anySchema.disallow(x); + anySchema = anySchema.disallow(x, x); + anySchema = anySchema.disallow([x, x, x]); + anySchema = anySchema.not(x); + anySchema = anySchema.not(x, x); + anySchema = anySchema.not([x, x, x]); + + anySchema = anySchema.default(); + anySchema = anySchema.default(x); + anySchema = anySchema.default(x, str); + + anySchema = anySchema.required(); + anySchema = anySchema.optional(); + anySchema = anySchema.forbidden(); + anySchema = anySchema.strip(); + + anySchema = anySchema.description(str); + anySchema = anySchema.notes(str); + anySchema = anySchema.notes(strArr); + anySchema = anySchema.tags(str); + anySchema = anySchema.tags(strArr); + + anySchema = anySchema.meta(obj); + anySchema = anySchema.example(obj); + anySchema = anySchema.unit(str); + + anySchema = anySchema.options(validOpts); + anySchema = anySchema.strict(); + anySchema = anySchema.strict(bool); + anySchema = anySchema.concat(x); + + altSchema = anySchema.when(str, whenOpts); + altSchema = anySchema.when(ref, whenOpts); + + anySchema = anySchema.label(str); + anySchema = anySchema.raw(); + anySchema = anySchema.raw(bool); + anySchema = anySchema.empty(); + anySchema = anySchema.empty(str); + anySchema = anySchema.empty(anySchema); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +arrSchema = Joi.array(); + +arrSchema = arrSchema.sparse(); +arrSchema = arrSchema.sparse(bool); +arrSchema = arrSchema.single(); +arrSchema = arrSchema.single(bool); +arrSchema = arrSchema.min(num); +arrSchema = arrSchema.max(num); +arrSchema = arrSchema.length(num); +arrSchema = arrSchema.unique(); + +arrSchema = arrSchema.items(numSchema); +arrSchema = arrSchema.items(numSchema, strSchema); +arrSchema = arrSchema.items([numSchema, strSchema]); + + +// - - - - - - - - + +namespace common_copy_paste { + // use search & replace from any + arrSchema = arrSchema.allow(x); + arrSchema = arrSchema.allow(x, x); + arrSchema = arrSchema.allow([x, x, x]); + arrSchema = arrSchema.valid(x); + arrSchema = arrSchema.valid(x, x); + arrSchema = arrSchema.valid([x, x, x]); + arrSchema = arrSchema.only(x); + arrSchema = arrSchema.only(x, x); + arrSchema = arrSchema.only([x, x, x]); + arrSchema = arrSchema.equal(x); + arrSchema = arrSchema.equal(x, x); + arrSchema = arrSchema.equal([x, x, x]); + arrSchema = arrSchema.invalid(x); + arrSchema = arrSchema.invalid(x, x); + arrSchema = arrSchema.invalid([x, x, x]); + arrSchema = arrSchema.disallow(x); + arrSchema = arrSchema.disallow(x, x); + arrSchema = arrSchema.disallow([x, x, x]); + arrSchema = arrSchema.not(x); + arrSchema = arrSchema.not(x, x); + arrSchema = arrSchema.not([x, x, x]); + + arrSchema = arrSchema.default(x); + + arrSchema = arrSchema.required(); + arrSchema = arrSchema.optional(); + arrSchema = arrSchema.forbidden(); + + arrSchema = arrSchema.description(str); + arrSchema = arrSchema.notes(str); + arrSchema = arrSchema.notes(strArr); + arrSchema = arrSchema.tags(str); + arrSchema = arrSchema.tags(strArr); + + arrSchema = arrSchema.meta(obj); + arrSchema = arrSchema.example(obj); + arrSchema = arrSchema.unit(str); + + arrSchema = arrSchema.options(validOpts); + arrSchema = arrSchema.strict(); + arrSchema = arrSchema.concat(x); + + altSchema = arrSchema.when(str, whenOpts); + altSchema = arrSchema.when(ref, whenOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +boolSchema = Joi.bool(); +boolSchema = Joi.boolean(); + +namespace common_copy_paste { + boolSchema = boolSchema.allow(x); + boolSchema = boolSchema.allow(x, x); + boolSchema = boolSchema.allow([x, x, x]); + boolSchema = boolSchema.valid(x); + boolSchema = boolSchema.valid(x, x); + boolSchema = boolSchema.valid([x, x, x]); + boolSchema = boolSchema.only(x); + boolSchema = boolSchema.only(x, x); + boolSchema = boolSchema.only([x, x, x]); + boolSchema = boolSchema.equal(x); + boolSchema = boolSchema.equal(x, x); + boolSchema = boolSchema.equal([x, x, x]); + boolSchema = boolSchema.invalid(x); + boolSchema = boolSchema.invalid(x, x); + boolSchema = boolSchema.invalid([x, x, x]); + boolSchema = boolSchema.disallow(x); + boolSchema = boolSchema.disallow(x, x); + boolSchema = boolSchema.disallow([x, x, x]); + boolSchema = boolSchema.not(x); + boolSchema = boolSchema.not(x, x); + boolSchema = boolSchema.not([x, x, x]); + + boolSchema = boolSchema.default(x); + + boolSchema = boolSchema.required(); + boolSchema = boolSchema.optional(); + boolSchema = boolSchema.forbidden(); + + boolSchema = boolSchema.description(str); + boolSchema = boolSchema.notes(str); + boolSchema = boolSchema.notes(strArr); + boolSchema = boolSchema.tags(str); + boolSchema = boolSchema.tags(strArr); + + boolSchema = boolSchema.meta(obj); + boolSchema = boolSchema.example(obj); + boolSchema = boolSchema.unit(str); + + boolSchema = boolSchema.options(validOpts); + boolSchema = boolSchema.strict(); + boolSchema = boolSchema.concat(x); + + altSchema = boolSchema.when(str, whenOpts); + altSchema = boolSchema.when(ref, whenOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +binSchema = Joi.binary(); + +binSchema = binSchema.encoding(str); +binSchema = binSchema.min(num); +binSchema = binSchema.max(num); +binSchema = binSchema.length(num); + +namespace common { + binSchema = binSchema.allow(x); + binSchema = binSchema.allow(x, x); + binSchema = binSchema.allow([x, x, x]); + binSchema = binSchema.valid(x); + binSchema = binSchema.valid(x, x); + binSchema = binSchema.valid([x, x, x]); + binSchema = binSchema.only(x); + binSchema = binSchema.only(x, x); + binSchema = binSchema.only([x, x, x]); + binSchema = binSchema.equal(x); + binSchema = binSchema.equal(x, x); + binSchema = binSchema.equal([x, x, x]); + binSchema = binSchema.invalid(x); + binSchema = binSchema.invalid(x, x); + binSchema = binSchema.invalid([x, x, x]); + binSchema = binSchema.disallow(x); + binSchema = binSchema.disallow(x, x); + binSchema = binSchema.disallow([x, x, x]); + binSchema = binSchema.not(x); + binSchema = binSchema.not(x, x); + binSchema = binSchema.not([x, x, x]); + + binSchema = binSchema.default(x); + + binSchema = binSchema.required(); + binSchema = binSchema.optional(); + binSchema = binSchema.forbidden(); + + binSchema = binSchema.description(str); + binSchema = binSchema.notes(str); + binSchema = binSchema.notes(strArr); + binSchema = binSchema.tags(str); + binSchema = binSchema.tags(strArr); + + binSchema = binSchema.meta(obj); + binSchema = binSchema.example(obj); + binSchema = binSchema.unit(str); + + binSchema = binSchema.options(validOpts); + binSchema = binSchema.strict(); + binSchema = binSchema.concat(x); + + altSchema = binSchema.when(str, whenOpts); + altSchema = binSchema.when(ref, whenOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +dateSchema = Joi.date(); + +dateSchema = dateSchema.min(date); +dateSchema = dateSchema.max(date); + +dateSchema = dateSchema.min(str); +dateSchema = dateSchema.max(str); + +dateSchema = dateSchema.min(num); +dateSchema = dateSchema.max(num); + +dateSchema = dateSchema.min(ref); +dateSchema = dateSchema.max(ref); + +dateSchema = dateSchema.format(str); +dateSchema = dateSchema.format(strArr); + +dateSchema = dateSchema.iso(); + +namespace common { + dateSchema = dateSchema.allow(x); + dateSchema = dateSchema.allow(x, x); + dateSchema = dateSchema.allow([x, x, x]); + dateSchema = dateSchema.valid(x); + dateSchema = dateSchema.valid(x, x); + dateSchema = dateSchema.valid([x, x, x]); + dateSchema = dateSchema.only(x); + dateSchema = dateSchema.only(x, x); + dateSchema = dateSchema.only([x, x, x]); + dateSchema = dateSchema.equal(x); + dateSchema = dateSchema.equal(x, x); + dateSchema = dateSchema.equal([x, x, x]); + dateSchema = dateSchema.invalid(x); + dateSchema = dateSchema.invalid(x, x); + dateSchema = dateSchema.invalid([x, x, x]); + dateSchema = dateSchema.disallow(x); + dateSchema = dateSchema.disallow(x, x); + dateSchema = dateSchema.disallow([x, x, x]); + dateSchema = dateSchema.not(x); + dateSchema = dateSchema.not(x, x); + dateSchema = dateSchema.not([x, x, x]); + + dateSchema = dateSchema.default(x); + + dateSchema = dateSchema.required(); + dateSchema = dateSchema.optional(); + dateSchema = dateSchema.forbidden(); + + dateSchema = dateSchema.description(str); + dateSchema = dateSchema.notes(str); + dateSchema = dateSchema.notes(strArr); + dateSchema = dateSchema.tags(str); + dateSchema = dateSchema.tags(strArr); + + dateSchema = dateSchema.meta(obj); + dateSchema = dateSchema.example(obj); + dateSchema = dateSchema.unit(str); + + dateSchema = dateSchema.options(validOpts); + dateSchema = dateSchema.strict(); + dateSchema = dateSchema.concat(x); + + altSchema = dateSchema.when(str, whenOpts); + altSchema = dateSchema.when(ref, whenOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +funcSchema = Joi.func(); + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +numSchema = Joi.number(); + +numSchema = numSchema.min(num); +numSchema = numSchema.min(ref); +numSchema = numSchema.max(num); +numSchema = numSchema.max(ref); +numSchema = numSchema.greater(num); +numSchema = numSchema.greater(ref); +numSchema = numSchema.less(num); +numSchema = numSchema.less(ref); +numSchema = numSchema.integer(); +numSchema = numSchema.precision(num); +numSchema = numSchema.multiple(num); +numSchema = numSchema.positive(); +numSchema = numSchema.negative(); + +namespace common { + numSchema = numSchema.allow(x); + numSchema = numSchema.allow(x, x); + numSchema = numSchema.allow([x, x, x]); + numSchema = numSchema.valid(x); + numSchema = numSchema.valid(x, x); + numSchema = numSchema.valid([x, x, x]); + numSchema = numSchema.only(x); + numSchema = numSchema.only(x, x); + numSchema = numSchema.only([x, x, x]); + numSchema = numSchema.equal(x); + numSchema = numSchema.equal(x, x); + numSchema = numSchema.equal([x, x, x]); + numSchema = numSchema.invalid(x); + numSchema = numSchema.invalid(x, x); + numSchema = numSchema.invalid([x, x, x]); + numSchema = numSchema.disallow(x); + numSchema = numSchema.disallow(x, x); + numSchema = numSchema.disallow([x, x, x]); + numSchema = numSchema.not(x); + numSchema = numSchema.not(x, x); + numSchema = numSchema.not([x, x, x]); + + numSchema = numSchema.default(x); + + numSchema = numSchema.required(); + numSchema = numSchema.optional(); + numSchema = numSchema.forbidden(); + + numSchema = numSchema.description(str); + numSchema = numSchema.notes(str); + numSchema = numSchema.notes(strArr); + numSchema = numSchema.tags(str); + numSchema = numSchema.tags(strArr); + + numSchema = numSchema.meta(obj); + numSchema = numSchema.example(obj); + numSchema = numSchema.unit(str); + + numSchema = numSchema.options(validOpts); + numSchema = numSchema.strict(); + numSchema = numSchema.concat(x); + + altSchema = numSchema.when(str, whenOpts); + altSchema = numSchema.when(ref, whenOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +objSchema = Joi.object(); +objSchema = Joi.object(schemaMap); + +objSchema = objSchema.keys(); +objSchema = objSchema.keys(schemaMap); + +objSchema = objSchema.min(num); +objSchema = objSchema.max(num); +objSchema = objSchema.length(num); + +objSchema = objSchema.pattern(exp, schema); + +objSchema = objSchema.and(str); +objSchema = objSchema.and(str, str); +objSchema = objSchema.and(str, str, str); +objSchema = objSchema.and(strArr); + +objSchema = objSchema.nand(str); +objSchema = objSchema.nand(str, str); +objSchema = objSchema.nand(str, str, str); +objSchema = objSchema.nand(strArr); + +objSchema = objSchema.or(str); +objSchema = objSchema.or(str, str); +objSchema = objSchema.or(str, str, str); +objSchema = objSchema.or(strArr); + +objSchema = objSchema.xor(str); +objSchema = objSchema.xor(str, str); +objSchema = objSchema.xor(str, str, str); +objSchema = objSchema.xor(strArr); + +objSchema = objSchema.with(str, str); +objSchema = objSchema.with(str, strArr); + +objSchema = objSchema.without(str, str); +objSchema = objSchema.without(str, strArr); + +objSchema = objSchema.rename(str, str); +objSchema = objSchema.rename(str, str, renOpts); + +objSchema = objSchema.assert(str, schema); +objSchema = objSchema.assert(str, schema, str); +objSchema = objSchema.assert(ref, schema); +objSchema = objSchema.assert(ref, schema, str); + +objSchema = objSchema.unknown(); +objSchema = objSchema.unknown(bool); + +objSchema = objSchema.type(func); +objSchema = objSchema.type(func, str); + +objSchema = objSchema.requiredKeys(str); +objSchema = objSchema.requiredKeys(str, str); +objSchema = objSchema.requiredKeys(strArr); + +objSchema = objSchema.optionalKeys(str); +objSchema = objSchema.optionalKeys(str, str); +objSchema = objSchema.optionalKeys(strArr); + +namespace common { + objSchema = objSchema.allow(x); + objSchema = objSchema.allow(x, x); + objSchema = objSchema.allow([x, x, x]); + objSchema = objSchema.valid(x); + objSchema = objSchema.valid(x, x); + objSchema = objSchema.valid([x, x, x]); + objSchema = objSchema.only(x); + objSchema = objSchema.only(x, x); + objSchema = objSchema.only([x, x, x]); + objSchema = objSchema.equal(x); + objSchema = objSchema.equal(x, x); + objSchema = objSchema.equal([x, x, x]); + objSchema = objSchema.invalid(x); + objSchema = objSchema.invalid(x, x); + objSchema = objSchema.invalid([x, x, x]); + objSchema = objSchema.disallow(x); + objSchema = objSchema.disallow(x, x); + objSchema = objSchema.disallow([x, x, x]); + objSchema = objSchema.not(x); + objSchema = objSchema.not(x, x); + objSchema = objSchema.not([x, x, x]); + + objSchema = objSchema.default(x); + + objSchema = objSchema.required(); + objSchema = objSchema.optional(); + objSchema = objSchema.forbidden(); + + objSchema = objSchema.description(str); + objSchema = objSchema.notes(str); + objSchema = objSchema.notes(strArr); + objSchema = objSchema.tags(str); + objSchema = objSchema.tags(strArr); + + objSchema = objSchema.meta(obj); + objSchema = objSchema.example(obj); + objSchema = objSchema.unit(str); + + objSchema = objSchema.options(validOpts); + objSchema = objSchema.strict(); + objSchema = objSchema.concat(x); + + altSchema = objSchema.when(str, whenOpts); + altSchema = objSchema.when(ref, whenOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +strSchema = Joi.string(); + +strSchema = strSchema.insensitive(); +strSchema = strSchema.min(num); +strSchema = strSchema.min(num, str); +strSchema = strSchema.min(ref); +strSchema = strSchema.min(ref, str); +strSchema = strSchema.max(num); +strSchema = strSchema.max(num, str); +strSchema = strSchema.max(ref); +strSchema = strSchema.max(ref, str); +strSchema = strSchema.creditCard(); +strSchema = strSchema.length(num); +strSchema = strSchema.length(num, str); +strSchema = strSchema.length(ref); +strSchema = strSchema.length(ref, str); +strSchema = strSchema.regex(exp); +strSchema = strSchema.regex(exp, str); +strSchema = strSchema.replace(exp, str); +strSchema = strSchema.replace(str, str); +strSchema = strSchema.alphanum(); +strSchema = strSchema.token(); +strSchema = strSchema.email(); +strSchema = strSchema.email(emailOpts); +strSchema = strSchema.ip(); +strSchema = strSchema.ip(ipOpts); +strSchema = strSchema.uri(); +strSchema = strSchema.uri(uriOpts); +strSchema = strSchema.guid(); +strSchema = strSchema.hex(); +strSchema = strSchema.hostname(); +strSchema = strSchema.isoDate(); +strSchema = strSchema.lowercase(); +strSchema = strSchema.uppercase(); +strSchema = strSchema.trim(); + +namespace common { + strSchema = strSchema.allow(x); + strSchema = strSchema.allow(x, x); + strSchema = strSchema.allow([x, x, x]); + strSchema = strSchema.valid(x); + strSchema = strSchema.valid(x, x); + strSchema = strSchema.valid([x, x, x]); + strSchema = strSchema.only(x); + strSchema = strSchema.only(x, x); + strSchema = strSchema.only([x, x, x]); + strSchema = strSchema.equal(x); + strSchema = strSchema.equal(x, x); + strSchema = strSchema.equal([x, x, x]); + strSchema = strSchema.invalid(x); + strSchema = strSchema.invalid(x, x); + strSchema = strSchema.invalid([x, x, x]); + strSchema = strSchema.disallow(x); + strSchema = strSchema.disallow(x, x); + strSchema = strSchema.disallow([x, x, x]); + strSchema = strSchema.not(x); + strSchema = strSchema.not(x, x); + strSchema = strSchema.not([x, x, x]); + + strSchema = strSchema.default(x); + + strSchema = strSchema.required(); + strSchema = strSchema.optional(); + strSchema = strSchema.forbidden(); + + strSchema = strSchema.description(str); + strSchema = strSchema.notes(str); + strSchema = strSchema.notes(strArr); + strSchema = strSchema.tags(str); + strSchema = strSchema.tags(strArr); + + strSchema = strSchema.meta(obj); + strSchema = strSchema.example(obj); + strSchema = strSchema.unit(str); + + strSchema = strSchema.options(validOpts); + strSchema = strSchema.strict(); + strSchema = strSchema.concat(x); + + altSchema = strSchema.when(str, whenOpts); + altSchema = strSchema.when(ref, whenOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +schema = Joi.alternatives(schemaArr); +schema = Joi.alternatives(schema, anySchema, boolSchema); + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +Joi.validate(value, obj); +Joi.validate(value, schema); +Joi.validate(value, schema, validOpts); +Joi.validate(value, schema, validOpts, (err, value) => { + x = value; + str = err.message; + str = err.details[0].path; + str = err.details[0].message; + str = err.details[0].type; +}); +Joi.validate(value, schema, (err, value) => { + x = value; + str = err.message; + str = err.details[0].path; + str = err.details[0].message; + str = err.details[0].type; +}); +// variant +Joi.validate(num, schema, validOpts, (err, value) => { + num = value; +}); + +// plain opts +Joi.validate(value, {}); + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +schema = Joi.compile(obj); + +Joi.assert(obj, schema); +Joi.assert(obj, schema, str); +Joi.assert(obj, schema, err); + +ref = Joi.ref(str, refOpts); +ref = Joi.ref(str); diff --git a/joi/joi-6.5.0.d.ts b/joi/joi-6.5.0.d.ts new file mode 100644 index 0000000000..d9ee7c20d1 --- /dev/null +++ b/joi/joi-6.5.0.d.ts @@ -0,0 +1,778 @@ +// Type definitions for joi v6.5.0 +// Project: https://github.com/spumko/joi +// Definitions by: Bart van der Schoor , Laurence Dougal Myers , Christopher Glantschnig , David Broder-Rodgers +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// TODO express type of Schema in a type-parameter (.default, .valid, .example etc) + +declare module 'joi' { + + export interface ValidationOptions { + /** + * when true, stops validation on the first error, otherwise returns all the errors found. Defaults to true. + */ + abortEarly?: boolean; + /** + * when true, attempts to cast values to the required types (e.g. a string to a number). Defaults to true. + */ + convert?: boolean; + /** + * when true, allows object to contain unknown keys which are ignored. Defaults to false. + */ + allowUnknown?: boolean; + /** + * when true, ignores unknown keys with a function value. Defaults to false. + */ + skipFunctions?: boolean; + /** + * when true, unknown keys are deleted (only when value is an object). Defaults to false. + */ + stripUnknown?: boolean; + /** + * overrides individual error messages. Defaults to no override ({}). + */ + language?: Object; + /** + * sets the default presence requirements. Supported modes: 'optional', 'required', and 'forbidden'. Defaults to 'optional'. + */ + presence?: string; + /** + * provides an external data set to be used in references + */ + context?: Object; + } + + export interface RenameOptions { + /** + * if true, does not delete the old key name, keeping both the new and old keys in place. Defaults to false. + */ + alias?: boolean; + /** + * if true, allows renaming multiple keys to the same destination where the last rename wins. Defaults to false. + */ + multiple?: boolean; + /** + * if true, allows renaming a key over an existing key. Defaults to false. + */ + override?: boolean; + /** + * if true, skip renaming of a key if it's undefined. Defaults to false. + */ + ignoreUndefined?: boolean; + } + + export interface EmailOptions { + /** + * Numerical threshold at which an email address is considered invalid + */ + errorLevel?: number | boolean; + /** + * Specifies a list of acceptable TLDs. + */ + tldWhitelist?: string[] | Object; + /** + * Number of atoms required for the domain. Be careful since some domains, such as io, directly allow email. + */ + minDomainAtoms?: number; + } + + export interface IpOptions { + /** + * One or more IP address versions to validate against. Valid values: ipv4, ipv6, ipvfuture + */ + version ?: string | string[]; + /** + * Used to determine if a CIDR is allowed or not. Valid values: optional, required, forbidden + */ + cidr?: string; + } + + export interface UriOptions { + /** + * Specifies one or more acceptable Schemes, should only include the scheme name. + * Can be an Array or String (strings are automatically escaped for use in a Regular Expression). + */ + scheme ?: string | RegExp | Array; + } + + export interface WhenOptions { + /** + * the required condition joi type. + */ + is: T; + /** + * the alternative schema type if the condition is true. Required if otherwise is missing. + */ + then?: Schema; + /** + * the alternative schema type if the condition is false. Required if then is missing + */ + otherwise?: Schema; + } + + export interface ReferenceOptions { + separator?: string; + contextPrefix?: string; + } + + export interface IPOptions { + version?: Array; + cidr?: string + } + + export interface ValidationError extends Error { + message: string; + details: ValidationErrorItem[]; + simple(): string; + annotated(): string; + } + + export interface ValidationErrorItem { + message: string; + type: string; + path: string; + options?: ValidationOptions; + } + + export interface ValidationResult { + error: ValidationError; + value: T; + } + + export interface SchemaMap { + [key: string]: Schema; + } + + export interface Schema extends AnySchema { + + } + + export interface Reference extends Schema { + + } + + export interface AnySchema> { + /** + * Whitelists a value + */ + allow(value: any, ...values: any[]): T; + allow(values: any[]): T; + + /** + * Adds the provided values into the allowed whitelist and marks them as the only valid values allowed. + */ + valid(value: any, ...values: any[]): T; + valid(values: any[]): T; + only(value: any, ...values : any[]): T; + only(values: any[]): T; + equal(value: any, ...values : any[]): T; + equal(values: any[]): T; + + /** + * Blacklists a value + */ + invalid(value: any, ...values: any[]): T; + invalid(values: any[]): T; + disallow(value: any, ...values : any[]): T; + disallow(values: any[]): T; + not(value: any, ...values : any[]): T; + not(values: any[]): T; + + /** + * Marks a key as required which will not allow undefined as value. All keys are optional by default. + */ + required(): T; + + /** + * Marks a key as optional which will allow undefined as values. Used to annotate the schema for readability as all keys are optional by default. + */ + optional(): T; + + /** + * Marks a key as forbidden which will not allow any value except undefined. Used to explicitly forbid keys. + */ + forbidden(): T; + + /** + * Marks a key to be removed from a resulting object or array after validation. Used to sanitize output. + */ + strip(): T; + + /** + * Annotates the key + */ + description(desc: string): T; + + /** + * Annotates the key + */ + notes(notes: string): T; + notes(notes: string[]): T; + + /** + * Annotates the key + */ + tags(notes: string): T; + tags(notes: string[]): T; + + /** + * Attaches metadata to the key. + */ + meta(meta: Object): T; + + /** + * Annotates the key with an example value, must be valid. + */ + example(value: any): T; + + /** + * Annotates the key with an unit name. + */ + unit(name: string): T; + + /** + * Overrides the global validate() options for the current key and any sub-key. + */ + options(options: ValidationOptions): T; + + /** + * Sets the options.convert options to false which prevent type casting for the current key and any child keys. + */ + strict(isStrict?: boolean): T; + + /** + * Sets a default value if the original value is undefined. + * @param value - the value. + * value supports references. + * value may also be a function which returns the default value. + * If value is specified as a function that accepts a single parameter, that parameter will be a context + * object that can be used to derive the resulting value. This clones the object however, which incurs some + * overhead so if you don't need access to the context define your method so that it does not accept any + * parameters. + * Without any value, default has no effect, except for object that will then create nested defaults + * (applying inner defaults of that object). + * + * Note that if value is an object, any changes to the object after default() is called will change the + * reference and any future assignment. + * + * Additionally, when specifying a method you must either have a description property on your method or the + * second parameter is required. + */ + default(value: any, description?: string): T; + default(): T; + + /** + * Returns a new type that is the result of adding the rules of one type to another. + */ + concat(schema: T): T; + + /** + * Converts the type into an alternatives type where the conditions are merged into the type definition where: + */ + when(ref: string, options: WhenOptions): AlternativesSchema; + when(ref: Reference, options: WhenOptions): AlternativesSchema; + + /** + * Overrides the key name in error messages. + */ + label(name: string): T; + + /** + * Outputs the original untouched value instead of the casted value. + */ + raw(isRaw?: boolean): T; + + /** + * Considers anything that matches the schema to be empty (undefined). + * @param schema - any object or joi schema to match. An undefined schema unsets that rule. + */ + empty(schema?: any) : T; + } + + export interface BooleanSchema extends AnySchema { + + } + + export interface NumberSchema extends AnySchema { + /** + * Specifies the minimum value. + * It can also be a reference to another field. + */ + min(limit: number): NumberSchema; + min(limit: Reference): NumberSchema; + + /** + * Specifies the maximum value. + * It can also be a reference to another field. + */ + max(limit: number): NumberSchema; + max(limit: Reference): NumberSchema; + + /** + * Specifies that the value must be greater than limit. + * It can also be a reference to another field. + */ + greater(limit: number): NumberSchema; + greater(limit: Reference): NumberSchema; + + /** + * Specifies that the value must be less than limit. + * It can also be a reference to another field. + */ + less(limit: number): NumberSchema; + less(limit: Reference): NumberSchema; + + /** + * Requires the number to be an integer (no floating point). + */ + integer(): NumberSchema; + + /** + * Specifies the maximum number of decimal places where: + * limit - the maximum number of decimal places allowed. + */ + precision(limit: number): NumberSchema; + + /** + * Specifies that the value must be a multiple of base. + */ + multiple(base: number): NumberSchema; + + /** + * Requires the number to be positive. + */ + positive(): NumberSchema; + + /** + * Requires the number to be negative. + */ + negative(): NumberSchema; + } + + export interface StringSchema extends AnySchema { + /** + * Allows the value to match any whitelist of blacklist item in a case insensitive comparison. + */ + insensitive(): StringSchema; + + /** + * Specifies the minimum number string characters. + * @param limit - the minimum number of string characters required. It can also be a reference to another field. + * @param encoding - if specified, the string length is calculated in bytes using the provided encoding. + */ + min(limit: number, encoding?: string): StringSchema; + min(limit: Reference, encoding?: string): StringSchema; + + /** + * Specifies the maximum number of string characters. + * @param limit - the maximum number of string characters allowed. It can also be a reference to another field. + * @param encoding - if specified, the string length is calculated in bytes using the provided encoding. + */ + max(limit: number, encoding?: string): StringSchema; + max(limit: Reference, encoding?: string): StringSchema; + + /** + * Requires the number to be a credit card number (Using Lunh Algorithm). + */ + creditCard(): StringSchema; + + /** + * Specifies the exact string length required + * @param limit - the required string length. It can also be a reference to another field. + * @param encoding - if specified, the string length is calculated in bytes using the provided encoding. + */ + length(limit: number, encoding?: string): StringSchema; + length(limit: Reference, encoding?: string): StringSchema; + + /** + * Defines a regular expression rule. + * @param pattern - a regular expression object the string value must match against. + * @param name - optional name for patterns (useful with multiple patterns). Defaults to 'required'. + */ + regex(pattern: RegExp, name?: string): StringSchema; + + /** + * Replace characters matching the given pattern with the specified replacement string where: + * @param pattern - a regular expression object to match against, or a string of which all occurrences will be replaced. + * @param replacement - the string that will replace the pattern. + */ + replace(pattern: RegExp, replacement: string): StringSchema; + replace(pattern: string, replacement: string): StringSchema; + + /** + * Requires the string value to only contain a-z, A-Z, and 0-9. + */ + alphanum(): StringSchema; + + /** + * Requires the string value to only contain a-z, A-Z, 0-9, and underscore _. + */ + token(): StringSchema; + + /** + * Requires the string value to be a valid email address. + */ + email(options?: EmailOptions): StringSchema; + + /** + * Requires the string value to be a valid ip address. + */ + ip(options?: IpOptions): StringSchema; + + /** + * Requires the string value to be a valid RFC 3986 URI. + */ + uri(options?: UriOptions): StringSchema; + + /** + * Requires the string value to be a valid GUID. + */ + guid(): StringSchema; + + /** + * Requires the string value to be a valid hexadecimal string. + */ + hex(): StringSchema; + + /** + * Requires the string value to be a valid hostname as per RFC1123. + */ + hostname(): StringSchema; + + /** + * Requires the string value to be in valid ISO 8601 date format. + */ + isoDate(): StringSchema; + + /** + * Requires the string value to be all lowercase. If the validation convert option is on (enabled by default), the string will be forced to lowercase. + */ + lowercase(): StringSchema; + + /** + * Requires the string value to be all uppercase. If the validation convert option is on (enabled by default), the string will be forced to uppercase. + */ + uppercase(): StringSchema; + + /** + * Requires the string value to contain no whitespace before or after. If the validation convert option is on (enabled by default), the string will be trimmed. + */ + trim(): StringSchema; + } + + export interface ArraySchema extends AnySchema { + /** + * Allow this array to be sparse. + * enabled can be used with a falsy value to go back to the default behavior. + */ + sparse(enabled?: any): ArraySchema; + + /** + * Allow single values to be checked against rules as if it were provided as an array. + * enabled can be used with a falsy value to go back to the default behavior. + */ + single(enabled?: any): ArraySchema; + + /** + * List the types allowed for the array values. + * type can be an array of values, or multiple values can be passed as individual arguments. + * If a given type is .required() then there must be a matching item in the array. + * If a type is .forbidden() then it cannot appear in the array. + * Required items can be added multiple times to signify that multiple items must be found. + * Errors will contain the number of items that didn't match. + * Any unmatched item having a label will be mentioned explicitly. + * + * @param type - a joi schema object to validate each array item against. + */ + items(type: Schema, ...types: Schema[]): ArraySchema; + items(types: Schema[]): ArraySchema; + + /** + * Specifies the minimum number of items in the array. + */ + min(limit: number): ArraySchema; + + /** + * Specifies the maximum number of items in the array. + */ + max(limit: number): ArraySchema; + + /** + * Specifies the exact number of items in the array. + */ + length(limit: number): ArraySchema; + + /** + * Requires the array values to be unique. + * Be aware that a deep equality is performed on elements of the array having a type of object, + * a performance penalty is to be expected for this kind of operation. + */ + unique(): ArraySchema; + } + + export interface ObjectSchema extends AnySchema { + /** + * Sets the allowed object keys. + */ + keys(schema?: SchemaMap): ObjectSchema; + + /** + * Specifies the minimum number of keys in the object. + */ + min(limit: number): ObjectSchema; + + /** + * Specifies the maximum number of keys in the object. + */ + max(limit: number): ObjectSchema; + + /** + * Specifies the exact number of keys in the object. + */ + length(limit: number): ObjectSchema; + + /** + * Specify validation rules for unknown keys matching a pattern. + */ + pattern(regex: RegExp, schema: Schema): ObjectSchema; + + /** + * Defines an all-or-nothing relationship between keys where if one of the peers is present, all of them are required as well. + * @param peers - the key names of which if one present, all are required. peers can be a single string value, + * an array of string values, or each peer provided as an argument. + */ + and(peer1: string, ...peers: string[]): ObjectSchema; + and(peers: string[]): ObjectSchema; + + /** + * Defines a relationship between keys where not all peers can be present at the same time. + * @param peers - the key names of which if one present, the others may not all be present. + * peers can be a single string value, an array of string values, or each peer provided as an argument. + */ + nand(peer1: string, ...peers: string[]): ObjectSchema; + nand(peers: string[]): ObjectSchema; + + /** + * Defines a relationship between keys where one of the peers is required (and more than one is allowed). + */ + or(peer1: string, ...peers: string[]): ObjectSchema; + or(peers: string[]): ObjectSchema; + + /** + * Defines an exclusive relationship between a set of keys. one of them is required but not at the same time where: + */ + xor(peer1: string, ...peers: string[]): ObjectSchema; + xor(peers: string[]): ObjectSchema; + + /** + * Requires the presence of other keys whenever the specified key is present. + */ + with(key: string, peers: string): ObjectSchema; + with(key: string, peers: string[]): ObjectSchema; + + /** + * Forbids the presence of other keys whenever the specified is present. + */ + without(key: string, peers: string): ObjectSchema; + without(key: string, peers: string[]): ObjectSchema; + + /** + * Renames a key to another name (deletes the renamed key). + */ + rename(from: string, to: string, options?: RenameOptions): ObjectSchema; + + /** + * Verifies an assertion where. + */ + assert(ref: string, schema: Schema, message?: string): ObjectSchema; + assert(ref: Reference, schema: Schema, message?: string): ObjectSchema; + + /** + * Overrides the handling of unknown keys for the scope of the current object only (does not apply to children). + */ + unknown(allow?: boolean): ObjectSchema; + + /** + * Requires the object to be an instance of a given constructor. + * + * @param constructor - the constructor function that the object must be an instance of. + * @param name - an alternate name to use in validation errors. This is useful when the constructor function does not have a name. + */ + type(constructor: Function, name?: string): ObjectSchema; + + /** + * Sets the specified children to required. + * + * @param children - can be a single string value, an array of string values, or each child provided as an argument. + * + * var schema = Joi.object().keys({ a: { b: Joi.number() }, c: { d: Joi.string() } }); + * var requiredSchema = schema.requiredKeys('', 'a.b', 'c', 'c.d'); + * + * Note that in this example '' means the current object, a is not required but b is, as well as c and d. + */ + requiredKeys(children: string): ObjectSchema; + requiredKeys(children: string[]): ObjectSchema; + requiredKeys(child:string, ...children: string[]): ObjectSchema; + + /** + * Sets the specified children to optional. + * + * @param children - can be a single string value, an array of string values, or each child provided as an argument. + * + * The behavior is exactly the same as requiredKeys. + */ + optionalKeys(children: string): ObjectSchema; + optionalKeys(children: string[]): ObjectSchema; + optionalKeys(child:string, ...children: string[]): ObjectSchema; + } + + export interface BinarySchema extends AnySchema { + /** + * Sets the string encoding format if a string input is converted to a buffer. + */ + encoding(encoding: string): BinarySchema; + + /** + * Specifies the minimum length of the buffer. + */ + min(limit: number): BinarySchema; + + /** + * Specifies the maximum length of the buffer. + */ + max(limit: number): BinarySchema; + + /** + * Specifies the exact length of the buffer: + */ + length(limit: number): BinarySchema; + } + + export interface DateSchema extends AnySchema { + + /** + * Specifies the oldest date allowed. + * Notes: 'now' can be passed in lieu of date so as to always compare relatively to the current date, + * allowing to explicitly ensure a date is either in the past or in the future. + * It can also be a reference to another field. + */ + min(date: Date): DateSchema; + min(date: number): DateSchema; + min(date: string): DateSchema; + min(date: Reference): DateSchema; + + /** + * Specifies the latest date allowed. + * Notes: 'now' can be passed in lieu of date so as to always compare relatively to the current date, + * allowing to explicitly ensure a date is either in the past or in the future. + * It can also be a reference to another field. + */ + max(date: Date): DateSchema; + max(date: number): DateSchema; + max(date: string): DateSchema; + max(date: Reference): DateSchema; + + /** + * Specifies the allowed date format: + * @param format - string or array of strings that follow the moment.js format. + */ + format(format: string): DateSchema; + format(format: string[]): DateSchema; + + /** + * Requires the string value to be in valid ISO 8601 date format. + */ + iso(): DateSchema; + } + + export interface FunctionSchema extends AnySchema { + + } + + export interface AlternativesSchema extends AnySchema { + try(schemas: Schema[]): AlternativesSchema; + when(ref: string, options: WhenOptions): AlternativesSchema; + when(ref: Reference, options: WhenOptions): AlternativesSchema; + } + + // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + + /** + * Generates a schema object that matches any data type. + */ + export function any(): Schema; + + /** + * Generates a schema object that matches an array data type. + */ + export function array(): ArraySchema; + + /** + * Generates a schema object that matches a boolean data type (as well as the strings 'true', 'false', 'yes', and 'no'). Can also be called via bool(). + */ + export function bool(): BooleanSchema; + + export function boolean(): BooleanSchema; + + /** + * Generates a schema object that matches a Buffer data type (as well as the strings which will be converted to Buffers). + */ + export function binary(): BinarySchema; + + /** + * Generates a schema object that matches a date type (as well as a JavaScript date string or number of milliseconds). + */ + export function date(): DateSchema; + + /** + * Generates a schema object that matches a function type. + */ + export function func(): FunctionSchema; + + /** + * Generates a schema object that matches a number data type (as well as strings that can be converted to numbers). + */ + export function number(): NumberSchema; + + /** + * Generates a schema object that matches an object data type (as well as JSON strings that parsed into objects). + */ + export function object(schema?: SchemaMap): ObjectSchema; + + /** + * Generates a schema object that matches a string data type. Note that empty strings are not allowed by default and must be enabled with allow(''). + */ + export function string(): StringSchema; + + /** + * Generates a type that will match one of the provided alternative schemas + */ + export function alternatives(types: Schema[]): Schema; + export function alternatives(type1: Schema, type2: Schema, ...types: Schema[]): Schema; + + /** + * Validates a value using the given schema and options. + */ + export function validate(value: T, schema: Schema, callback: (err: ValidationError, value: T) => void): void; + export function validate(value: T, schema: Object, callback: (err: ValidationError, value: T) => void): void; + export function validate(value: T, schema: Object, options?: ValidationOptions, callback?: (err: ValidationError, value: T) => void): ValidationResult; + + /** + * Converts literal schema definition to joi schema object (or returns the same back if already a joi schema object). + */ + export function compile(schema: Object): Schema; + + /** + * Validates a value against a schema and throws if validation fails. + * + * @param value - the value to validate. + * @param schema - the schema object. + * @param message - optional message string prefix added in front of the error message. may also be an Error object. + */ + export function assert(value: any, schema: Schema, message?: string | Error): void; + + /** + * Generates a reference to the value of the named key. + */ + export function ref(key: string, options?: ReferenceOptions): Reference; +} diff --git a/joi/joi-tests.ts b/joi/joi-tests.ts index a00543fe4e..e5bda7874c 100644 --- a/joi/joi-tests.ts +++ b/joi/joi-tests.ts @@ -231,16 +231,18 @@ arrSchema = arrSchema.sparse(); arrSchema = arrSchema.sparse(bool); arrSchema = arrSchema.single(); arrSchema = arrSchema.single(bool); +arrSchema = arrSchema.ordered(anySchema); +arrSchema = arrSchema.ordered(anySchema, numSchema, strSchema, arrSchema, boolSchema, binSchema, dateSchema, funcSchema, objSchema); arrSchema = arrSchema.min(num); arrSchema = arrSchema.max(num); arrSchema = arrSchema.length(num); arrSchema = arrSchema.unique(); + arrSchema = arrSchema.items(numSchema); arrSchema = arrSchema.items(numSchema, strSchema); arrSchema = arrSchema.items([numSchema, strSchema]); - // - - - - - - - - namespace common_copy_paste { @@ -420,6 +422,10 @@ dateSchema = dateSchema.format(strArr); dateSchema = dateSchema.iso(); +dateSchema = dateSchema.timestamp(); +dateSchema = dateSchema.timestamp('javascript'); +dateSchema = dateSchema.timestamp('unix'); + namespace common { dateSchema = dateSchema.allow(x); dateSchema = dateSchema.allow(x, x); @@ -471,6 +477,11 @@ namespace common { funcSchema = Joi.func(); +funcSchema = funcSchema.arity(num); +funcSchema = funcSchema.minArity(num); +funcSchema = funcSchema.maxArity(num); +funcSchema = funcSchema.ref(); + // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- numSchema = Joi.number(); @@ -770,5 +781,15 @@ Joi.assert(obj, schema); Joi.assert(obj, schema, str); Joi.assert(obj, schema, err); +Joi.attempt(obj, schema); +Joi.attempt(obj, schema, str); +Joi.attempt(obj, schema, err); + ref = Joi.ref(str, refOpts); ref = Joi.ref(str); + +Joi.isRef(ref); + +schema = Joi.reach(schema, ''); + +const Joi2 = Joi.extend({ name: '', base: schema }); diff --git a/joi/joi.d.ts b/joi/joi.d.ts index d9ee7c20d1..0153009dc2 100644 --- a/joi/joi.d.ts +++ b/joi/joi.d.ts @@ -1,6 +1,6 @@ -// Type definitions for joi v6.5.0 -// Project: https://github.com/spumko/joi -// Definitions by: Bart van der Schoor , Laurence Dougal Myers , Christopher Glantschnig , David Broder-Rodgers +// Type definitions for joi v9.0.0 +// Project: https://github.com/hapijs/joi +// Definitions by: Bart van der Schoor , Laurence Dougal Myers , Christopher Glantschnig , David Broder-Rodgers , Gael Magnan de Bornier // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TODO express type of Schema in a type-parameter (.default, .valid, .example etc) @@ -487,6 +487,13 @@ declare module 'joi' { items(type: Schema, ...types: Schema[]): ArraySchema; items(types: Schema[]): ArraySchema; + /** + * Lists the types in sequence order for the array values where: + * @param type - a joi schema object to validate against each array item in sequence order. type can be an array of values, or multiple values can be passed as individual arguments. + * If a given type is .required() then there must be a matching item with the same index position in the array. Errors will contain the number of items that didn't match. Any unmatched item having a label will be mentioned explicitly. + */ + ordered(type: Schema, ...types: Schema[]): ArraySchema; + /** * Specifies the minimum number of items in the array. */ @@ -683,10 +690,41 @@ declare module 'joi' { * Requires the string value to be in valid ISO 8601 date format. */ iso(): DateSchema; + + + /** + * Requires the value to be a timestamp interval from Unix Time. + * @param type - the type of timestamp (allowed values are unix or javascript [default]) + */ + timestamp(type?: 'javascript' | 'unix'): DateSchema; } export interface FunctionSchema extends AnySchema { + /** + * Specifies the arity of the function where: + * @param n - the arity expected. + */ + arity(n: number): FunctionSchema; + + + /** + * Specifies the minimal arity of the function where: + * @param n - the minimal arity expected. + */ + minArity(n: number): FunctionSchema; + + + /** + * Specifies the minimal arity of the function where: + * @param n - the minimal arity expected. + */ + maxArity(n: number): FunctionSchema; + + /** + * Requires the function to be a Joi reference. + */ + ref(): FunctionSchema; } export interface AlternativesSchema extends AnySchema { @@ -695,6 +733,33 @@ declare module 'joi' { when(ref: Reference, options: WhenOptions): AlternativesSchema; } + export interface Terms { + value: any; + state: { + key: string, + path: string, + parent: any + }; + options: ValidationOptions; + } + + export interface Rules { + name: string; + params?: ObjectSchema | { [key: string]: Schema }; + setup?: Function; + validate?: Function; + description: string | Function; + } + + export interface Extension { + name: string; + base?: Schema; + pre?: Function; + language?: {}; + describe?: Function; + rules?: Rules[]; + } + // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- /** @@ -771,8 +836,38 @@ declare module 'joi' { */ export function assert(value: any, schema: Schema, message?: string | Error): void; + + /** + * Validates a value against a schema, returns valid object, and throws if validation fails where: + * + * @param value - the value to validate. + * @param schema - the schema object. + * @param message - optional message string prefix added in front of the error message. may also be an Error object. + */ + export function attempt(value: any, schema: Schema, message?: string | Error): void; + + /** * Generates a reference to the value of the named key. */ export function ref(key: string, options?: ReferenceOptions): Reference; + + + /** + * Checks whether or not the provided argument is a reference. It's especially useful if you want to post-process error messages. + */ + export function isRef(ref: any): boolean; + + + /** + * Get a sub-schema of an existing schema based on a path. Path separator is a dot (.). + */ + export function reach(schema: Schema, path: string): Schema; + + + /** + * Creates a new Joi instance customized with the extension(s) you provide included. + */ + export function extend(extention: Extension): any; + } From 398bd742115e2b071ab3edf8b543b6df6fa62dc2 Mon Sep 17 00:00:00 2001 From: Charlie Arnold Date: Sat, 14 May 2016 10:52:52 -0700 Subject: [PATCH 076/402] react-select: change from ES6 export default to 'export =' to match javascript module (#9274) --- react-select/react-select-tests.tsx | 3 ++- react-select/react-select.d.ts | 9 +++++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/react-select/react-select-tests.tsx b/react-select/react-select-tests.tsx index 57bef47be2..d3298e55f8 100644 --- a/react-select/react-select-tests.tsx +++ b/react-select/react-select-tests.tsx @@ -5,7 +5,8 @@ import * as React from "react"; import * as ReactDOM from "react-dom"; -import Select, { Option, MenuRendererProps } from "react-select"; +import { Option, MenuRendererProps } from "react-select-props"; +import Select = require("react-select"); class SelectTest extends React.Component, {}> { diff --git a/react-select/react-select.d.ts b/react-select/react-select.d.ts index 5e671b0cd8..dc3ca16bc8 100644 --- a/react-select/react-select.d.ts +++ b/react-select/react-select.d.ts @@ -402,10 +402,15 @@ declare namespace ReactSelect { } declare module "react-select" { - const select: ReactSelect.ReactSelectClass; + const RS: ReactSelect.ReactSelectClass; + export = RS; +} + +declare module "react-select-props" { + interface Option extends ReactSelect.Option {} interface MenuRendererProps extends ReactSelect.MenuRendererProps {} - export default select; export { MenuRendererProps, Option }; } + From 73d6e70b5eb7fcd9383d4055d08a5b6edb82db77 Mon Sep 17 00:00:00 2001 From: Moes Date: Mon, 16 May 2016 10:12:32 +1000 Subject: [PATCH 077/402] Update jquery.pnotify.d.ts remove the I from the interface --- jquery.pnotify/jquery.pnotify.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/jquery.pnotify/jquery.pnotify.d.ts b/jquery.pnotify/jquery.pnotify.d.ts index c07347c1e8..7f727aa1b0 100644 --- a/jquery.pnotify/jquery.pnotify.d.ts +++ b/jquery.pnotify/jquery.pnotify.d.ts @@ -30,7 +30,7 @@ interface PNotifyLabel { } -interface IPNotifyconfirmButton { +interface PNotifyconfirmButton { text?: string; addClass?: string; /** @@ -73,11 +73,11 @@ interface PNotifyconfirm { /** * The buttons to display, and their callbacks. */ - buttons?: IPNotifyconfirmButton[]; + buttons?: PNotifyconfirmButton[]; } -interface IPNotifyButtons { +interface PNotifyButtons { /** * Provide a button for the user to manually close the notice. */ From 5e1ca2b9ef1971a6b08d9fb6d9277f20c61887f2 Mon Sep 17 00:00:00 2001 From: Thomas Puttkamer Date: Tue, 17 May 2016 05:39:07 +0200 Subject: [PATCH 078/402] fixing a Promise bug in type definition (#9334) * fixing a Promise bug in type definition * add Promise to Mongoose object --- mongoose/mongoose.d.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index 00915d3473..a2aabc0128 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -40,6 +40,7 @@ declare module "mongoose" { mquery: any; version: string; connection: Connection; + Promise: any; } export interface Connection extends NodeJS.EventEmitter { @@ -307,8 +308,8 @@ declare module "mongoose" { circle(area: Object): Query; circle(path: string, area: Object): Query; comment(val: any): Query; - count(callback?: (err: any, count: number) => void): Query; - count(criteria: Object, callback?: (err: any, count: number) => void): Query; + count(callback?: (err: any, count: number) => void): Query; + count(criteria: Object, callback?: (err: any, count: number) => void): Query; distinct(callback?: (err: any, res: T) => void): Query; distinct(field: string, callback?: (err: any, res: T) => void): Query; distinct(criteria: Object, field: string, callback?: (err: any, res: T) => void): Query; @@ -481,7 +482,7 @@ declare module "mongoose" { export class Promise { constructor(fn?: (err: any, result: T) => void); - then(onFulFill: (result: T) => void, onReject?: (err: any) => void): Promise; + then(onFulFill: (result: T) => void | U | Promise, onReject?: (err: any) => void | U | Promise): Promise; end(): void; fulfill(result: T): Promise; From 6f5c53028aaeb2f9e184561f4bf70eaa22a351c3 Mon Sep 17 00:00:00 2001 From: Connor Wyatt Date: Tue, 17 May 2016 07:47:23 +0100 Subject: [PATCH 079/402] Modified call signature of Sinon's calledWithNew method to no longer take a parameter (#9343) --- sinon/sinon.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sinon/sinon.d.ts b/sinon/sinon.d.ts index 719ed6405c..2596adf0ca 100644 --- a/sinon/sinon.d.ts +++ b/sinon/sinon.d.ts @@ -59,7 +59,7 @@ declare namespace Sinon { (...args: any[]): any; calledBefore(anotherSpy: SinonSpy): boolean; calledAfter(anotherSpy: SinonSpy): boolean; - calledWithNew(spy: SinonSpy): boolean; + calledWithNew(): boolean; withArgs(...args: any[]): SinonSpy; alwaysCalledOn(obj: any): boolean; alwaysCalledWith(...args: any[]): boolean; From b76dd8a7f95b71696982befbb7589940d27e940b Mon Sep 17 00:00:00 2001 From: Boris Cherny Date: Mon, 16 May 2016 23:48:39 -0700 Subject: [PATCH 080/402] angularjs: overload .get with typings for builtin servies (#9345) --- angularjs/angular.d.ts | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 98484e16f4..204c645b0c 100644 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -1845,7 +1845,7 @@ declare namespace angular { controller(name: string): any; injector(): any; scope(): IScope; - + /** * Overload for custom scope interfaces */ @@ -1870,6 +1870,33 @@ declare namespace angular { annotate(fn: Function, strictDi?: boolean): string[]; annotate(inlineAnnotatedFunction: any[]): string[]; get(name: string, caller?: string): T; + get(name: '$anchorScroll'): IAnchorScrollService + get(name: '$cacheFactory'): ICacheFactoryService + get(name: '$compile'): ICompileService + get(name: '$controller'): IControllerService + get(name: '$document'): IDocumentService + get(name: '$exceptionHandler'): IExceptionHandlerService + get(name: '$filter'): IFilterService + get(name: '$http'): IHttpService + get(name: '$httpBackend'): IHttpBackendService + get(name: '$httpParamSerializer'): IHttpParamSerializer + get(name: '$httpParamSerializerJQLike'): IHttpParamSerializer + get(name: '$interpolate'): IInterpolateService + get(name: '$interval'): IIntervalService + get(name: '$locale'): ILocaleService + get(name: '$location'): ILocationService + get(name: '$log'): ILogService + get(name: '$parse'): IParseService + get(name: '$q'): IQService + get(name: '$rootElement'): IRootElementService + get(name: '$rootScope'): IRootScopeService + get(name: '$sce'): ISCEService + get(name: '$sceDelegate'): ISCEDelegateService + get(name: '$templateCache'): ITemplateCacheService + get(name: '$templateRequest'): ITemplateRequestService + get(name: '$timeout'): ITimeoutService + get(name: '$window'): IWindowService + get(name: '$xhrFactory'): IXhrFactory has(name: string): boolean; instantiate(typeConstructor: Function, locals?: any): T; invoke(inlineAnnotatedFunction: any[]): any; From 74c1ffbba4e8f33765ccb1b9b1eaa0eacabe6e58 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Elis=C3=A9e=20Maurer?= Date: Tue, 17 May 2016 08:53:51 +0200 Subject: [PATCH 081/402] three: Fix a couple typos (#9348) --- threejs/three.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/threejs/three.d.ts b/threejs/three.d.ts index 867e687951..144302d423 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -3147,7 +3147,7 @@ declare namespace THREE { onChange(callback: Function): void; static RotationOrders: string[]; - static DefautlOrder: string; + static DefaultOrder: string; } /** @@ -6002,7 +6002,7 @@ declare namespace THREE { } - // Extras / Geomerties ///////////////////////////////////////////////////////////////////// + // Extras / Geometries ///////////////////////////////////////////////////////////////////// export class BoxBufferGeometry extends BufferGeometry { constructor(width: number, height: number, depth: number, widthSegments?: number, heightSegments?: number, depthSegments?: number); From b4bbee8f60560c34bc74b154b283f7ce83a31dae Mon Sep 17 00:00:00 2001 From: CodeAnimal Date: Tue, 17 May 2016 07:56:40 +0100 Subject: [PATCH 082/402] Stripe node 4.6.0 (#9350) * Add stripe subscription methods Add root subscription methods, in addition to subscription methods that are defined on customer objects. https://stripe.com/docs/api/node#subscriptions * Bump version to stripe-node 4.6.0 * Update customers.retrieve signature * Fix wrong signature for stripe.customers.update The return type was Promise> when in fact it should be Promise (it is a resource object, not a list) * Add created attribute to ISubscription interface --- stripe/stripe-node.d.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/stripe/stripe-node.d.ts b/stripe/stripe-node.d.ts index 202cd5790d..1e3d2caca7 100644 --- a/stripe/stripe-node.d.ts +++ b/stripe/stripe-node.d.ts @@ -4031,6 +4031,8 @@ declare namespace StripeNode { */ canceled_at: number; + created: number; + /** * End of the current period that the subscription has been invoiced for. At the end of this period, a new invoice will be created. */ @@ -5086,8 +5088,8 @@ declare namespace StripeNode { * * @param id The identifier of the customer to be retrieved. */ - update(id: string, data: customers.ICustomerUpdateOptions, options: HeaderOptions, response?: IResponseFn): Promise>; - update(id: string, data: customers.ICustomerUpdateOptions, response?: IResponseFn): Promise>; + update(id: string, data: customers.ICustomerUpdateOptions, options: HeaderOptions, response?: IResponseFn): Promise; + update(id: string, data: customers.ICustomerUpdateOptions, response?: IResponseFn): Promise; /** * Retrieves the details of an existing customer. You need only supply the unique customer identifier that was returned upon customer @@ -5098,6 +5100,8 @@ declare namespace StripeNode { * * @param id The identifier of the customer to be retrieved. */ + retrieve(id: string, data: IDataOptions, options: HeaderOptions, response?: IResponseFn): Promise; + retrieve(id: string, data: IDataOptions, response?: IResponseFn): Promise; retrieve(id: string, options: HeaderOptions, response?: IResponseFn): Promise; retrieve(id: string, response?: IResponseFn): Promise; From 2b93f68f6a09515e9b2744f9f2b3a1938e31efd3 Mon Sep 17 00:00:00 2001 From: Shawn Clabough Date: Tue, 17 May 2016 23:34:53 -0700 Subject: [PATCH 083/402] Add PivotSchema property name 'cube' (#9280) --- kendo-ui/kendo-ui.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/kendo-ui/kendo-ui.d.ts b/kendo-ui/kendo-ui.d.ts index cf57014386..b283f21c14 100644 --- a/kendo-ui/kendo-ui.d.ts +++ b/kendo-ui/kendo-ui.d.ts @@ -843,6 +843,7 @@ declare namespace kendo.data { axes?: any; catalogs?: any; cubes?: any; + cube?: any; data?: any; dimensions?: any; hierarchies?: any; From e0abafb1a6ff652f7ff967120e312d5c1916eaef Mon Sep 17 00:00:00 2001 From: Andrey Lipatkin Date: Wed, 18 May 2016 09:35:03 +0300 Subject: [PATCH 084/402] Narrowing down possible values for direction parameter (#9352) * Fixing favIconUrl property name typo for TabChangeInfo class * Empty commit to trigger Travis CI * Made direction parameter more specific by using string literal typing --- df-visible/df-visible.d.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/df-visible/df-visible.d.ts b/df-visible/df-visible.d.ts index 24de14b71e..b8d05fe360 100644 --- a/df-visible/df-visible.d.ts +++ b/df-visible/df-visible.d.ts @@ -5,6 +5,8 @@ /// +type Direction = "horizontal" | "vertical" | "both"; + interface JQuery { /** * Gets the value of a setting. @@ -12,5 +14,5 @@ interface JQuery { * @param callback The callback parameter should be a function that looks like this: * function(object details) {...}; */ - visible(partial?: boolean, hidden?: boolean, direction?: string): boolean; + visible(partial?: boolean, hidden?: boolean, direction?: Direction): boolean; } From 7e9254fac751056a7841b65136c7841f1b290475 Mon Sep 17 00:00:00 2001 From: vvakame Date: Sat, 21 May 2016 08:11:47 -0700 Subject: [PATCH 085/402] fix line ending of daterangepicker --- daterangepicker/daterangepicker-tests.ts | 118 +++++----- daterangepicker/daterangepicker.d.ts | 284 +++++++++++------------ 2 files changed, 201 insertions(+), 201 deletions(-) diff --git a/daterangepicker/daterangepicker-tests.ts b/daterangepicker/daterangepicker-tests.ts index e8d55f4f8e..ca1f99961c 100644 --- a/daterangepicker/daterangepicker-tests.ts +++ b/daterangepicker/daterangepicker-tests.ts @@ -1,59 +1,59 @@ -/// - -function tests_simple() { - $('#daterange').daterangepicker(); - $('input[name="daterange"]').daterangepicker({ - timePicker: true, - timePickerIncrement: 30, - locale: { - format: 'MM/DD/YYYY h:mm A' - } - }); - - $('#reportrange').daterangepicker({ - ranges: { - 'Today': [moment(), moment()], - 'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], - 'Last 7 Days': [moment().subtract(6, 'days'), moment()], - 'Last 30 Days': [moment().subtract(29, 'days'), moment()], - 'This Month': [moment().startOf('month'), moment().endOf('month')], - 'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')] - } - }); - - $('input[name="datefilter"]').on('apply.daterangepicker', function (ev, picker) { - $(this).val(picker.startDate.format('MM/DD/YYYY') + ' - ' + picker.endDate.format('MM/DD/YYYY')); - }); - - - $('input[name="datefilter"]').on('cancel.daterangepicker', function (ev, picker) { - $(this).val(''); - }); - - $('#demo').daterangepicker({ - "startDate": "05/06/2016", - "endDate": "05/12/2016" - }, function (start: string, end: string, label: string) { - console.log("New date range selected: ' + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD') + ' (predefined range: ' + label + ')"); - }); - - $(function() { - - function cb(start: moment.Moment, end: moment.Moment) { - $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY')); - } - cb(moment().subtract(29, 'days'), moment()); - - $('#reportrange').daterangepicker({ - ranges: { - 'Today': [moment(), moment()], - 'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], - 'Last 7 Days': [moment().subtract(6, 'days'), moment()], - 'Last 30 Days': [moment().subtract(29, 'days'), moment()], - 'This Month': [moment().startOf('month'), moment().endOf('month')], - 'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')] - } - }, cb); - -}); -} +/// + +function tests_simple() { + $('#daterange').daterangepicker(); + $('input[name="daterange"]').daterangepicker({ + timePicker: true, + timePickerIncrement: 30, + locale: { + format: 'MM/DD/YYYY h:mm A' + } + }); + + $('#reportrange').daterangepicker({ + ranges: { + 'Today': [moment(), moment()], + 'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], + 'Last 7 Days': [moment().subtract(6, 'days'), moment()], + 'Last 30 Days': [moment().subtract(29, 'days'), moment()], + 'This Month': [moment().startOf('month'), moment().endOf('month')], + 'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')] + } + }); + + $('input[name="datefilter"]').on('apply.daterangepicker', function (ev, picker) { + $(this).val(picker.startDate.format('MM/DD/YYYY') + ' - ' + picker.endDate.format('MM/DD/YYYY')); + }); + + + $('input[name="datefilter"]').on('cancel.daterangepicker', function (ev, picker) { + $(this).val(''); + }); + + $('#demo').daterangepicker({ + "startDate": "05/06/2016", + "endDate": "05/12/2016" + }, function (start: string, end: string, label: string) { + console.log("New date range selected: ' + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD') + ' (predefined range: ' + label + ')"); + }); + + $(function() { + + function cb(start: moment.Moment, end: moment.Moment) { + $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY')); + } + cb(moment().subtract(29, 'days'), moment()); + + $('#reportrange').daterangepicker({ + ranges: { + 'Today': [moment(), moment()], + 'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], + 'Last 7 Days': [moment().subtract(6, 'days'), moment()], + 'Last 30 Days': [moment().subtract(29, 'days'), moment()], + 'This Month': [moment().startOf('month'), moment().endOf('month')], + 'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')] + } + }, cb); + +}); +} diff --git a/daterangepicker/daterangepicker.d.ts b/daterangepicker/daterangepicker.d.ts index 6d24c0bd42..11190aa85d 100644 --- a/daterangepicker/daterangepicker.d.ts +++ b/daterangepicker/daterangepicker.d.ts @@ -1,142 +1,142 @@ -// Type definitions for Date Range Picker v2.1.19 -// Project: http://www.daterangepicker.com/ -// Definitions by: SirMartin -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// - -interface JQuery { - daterangepicker(settings?: daterangepicker.Settings): JQuery; - daterangepicker(settings?: daterangepicker.Settings, callback?: (start?: string | Date | moment.Moment, end?: string | Date | moment.Moment, label?: string) => any): JQuery; -} - -declare module daterangepicker { - - interface DatepickerEventObject extends JQueryEventObject { - date: Date; - format(format?: string): string; - } - - interface Settings { - /** - * The start of the initially selected date range - */ - startDate?: string | moment.Moment | Date; - /** - * The end of the initially selected date range - */ - endDate?: string | moment.Moment | Date; - /** - * The earliest date a user may select - */ - minDate?: string | moment.Moment | Date; - /** - * The latest date a user may select - */ - maxDate?: string | moment.Moment | Date; - /** - * The maximum span between the selected start and end dates. Can have any property you can add to a moment object (i.e. days, months) - */ - dateLimit?: any; - /** - * Show year and month select boxes above calendars to jump to a specific month and year - */ - showDropdowns?: boolean; - /** - * Show localized week numbers at the start of each week on the calendars - */ - showWeekNumbers?: boolean; - /** - * Show ISO week numbers at the start of each week on the calendars - */ - showISOWeekNumbers?: boolean; - /** - * Allow selection of dates with times, not just dates - */ - timePicker?: boolean; - /** - * Increment of the minutes selection list for times (i.e. 30 to allow only selection of times ending in 0 or 30) - */ - timePickerIncrement?: number; - /** - * Use 24- hour instead of 12- hour times, removing the AM/ PM selection. - */ - timePicker24Hour?: boolean; - /** - * Show seconds in the timePicker. - */ - timePickerSeconds?: boolean; - /** - * Set predefined date ranges the user can select from.Each key is the label for the range, and its value an array with two dates representing the bounds of the range. - */ - ranges?: any; - /** - * (string: 'left'/'right'/'center') Whether the picker appears aligned to the left, to the right, or centered under the HTML element it's attached to - */ - opens?: string; - /** - * (string: 'down' or 'up') Whether the picker appears below (default) or above the HTML element it's attached to - */ - drops?: string; - /** - * CSS class names that will be added to all buttons in the picker - */ - buttonClasses?: string[]; - /** - * CSS class string that will be added to the apply button - */ - applyClass?: string; - /** - * CSS class string that will be added to the cancel button - */ - cancelClass?: string; - /** - * Allows you to provide localized strings for buttons and labels, customize the date display format, and change the first day of week for the calendars. - */ - locale?: Locale; - /** - * Show only a single calendar to choose one date, instead of a range picker with two calendars; the start and end dates provided to your callback will be the same single date chosen. - */ - singleDatePicker?: boolean; - /** - * Hide the apply and cancel buttons, and automatically apply a new date range as soon as two dates or a predefined range is selected. - */ - autoApply?: boolean; - /** - * When enabled, the two calendars displayed will always be for two sequential months (i.e.January and February), and both will be advanced when clicking the left or right arrows above the calendars.When disabled, the two calendars can be individually advanced and display any month/ year. - */ - linkedCalendars?: boolean; - /** - * jQuery selector of the parent element that the date range picker will be added to, if not provided this will be 'body' - */ - parentEl?: string; - /** - * A function that is passed each date in the two calendars before they are displayed, and may return true or false to indicate whether that date should be available for selection or not. - */ - isInvalidDate?(startDate: string | moment.Moment | Date, endDate?: string | moment.Moment | Date): boolean; - /** - * Indicates whether the date range picker should automatically update the value of an < input > element it's attached to at initialization and when the selected dates change. - */ - autoUpdateInput?: boolean; - /** - * Normally, if you use the ranges option to specify pre- defined date ranges, calendars for choosing a custom date range are not shown until the user clicks "Custom Range".When this option is set to true, the calendars for choosing a custom date range are always shown instead. - */ - alwaysShowCalendars?: boolean; - } - - interface Locale { - /** - * Text for cancel label. - */ - cancelLabel?: string; - /** - * Text for apply label. - */ - applyLabel?: string; - /** - * Format of the date string. example: 'YYYY-MM-DD' - */ - format?: string; - } -} \ No newline at end of file +// Type definitions for Date Range Picker v2.1.19 +// Project: http://www.daterangepicker.com/ +// Definitions by: SirMartin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +interface JQuery { + daterangepicker(settings?: daterangepicker.Settings): JQuery; + daterangepicker(settings?: daterangepicker.Settings, callback?: (start?: string | Date | moment.Moment, end?: string | Date | moment.Moment, label?: string) => any): JQuery; +} + +declare module daterangepicker { + + interface DatepickerEventObject extends JQueryEventObject { + date: Date; + format(format?: string): string; + } + + interface Settings { + /** + * The start of the initially selected date range + */ + startDate?: string | moment.Moment | Date; + /** + * The end of the initially selected date range + */ + endDate?: string | moment.Moment | Date; + /** + * The earliest date a user may select + */ + minDate?: string | moment.Moment | Date; + /** + * The latest date a user may select + */ + maxDate?: string | moment.Moment | Date; + /** + * The maximum span between the selected start and end dates. Can have any property you can add to a moment object (i.e. days, months) + */ + dateLimit?: any; + /** + * Show year and month select boxes above calendars to jump to a specific month and year + */ + showDropdowns?: boolean; + /** + * Show localized week numbers at the start of each week on the calendars + */ + showWeekNumbers?: boolean; + /** + * Show ISO week numbers at the start of each week on the calendars + */ + showISOWeekNumbers?: boolean; + /** + * Allow selection of dates with times, not just dates + */ + timePicker?: boolean; + /** + * Increment of the minutes selection list for times (i.e. 30 to allow only selection of times ending in 0 or 30) + */ + timePickerIncrement?: number; + /** + * Use 24- hour instead of 12- hour times, removing the AM/ PM selection. + */ + timePicker24Hour?: boolean; + /** + * Show seconds in the timePicker. + */ + timePickerSeconds?: boolean; + /** + * Set predefined date ranges the user can select from.Each key is the label for the range, and its value an array with two dates representing the bounds of the range. + */ + ranges?: any; + /** + * (string: 'left'/'right'/'center') Whether the picker appears aligned to the left, to the right, or centered under the HTML element it's attached to + */ + opens?: string; + /** + * (string: 'down' or 'up') Whether the picker appears below (default) or above the HTML element it's attached to + */ + drops?: string; + /** + * CSS class names that will be added to all buttons in the picker + */ + buttonClasses?: string[]; + /** + * CSS class string that will be added to the apply button + */ + applyClass?: string; + /** + * CSS class string that will be added to the cancel button + */ + cancelClass?: string; + /** + * Allows you to provide localized strings for buttons and labels, customize the date display format, and change the first day of week for the calendars. + */ + locale?: Locale; + /** + * Show only a single calendar to choose one date, instead of a range picker with two calendars; the start and end dates provided to your callback will be the same single date chosen. + */ + singleDatePicker?: boolean; + /** + * Hide the apply and cancel buttons, and automatically apply a new date range as soon as two dates or a predefined range is selected. + */ + autoApply?: boolean; + /** + * When enabled, the two calendars displayed will always be for two sequential months (i.e.January and February), and both will be advanced when clicking the left or right arrows above the calendars.When disabled, the two calendars can be individually advanced and display any month/ year. + */ + linkedCalendars?: boolean; + /** + * jQuery selector of the parent element that the date range picker will be added to, if not provided this will be 'body' + */ + parentEl?: string; + /** + * A function that is passed each date in the two calendars before they are displayed, and may return true or false to indicate whether that date should be available for selection or not. + */ + isInvalidDate?(startDate: string | moment.Moment | Date, endDate?: string | moment.Moment | Date): boolean; + /** + * Indicates whether the date range picker should automatically update the value of an < input > element it's attached to at initialization and when the selected dates change. + */ + autoUpdateInput?: boolean; + /** + * Normally, if you use the ranges option to specify pre- defined date ranges, calendars for choosing a custom date range are not shown until the user clicks "Custom Range".When this option is set to true, the calendars for choosing a custom date range are always shown instead. + */ + alwaysShowCalendars?: boolean; + } + + interface Locale { + /** + * Text for cancel label. + */ + cancelLabel?: string; + /** + * Text for apply label. + */ + applyLabel?: string; + /** + * Format of the date string. example: 'YYYY-MM-DD' + */ + format?: string; + } +} From 41f31600a1bff1adef3c76642183b20ec97aa81e Mon Sep 17 00:00:00 2001 From: Abhishek Garg Date: Sat, 21 May 2016 20:44:13 +0530 Subject: [PATCH 086/402] Rectify type for IState.template (#9354) Add `params: IStateParamsService` for IState.template function --- angular-ui-router/angular-ui-router.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/angular-ui-router/angular-ui-router.d.ts b/angular-ui-router/angular-ui-router.d.ts index 945d07fb73..88f00c9b5d 100644 --- a/angular-ui-router/angular-ui-router.d.ts +++ b/angular-ui-router/angular-ui-router.d.ts @@ -35,7 +35,7 @@ declare namespace angular.ui { /** * String HTML content, or function that returns an HTML string */ - template?: string | {(): string}; + template?: string | {(params: IStateParamsService): string}; /** * String URL path to template file OR Function, returns URL path string */ From 48a5cfd0d77476d19531c42100d7d414fda4c73f Mon Sep 17 00:00:00 2001 From: Vaggelis Mparmpas Date: Sat, 21 May 2016 17:15:52 +0200 Subject: [PATCH 087/402] cachefactory typings (#9202) * cachefactory typings * Removed: I prefix from model interfaces Added: interfaces: CacheGetOptions, CachePutOptions, CacheTouchOptions --- cachefactory/cachefactory-tests.ts | 34 +++ cachefactory/cachefactory.d.ts | 443 +++++++++++++++++++++++++++++ 2 files changed, 477 insertions(+) create mode 100644 cachefactory/cachefactory-tests.ts create mode 100644 cachefactory/cachefactory.d.ts diff --git a/cachefactory/cachefactory-tests.ts b/cachefactory/cachefactory-tests.ts new file mode 100644 index 0000000000..0c859e749d --- /dev/null +++ b/cachefactory/cachefactory-tests.ts @@ -0,0 +1,34 @@ +/// + +CacheFactory.get('test'); + +CacheFactory.createCache('test', { + deleteOnExpire: 'aggressive', + recycleFreq: 60000 +}); + +let testCache = CacheFactory.get('test'); + +testCache.put('testOne', {title: 'testOne', id: 1}); + +let item = testCache.get('testOne'); + + +let profileCache = CacheFactory('profileCache', { + maxAge: 60 * 60 * 1000, + deleteOnExpire: 'aggressive' +}); + +let localStoragePolyfill = { + getItem: (key: string) => { return ""; }, + setItem: (key: string, value: string) => { }, + removeItem: (key: string) => { } +}; + +let myAwesomeCache = CacheFactory('myAwesomeCache', { + maxAge: 15 * 60 * 1000, + cacheFlushInterval: 60 * 60 * 1000, + deleteOnExpire: 'aggressive', + storageMode: 'localStorage', + storageImpl: localStoragePolyfill +}); \ No newline at end of file diff --git a/cachefactory/cachefactory.d.ts b/cachefactory/cachefactory.d.ts new file mode 100644 index 0000000000..ac416e6837 --- /dev/null +++ b/cachefactory/cachefactory.d.ts @@ -0,0 +1,443 @@ +// Type definitions for CacheFactory 1.4.0 +// Project: https://github.com/jmdobry/CacheFactory +// Definitions by: Vaggelis Mparmpas , Daniel Massa +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module CacheFactory { + export interface IStoreImplementation { + getItem(key: string): string; + + setItem(key: string, value: string): void; + + removeItem(key: string): void; + } + + export interface CacheGetOptions { + /* + * A callback function to be executed whenever an expired item is removed from a cache when the cache is in passive + * or aggressive mode. Will be passed the key and value of the expired item. + * + * Will be passed a third done argument if the cache is in passive mode. This allows you to synchronously access the + * key and value of the expired item when you make the cache#get(key[, options]) call that is the reason the expired + * item is being removed in the first place. Default: null. + */ + onExpire?(key: string, value: any): any; + } + + export interface CachePutOptions { + /* + * The number of milliseconds until a newly inserted item expires. Default: Number.MAX_VALUE. + */ + maxAge?: number; + + /* + * If inserting a promise into a cache, also insert the rejection value if the promise rejects. Default: false. + */ + storeOnReject?: boolean; + + /* + * If inserting a promise into a cache, also insert the resolved value if the promise resolves. Default: false. + */ + storeOnResolve?: boolean; + + created?: Date; + access?: Date; + expires?: Date; + } + + export interface CacheTouchOptions extends CachePutOptions { } + + export interface CacheOptions { + /* + * If set, remove all items from a cache on an interval after the given number of milliseconds. Default: null. + */ + cacheFlushInterval?: number; + + /* + * Maximum number of items a cache can hold. Adding more items than the capacity will cause the cache to operate + * like an LRU cache, removing the least recently used items to stay under capacity. Default: Number.MAX_VALUE. + */ + + capacity?: number; + + /* + * Determines the behavior of a cache when an item expires. Default: none. + * + * Possible values: + * + * none - cache will do nothing when an item expires. + * passive - cache will do nothing when an item expires. Expired items will remain in the cache until requested, + * at which point they are removed, and undefined is returned. + * aggressive - cache will remove expired items as soon as they are discovered. + */ + deleteOnExpire?: string; + + /* + * Determines whether a cache is disabled. Default: false. + */ + disabled?: boolean; + + /* + * The number of milliseconds until a newly inserted item expires. Default: Number.MAX_VALUE. + */ + maxAge?: number; + + /* + * Determines how often a cache will scan for expired items when in aggressive mode. Default: 1000 (milliseconds). + */ + recycleFreq?: number; + + /* + * If inserting a promise into a cache, also insert the rejection value if the promise rejects. Default: false. + */ + storeOnReject?: boolean; + + /* + * If inserting a promise into a cache, also insert the resolved value if the promise resolves. Default: false. + */ + storeOnResolve?: boolean; + + /* + * Provide a custom storage medium, e.g. a polyfill for localStorage. Default: null. + * + * Must implement: + * + * setItem - Same API as localStorage.setItem(key, value) + * getItem - Same API as localStorage.getItem(key) + * removeItem - Same API as localStorage.removeItem(key) + */ + storageImpl?: IStoreImplementation; + + /* + * Determines the storage medium used by a cache. Default: memory. + * + * Possible values: + * + * memory - cache will hold data in memory. Data is cleared when the page is refreshed. + * localStorage - cache will hold data in localStorage if available. Data is not cleared when the page is refreshed. + * sessionStorage - cache will hold data in sessionStorage if available. Data is not cleared when the page is refreshed. + */ + storageMode?: string; + + /* + * Determines the namespace of a cache when storageMode is set to localStorage or sessionStorage. Make it a shorter + * string to save space. Default: angular-cache.caches. + */ + storagePrefix?: string; + + /* + * A callback function to be executed whenever an expired item is removed from a cache when the cache is in passive + * or aggressive mode. Will be passed the key and value of the expired item. + * + * Will be passed a third done argument if the cache is in passive mode. This allows you to synchronously access the + * key and value of the expired item when you make the cache#get(key[, options]) call that is the reason the expired + * item is being removed in the first place. Default: null. + */ + onExpire?(key: string, value: any): any; + } + + export interface ICache { + + $$id: string; + + /** + * Return the item with the given key.options, if provided, must be an object. + * + * If the cache is in passive mode, then options.onExpire can be a function that will be called with the key + * and value of the requested item if the requested item is expired, with the get call itself returning undefined. + * @param key + * @returns {} + */ + get(key: string, options?: CacheGetOptions): T; + + /** + * Insert the item with the given key and value into the cache.options, if provided, must be an object. + * + * If inserting a promise, options.storeOnReject determines whether to insert the rejection value if the promise + * rejects (overriding the default storeOnReject setting for the cache). If inserting a promise, options.storeOnResolve + * determines whether to insert the resolved value if the promise resolves (overriding the default storeOnResolve setting for the cache). + * + * @param key + * @param value + * @param options + */ + put(key: string, value: T, options?: CachePutOptions): void; + + /** + * Remove and return the item with the given key, if it is in the cache. + * @param key + * @returns {} + */ + remove(key: string): T; + + /** + * Remove all items in the cache. + */ + removeAll(): void; + + /** + * Remove and return all expired items in the cache. + * @returns {} + */ + removeExpired(): { [key: string]: any }; + + /** + * Completely destroy this cache and its data. + * @returns {} + */ + destroy(): void; + + /** + * Returns an object containing information about the cache. + * + * @param key + */ + info(): CacheInfo; + + /** + * Returns an object containing information about the item with the given key, if the item is in the cache. + * + * @param key + */ + info(key: string): CacheItemInfo; + + /** + * Return the keys of all items in the cache as an object. + * @returns {} + */ + keySet(): any; + + /** + * Return the keys of all items in the cache as an array. + * @returns [] + */ + keys(): Array; + + /** + * Enable the cache. + */ + enable(): void; + + /** + * Disable the cache. + */ + disable(): void; + + /** + * cache#touch() will "touch" all items in the cache. + * cache#touch(key) will "touch" the item with the given key. + * + * @param key + */ + touch(key?: string, options?: CacheTouchOptions): void; + + /** + * Set the cacheFlushInterval for the cache. + * @param cacheFlushInterval + */ + setCacheFlushInterval(cacheFlushInterval: number): void; + + /** + * Set the capacity for the cache.Setting this lower than the current item count will result in those items being removed. + * @param capacity + */ + setCapacity(capacity: number): void; + + /** + * Set the deleteOnExpire for the cache. + * @param deleteOnExpire + */ + setDeleteOnExpire(deleteOnExpire: string): void; + + /** + * Set the maxAge for the cache. + */ + setMaxAge(maxAge: number): void; + + /** + * Set the onExpire for the cache. + * @param onExpire + */ + setOnExpire(onExpire: Function): void; + + /** + * Set the recycleFreq for the cache. + * @param recycleFreq + */ + setRecycleFreq(recycleFreq: number): void; + + /** + * Set the storageMode for the cache.This will move data from the current storage medium to the new one. + * @param storageMode + */ + setStorageMode(storageMode: string): void; + + /** + * Set multiple options for the cache at a time.Setting strict to true will reset options for the cache + * that are not specifically set in the options hash to CacheFactoryProvider.defaults. + * @param options + */ + setOptions(options: CacheOptions, strict?: boolean): void; + + /** + * Return the values of all items in the cache as an array. + * @returns Array + */ + values(): Array + } + + export interface ICacheFactory { + + BinaryHeap: IBinaryHeap; + utils: IUtils; + defaults: CacheOptions; + + /** + * Create a cache. cache must not already exist. cacheId must be a string. options is an optional argument and must be an object. + * Any options you pass here will override any default options. + * @param cacheId + * @param options + * @returns ICache + */ + (cacheId: string, options?: CacheOptions): ICache; + + /** + * Create a cache. cache must not already exist. cacheId must be a string. options is an optional argument and must be an object. + * Any options you pass here will override any default options. + * @param cacheId + * @param options + * @returns ICache + */ + createCache(cacheId: string, options?: CacheOptions): ICache; + + /** + * Return the cache with the given cacheId. + * @param cacheId The id of the cache storage. + * @returns ICache + */ + get(cacheId: string, options?: CacheOptions): ICache; + + /** + * Return an object of key- value pairs, the keys being cache ids and the values being the result of .info() being called on each cache. + * @returns CacheInfo + */ + info(): CacheInfo; + + /** + * Return the ids of all registered caches as an object. + * @returns {[key: string]: ICache} + */ + keySet(): { [key: string]: ICache }; + + /** + * Return the ids of all registered caches as an array. + * @returns Array + */ + keys(): Array; + + /** + * Destroy the cache with the given cacheId. + * @param cacheId + */ + destroy(cacheId: string): void; + + /** + * Destroy all registered caches. + */ + destroyAll(): void; + + /** + * Remove all data from all registered caches. + */ + clearAll(): void; + + /** + * Enable all registered caches. + */ + enableAll(): void; + + /** + * Disable all registered caches. + */ + disableAll(): void; + + /** + * Call.touch() on all registered caches. + */ + touchAll(): void; + + /** + * Call.removeExpired() on all registered caches.Returns a hash of any expired items, keyed by cache id. + * @returns {} + */ + removeExpiredFromAll(): Array<{ [key: string]: Array<{ [key: string]: any }> }>; + } + + export interface IUtils { + isNumber(value: any): boolean; + isString(value: any): boolean; + isObject(value: any): boolean; + isFunction(value: any): boolean; + equals(a: any, b: any): boolean; + fromJson(value: any): {} + Promise: any; + } + + export interface HeapItem { + key: string; + accessed: Date; + } + + export interface IBinaryHeap { + (w?: IWeightFunc, c?: ICompareFunc): void; + + heap: Array; + weightFunc: IWeightFunc; + compareFunc: ICompareFunc; + + push(node: HeapItem): void; + pop(): HeapItem; + peek(): HeapItem; + remove(node: HeapItem): HeapItem; + removeAll(): void; + size(): Number; + } + + export interface IWeightFunc { + (x: T): T; + } + + export interface ICompareFunc { + (x: T, y: T): boolean; + } + + export interface CacheInfo { + size: Number; + caches: { [key: string]: any }; + capacity: Number; + maxAge: Number; + deleteOnExpire: string; + onExpire: Function; + cacheFlushInterval: Number; + recycleFreq: Number; + storageMode: string; + storageImpl: IStoreImplementation; + disabled: boolean; + storagePrefix: string; + storeOnResolve: boolean; + storeOnReject: boolean; + } + + export interface CacheItemInfo { + created: Date; + accessed: Date; + expires: Date; + isExpired: boolean; + } +} + +declare var CacheFactory: CacheFactory.ICacheFactory; + +declare module "cachefactory" { + export = CacheFactory; +} \ No newline at end of file From c59e98d3eedfb82077794ef89a964c98645b9bc5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Monteiro?= Date: Sat, 21 May 2016 16:16:41 +0100 Subject: [PATCH 088/402] removed get/set (not present in the object);added function;updated test file; (#9356) --- ngstorage/ngstorage-tests.ts | 13 +++++-------- ngstorage/ngstorage.d.ts | 4 +--- 2 files changed, 6 insertions(+), 11 deletions(-) diff --git a/ngstorage/ngstorage-tests.ts b/ngstorage/ngstorage-tests.ts index 698723eaa3..e3a427b9b1 100644 --- a/ngstorage/ngstorage-tests.ts +++ b/ngstorage/ngstorage-tests.ts @@ -5,10 +5,6 @@ var app: any; app.controller('LocalCtrl', function ($localStorage: angular.storage.IStorageService) { - $localStorage.set('MyKey', 'value'); - - $localStorage.get('MyKey'); - $localStorage.$default({ counter: 1 }); @@ -20,14 +16,12 @@ app.controller('LocalCtrl', function ($localStorage: angular.storage.IStorageSer $localStorage.$reset(); $localStorage.$apply(); + + $localStorage.$sync(); }); app.controller('SessionCtrl', function ($sessionStorage: angular.storage.IStorageService) { - $sessionStorage.set('MyKey', 'value'); - - $sessionStorage.get('MyKey'); - $sessionStorage.$default({ counter: 1 }); @@ -39,9 +33,12 @@ app.controller('SessionCtrl', function ($sessionStorage: angular.storage.IStorag $sessionStorage.$reset(); $sessionStorage.$apply(); + + $sessionStorage.$sync(); }); app.config(['$localStorageProvider', function ($localStorageProvider: angular.storage.IStorageProvider) { + $localStorageProvider.setKeyPrefix('NewPrefix'); $localStorageProvider.get('MyKey'); diff --git a/ngstorage/ngstorage.d.ts b/ngstorage/ngstorage.d.ts index 0ea372ccb8..d6abea24bf 100644 --- a/ngstorage/ngstorage.d.ts +++ b/ngstorage/ngstorage.d.ts @@ -11,9 +11,7 @@ declare namespace angular.storage { $default(items: {}): IStorageService; $reset(items?: {}): IStorageService; $apply(): void; - - get(key: string): T; - set(key: string, value: T): T; + $sync(): void; } export interface IStorageProvider extends angular.IServiceProvider { From 668ab30824b7b004d50dccd13f3fb956f1ecc2f2 Mon Sep 17 00:00:00 2001 From: Colin Eberhardt Date: Sat, 21 May 2016 16:18:32 +0100 Subject: [PATCH 089/402] Added initial typings for remote-redux-devtools (#9357) --- .../remote-redux-devtools-tests.ts | 13 ++++++++ .../remote-redux-devtools.d.ts | 31 +++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 remote-redux-devtools/remote-redux-devtools-tests.ts create mode 100644 remote-redux-devtools/remote-redux-devtools.d.ts diff --git a/remote-redux-devtools/remote-redux-devtools-tests.ts b/remote-redux-devtools/remote-redux-devtools-tests.ts new file mode 100644 index 0000000000..257df63682 --- /dev/null +++ b/remote-redux-devtools/remote-redux-devtools-tests.ts @@ -0,0 +1,13 @@ +/// + +import * as devTools from "remote-redux-devtools"; + +// example configuration from: https://github.com/zalmoxisus/remote-redux-devtools +devTools({ + name: 'Android app', + realtime: true, + hostname: 'localhost', + port: 8000, + maxAge: 30, + filters: { blacklist: ['EFFECT_RESOLVED'] } +}); diff --git a/remote-redux-devtools/remote-redux-devtools.d.ts b/remote-redux-devtools/remote-redux-devtools.d.ts new file mode 100644 index 0000000000..b43f35cd1f --- /dev/null +++ b/remote-redux-devtools/remote-redux-devtools.d.ts @@ -0,0 +1,31 @@ +// Type definitions for remote-redux-devtools v0.3.2 +// Project: https://github.com/zalmoxisus/remote-redux-devtools +// Definitions by: Colin Eberhardt +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "remote-redux-devtools" { + + type StringOrArray = string | string[]; + + interface Config { + name?: string; + realtime?: boolean; + hostname?: string; + port?: number; + secure?: boolean; + filters?: {[key: string]: string[]}; + maxAge?: number; + startOn?: StringOrArray; + stopOn?: StringOrArray; + sendOn?: StringOrArray; + sendOnError?: number; + sendTo?: string; + id?: string; + } + + function devTools(config?: Config): Function; + + namespace devTools {} + + export = devTools; +} From 8f68f8cd4b719ad79a172751b3b295b0d3ff76a7 Mon Sep 17 00:00:00 2001 From: Ian Firkin Date: Sat, 21 May 2016 11:19:17 -0400 Subject: [PATCH 090/402] Dojo xhr (#9339) * Makes xhr return a promise instead of void Xhr takes an argument which determines it's return type--either Promise (the default) or Deferred. Currently in the type definitions, it returns void. I've also commented out the "helper" methods (get, post, etc.), to match the source code--they're commented out there as well. * Comments out entire interface body Removes the entire interface with helper methods. * Adds back "helper" methods to xhr This methods are included via the `util.addCommonMethods` call, and so should be in the type definitions. --- dojo/dojo.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dojo/dojo.d.ts b/dojo/dojo.d.ts index 455ffc8fe3..bf3258a14a 100644 --- a/dojo/dojo.d.ts +++ b/dojo/dojo.d.ts @@ -649,7 +649,7 @@ declare namespace dojo { * @param url URL to request * @param options OptionalOptions for the request. */ - interface xhr { (url: String, options?: dojo.request.xhr.__Options): void } + interface xhr { (url: String, options?: dojo.request.xhr.__Options): dojo.request.__Promise } interface xhr { /** * Send an HTTP DELETE request using XMLHttpRequest with the given URL and options. From ddc412f754995472591181f1e507923dc3eda84b Mon Sep 17 00:00:00 2001 From: styu Date: Sat, 21 May 2016 11:22:26 -0400 Subject: [PATCH 091/402] Add MergeView typings to CodeMirror (#9344) * Add MergeView typings to CodemMirror * Move MergeView definitions to new namespace and removed unnecessary callback interfaces --- codemirror/codemirror.d.ts | 109 +++++++++++++++++++++++++++++++++++++ 1 file changed, 109 insertions(+) diff --git a/codemirror/codemirror.d.ts b/codemirror/codemirror.d.ts index bade422821..4d95220c67 100644 --- a/codemirror/codemirror.d.ts +++ b/codemirror/codemirror.d.ts @@ -1125,6 +1125,115 @@ declare namespace CodeMirror { severity?: string; to?: Position; } + + /** + * A function that calculates either a two-way or three-way merge between different sets of content. + */ + function MergeView(element: HTMLElement, options?: MergeView.MergeViewEditorConfiguration): MergeView.MergeViewEditor; + + namespace MergeView { + /** + * Options available to MergeView. + */ + interface MergeViewEditorConfiguration extends EditorConfiguration { + /** + * Determines whether the original editor allows editing. Defaults to false. + */ + allowEditingOriginals?: boolean; + + /** + * When true stretches of unchanged text will be collapsed. When a number is given, this indicates the amount + * of lines to leave visible around such stretches (which defaults to 2). Defaults to false. + */ + collapseIdentical?: boolean | number; + + /** + * Sets the style used to connect changed chunks of code. By default, connectors are drawn. When this is set to "align", + * the smaller chunk is padded to align with the bigger chunk instead. + */ + connect?: string; + + /** + * Callback for when stretches of unchanged text are collapsed. + */ + onCollapse?(mergeView: MergeViewEditor, line: number, size: number, mark: TextMarker): void; + + /** + * Provides original version of the document to be shown on the right of the editor. + */ + orig: any; + + /** + * Provides original version of the document to be shown on the left of the editor. + * To create a 2-way (as opposed to 3-way) merge view, provide only one of origLeft and origRight. + */ + origLeft?: any; + + /** + * Provides original version of document to be shown on the right of the editor. + * To create a 2-way (as opposed to 3-way) merge view, provide only one of origLeft and origRight. + */ + origRight?: any; + + /** + * Determines whether buttons that allow the user to revert changes are shown. Defaults to true. + */ + revertButtons?: boolean; + + /** + * When true, changed pieces of text are highlighted. Defaults to true. + */ + showDifferences?: boolean; + } + + interface MergeViewEditor extends Editor { + /** + * Returns the editor instance. + */ + editor(): Editor; + + /** + * Left side of the merge view. + */ + left: DiffView; + leftChunks(): MergeViewDiffChunk; + leftOriginal(): Editor; + + /** + * Right side of the merge view. + */ + right: DiffView; + rightChunks(): MergeViewDiffChunk; + rightOriginal(): Editor; + + /** + * Sets whether or not the merge view should show the differences between the editor views. + */ + setShowDifferences(showDifferences: boolean): void; + } + + /** + * Tracks changes in chunks from oroginal to new. + */ + interface MergeViewDiffChunk { + editFrom: number; + editTo: number; + origFrom: number; + origTo: number; + } + + interface DiffView { + /** + * Forces the view to reload. + */ + forceUpdate(): (mode: string) => void; + + /** + * Sets whether or not the merge view should show the differences between the editor views. + */ + setShowDifferences(showDifferences: boolean): void; + } + } } declare module "codemirror" { From 4143c4ff6f587cd365b549c3a256ffbd7e469705 Mon Sep 17 00:00:00 2001 From: Jules Truong Date: Sat, 21 May 2016 17:25:45 +0200 Subject: [PATCH 092/402] Miss register to Configurationoptions (#9292) --- i18n-node/i18n-node.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/i18n-node/i18n-node.d.ts b/i18n-node/i18n-node.d.ts index 568228df45..d5703a825d 100644 --- a/i18n-node/i18n-node.d.ts +++ b/i18n-node/i18n-node.d.ts @@ -50,6 +50,11 @@ declare namespace i18n { * json files prefix */ prefix?: string; + + /** + * object or [obj1, obj2] to bind the i18n api and current locale to - defaults to null + */ + register?: any; } export interface TranslateOptions { phrase: string; From 445ed7e54c1b2a8e84610afab0aab2b2ee2ffb4e Mon Sep 17 00:00:00 2001 From: Ville Lahdenvuo Date: Sat, 21 May 2016 17:25:56 +0200 Subject: [PATCH 093/402] Add Undefined to should (#7746) --- should/should.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/should/should.d.ts b/should/should.d.ts index ce2743dfd8..b0e6054bde 100644 --- a/should/should.d.ts +++ b/should/should.d.ts @@ -40,6 +40,7 @@ interface ShouldAssertion { Function(): ShouldAssertion; Date(): ShouldAssertion; Class(): ShouldAssertion; + Undefined(): ShouldAssertion; generator(): ShouldAssertion; iterable(): ShouldAssertion; iterator(): ShouldAssertion; From b76f5c0e57f34b4a5aad4bf836ab89c5774ad9d3 Mon Sep 17 00:00:00 2001 From: Cluda Date: Sat, 21 May 2016 17:26:05 +0200 Subject: [PATCH 094/402] SignOptions.expiresIn should be string or number (#8806) * SignOptions.expiresIn should be any https://github.com/rauchg/ms.js can take number or string * expiresIn should be a string or a number --- jsonwebtoken/jsonwebtoken.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jsonwebtoken/jsonwebtoken.d.ts b/jsonwebtoken/jsonwebtoken.d.ts index 888ac75d6f..da2fb3b99a 100644 --- a/jsonwebtoken/jsonwebtoken.d.ts +++ b/jsonwebtoken/jsonwebtoken.d.ts @@ -23,7 +23,7 @@ declare module "jsonwebtoken" { */ algorithm?: string; /** @member {string} - Lifetime for the token expressed in a string describing a time span [rauchg/ms](https://github.com/rauchg/ms.js). Eg: `60`, `"2 days"`, `"10h"`, `"7d"` */ - expiresIn?: string; + expiresIn?: string | number; notBefore?: string; audience?: string; subject?: string; From ac94ea73311e9d5607f919b5c174d66d72c78a29 Mon Sep 17 00:00:00 2001 From: Antonio Morales Date: Sat, 21 May 2016 08:26:16 -0700 Subject: [PATCH 095/402] Update sendgrid typings to v2.0.0 (#8492) * rename sendgrid typing file to include version * upate sendgrid typing definitions * add reference to smtpapi typings * merge * make tests pass --- sendgrid/sendgrid-1.1.0.d.ts | 169 +++++++++++++++++++++++++++++++++++ sendgrid/sendgrid-tests.ts | 114 +++++++++++++++++++++-- sendgrid/sendgrid.d.ts | 70 +++++++++------ 3 files changed, 323 insertions(+), 30 deletions(-) create mode 100644 sendgrid/sendgrid-1.1.0.d.ts diff --git a/sendgrid/sendgrid-1.1.0.d.ts b/sendgrid/sendgrid-1.1.0.d.ts new file mode 100644 index 0000000000..7f644b65b0 --- /dev/null +++ b/sendgrid/sendgrid-1.1.0.d.ts @@ -0,0 +1,169 @@ +// Type definitions for sendgrid 1.1.0 +// Project: https://github.com/sendgrid/sendgrid-nodejs +// Definitions by: Maxime LUCE +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module Sendgrid { + //#region Options + + export interface UriParts { + protocol: string; + host: string; + port: string; + endpoint: string; + } + + export interface Options { + protocol?: string; + host?: string; + port?: string; + endpoint?: string; + uri?: string; + proxy?: string; + web?: { + pool?: any; + } + } + + export interface OptionsExport { + uriParts: UriParts; + uri: string; + + proxy?: string; + web?: { + pool?: any; + } + } + + //#endregion + + //#region Email + + export interface EmailOptions { + to?: any; + toname?: string; + from?: string; + fromname?: string; + subject?: string; + text?: string; + html?: string; + bcc?: any; + replyto?: string; + date?: Date; + headers?: { [key: string]: string }; + files?: FileHandlerOptions[]; + smtpapi?: any; + } + + export class Email { + to: any; + toname: string; + from: string; + fromname: string; + subject: string; + text: string; + html: string; + bcc: any; + replyto: string; + date: Date; + headers: { [key: string]: string }; + files: FileHandler[]; + smtpapi: any; + + constructor(); + constructor(options: EmailOptions); + + addTo(address: string): void; + addHeader(type: string, value: string): void; + addSubstitution(type: string, value: string): void; + addSubstitution(type: string, value: string[]): void; + addSection(section: { [key: string]: string }): void; + addUniqueArg(uarg: { [key: string]: string }): void; + addCategory(category: string): void; + addFilter(filter: string, command: string, value: number): void; + addFilter(filter: string, command: string, value: string): void; + addFile(file: FileHandlerOptions): void; + + setFrom(address: string): void; + setSubject(subject: string): void; + setText(text: string): void; + setHtml(html: string): void; + setHeaders(headers: { [key: string]: string }): void; + setSubstitutions(substitutions: { [key: string]: string[] }): void; + setSections(sections: { [key: string]: string }): void; + setUniqueArgs(uargs: { [key: string]: string }): void; + setCategories(categories: string[]): void; + setFilters(filters: any): void; + } + + //#endregion + + //#region FileHandler + + export interface FileHandlerOptions { + filename?: string; + contentType?: string; + cid?: string; + path?: string; + url?: string; + content?: any; + } + + export class FileHandler { + filename: string; + contentType: string; + cid: string; + + type: string; + content: string; + path: string; + url: string; + + constructor(options: FileHandlerOptions); + + loadContent(callback: HandlerCallback): void; + + static handlers: { + content: Handler; + path: Handler; + url: Handler; + none: Handler; + }; + } + + export interface Handler { + (file: FileHandler, callback: HandlerCallback): void; + } + + export interface HandlerCallback { + (hasError: boolean, error: Error): void; + (hasError: boolean, error: string): void; + } + + //#endregion + + //#region Sendgrid Class + + interface Constructor { + (api_user: string, api_key: string, options?: Options): Instance; + new (api_user: string, api_key: string, options?: Options): Instance; + } + + export interface Instance { + version: string; + api_user: string; + api_key: string; + options: OptionsExport; + Email: typeof Email; + + send(email: EmailOptions, callback: (err: Error, json: any) => any): void; + send(email: Email, callback: (err: Error, json: any) => any): void; + } + + //#endregion +} + +declare module "sendgrid" { + var ctor: Sendgrid.Constructor; + export = ctor; +} \ No newline at end of file diff --git a/sendgrid/sendgrid-tests.ts b/sendgrid/sendgrid-tests.ts index e7d34feb08..37c0c98a2b 100644 --- a/sendgrid/sendgrid-tests.ts +++ b/sendgrid/sendgrid-tests.ts @@ -1,14 +1,12 @@ /** - * Test suite created by Maxime LUCE - * * Created by using code samples from https://github.com/sendgrid/sendgrid-nodejs#usage */ /// /// -import sg = require("sendgrid"); -var sendgrid = sg("api_user", "api_key"); +import sg = require('sendgrid'); +var sendgrid = sg('YOUR_SENDGRID_API_KEY'); /* * Simple Usage @@ -19,11 +17,11 @@ var payload = { subject: 'Saying Hi', text: 'This is my first email through SendGrid' }; + sendgrid.send(payload, function (err, json) { if (err) { console.error(err); } - console.log(json); }); @@ -63,6 +61,30 @@ email.addTo('foo@bar.com'); email.addTo('another@another.com'); sendgrid.send(email, function (err, json) { }); +/** + * addSmtpapiTo + * https://github.com/sendgrid/sendgrid-nodejs#addsmtpapito + */ +var email = new sendgrid.Email() +email.addSmtpapiTo('test@test.com'); +sendgrid.send(email, function(err, json) { }); + +/** + * setTos + * https://github.com/sendgrid/sendgrid-nodejs#settos + */ +var email = new sendgrid.Email(); +email.setTos(['foo@bar.com', 'another@another.com']); +sendgrid.send(email, function(err, json) { }); + +/** + * setSmtpapiTos + * https://github.com/sendgrid/sendgrid-nodejs#setsmtpapitos + */ +var email = new sendgrid.Email(); +email.setSmtpapiTos(["test@test.com","test2@test.com"]); +sendgrid.send(email, function(err, json) { }); + /** * setFrom @@ -72,6 +94,48 @@ var email = new sendgrid.Email(); email.setFrom('foo@bar.com'); sendgrid.send(email, function (err, json) { }); +/** + * setFromName + * https://github.com/sendgrid/sendgrid-nodejs#setfromname + */ +var email = new sendgrid.Email(); +email.setFromName('Bob Bar'); +sendgrid.send(email, function(err, json) { }); + +/** + * addCc + * https://github.com/sendgrid/sendgrid-nodejs#addcc + */ +var email = new sendgrid.Email(); +email.addCc('foo@bar.com'); +email.addCc('another@another.com'); +sendgrid.send(email, function(err, json) { }); + +/** + * setCcs + * https://github.com/sendgrid/sendgrid-nodejs#setccs + */ +var email = new sendgrid.Email(); +email.setCcs(['foo@bar.com', 'another@another.com']); +sendgrid.send(email, function(err, json) { }); + +/** + * addBcc + * https://github.com/sendgrid/sendgrid-nodejs#addbcc + */ +var email = new sendgrid.Email(); +email.addBcc('foo@bar.com'); +email.addBcc('another@another.com'); +sendgrid.send(email, function(err, json) { }); + +/** + * setBccs + * https://github.com/sendgrid/sendgrid-nodejs#setbccs + */ +var email = new sendgrid.Email(); +email.setBccs(['foo@bar.com', 'another@another.com']); +sendgrid.send(email, function(err, json) { }); + /** * setSubject * https://github.com/sendgrid/sendgrid-nodejs#setsubject @@ -96,6 +160,39 @@ var email = new sendgrid.Email(); email.setHtml('

Some html

'); sendgrid.send(email, function (err, json) { }); +/** + * setDate + * https://github.com/sendgrid/sendgrid-nodejs#setdate + */ +var email = new sendgrid.Email(); +email.setDate('Wed, 17 Dec 2014 19:21:16 +0000'); +sendgrid.send(email, function(err, json) { }); + +/** + * setSendAt + * https://github.com/sendgrid/sendgrid-nodejs#setsendat + */ +var email = new sendgrid.Email(); +email.setSendAt(1409348513); +sendgrid.send(email, function(err, json) { }); + +/** + * setSendEachAt + * https://github.com/sendgrid/sendgrid-nodejs#setsendeachat + */ +var email = new sendgrid.Email(); +email.setSendEachAt([1409348513, 1409348514]); +sendgrid.send(email, function(err, json) { }); + +/** + * addSendEachAt + * https://github.com/sendgrid/sendgrid-nodejs#addsendeachat + */ +var email = new sendgrid.Email(); +email.addSendEachAt(1409348513); +email.addSendEachAt(1409348514); +sendgrid.send(email, function(err, json) { }); + /** * addHeader * https://github.com/sendgrid/sendgrid-nodejs#addheader @@ -200,6 +297,13 @@ email.setFilters({ } }); +/** + * setASMGroupID + * https://github.com/sendgrid/sendgrid-nodejs#setasmgroupid + */ +var email = new sendgrid.Email(); +email.setASMGroupID(123); + /** * addFile * https://github.com/sendgrid/sendgrid-nodejs#addfile diff --git a/sendgrid/sendgrid.d.ts b/sendgrid/sendgrid.d.ts index 602e3de4fd..b61db7162e 100644 --- a/sendgrid/sendgrid.d.ts +++ b/sendgrid/sendgrid.d.ts @@ -1,8 +1,10 @@ -// Type definitions for sendgrid 1.1.0 +// Type definitions for sendgrid v2.0.0 // Project: https://github.com/sendgrid/sendgrid-nodejs // Definitions by: Maxime LUCE // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// + declare namespace Sendgrid { //#region Options @@ -52,7 +54,7 @@ declare namespace Sendgrid { date?: Date; headers?: { [key: string]: string }; files?: FileHandlerOptions[]; - smtpapi?: any; + smtpapi?: SmtpApi.Instance; } export class Email { @@ -68,32 +70,47 @@ declare namespace Sendgrid { date: Date; headers: { [key: string]: string }; files: FileHandler[]; - smtpapi: any; + smtpapi: SmtpApi.Instance; constructor(); constructor(options: EmailOptions); - addTo(address: string): void; - addHeader(type: string, value: string): void; - addSubstitution(type: string, value: string): void; - addSubstitution(type: string, value: string[]): void; - addSection(section: { [key: string]: string }): void; - addUniqueArg(uarg: { [key: string]: string }): void; - addCategory(category: string): void; - addFilter(filter: string, command: string, value: number): void; - addFilter(filter: string, command: string, value: string): void; - addFile(file: FileHandlerOptions): void; + new(options: EmailOptions): Email; - setFrom(address: string): void; - setSubject(subject: string): void; - setText(text: string): void; - setHtml(html: string): void; - setHeaders(headers: { [key: string]: string }): void; - setSubstitutions(substitutions: { [key: string]: string[] }): void; - setSections(sections: { [key: string]: string }): void; - setUniqueArgs(uargs: { [key: string]: string }): void; - setCategories(categories: string[]): void; - setFilters(filters: any): void; + addTo(address: string): Email; + addHeader(type: string, value: string): Email; + addSubstitution(type: string, value: string): Email; + addSubstitution(type: string, value: string[]): Email; + addSection(section: { [key: string]: string }): Email; + addUniqueArg(uarg: { [key: string]: string }): Email; + addCategory(category: string): Email; + addFilter(filter: string, command: string, value: number): Email; + addFilter(filter: string, command: string, value: string): Email; + addFile(file: FileHandlerOptions): Email; + addSmtpapiTo(to: string): Email; + addCc(cc: string): Email; + addBcc(bcc: string): Email; + addSendEachAt(send_each_at: number): Email; + + setFrom(address: string): Email; + setSubject(subject: string): Email; + setText(text: string): Email; + setHtml(html: string): Email; + setHeaders(headers: { [key: string]: string }): Email; + setSubstitutions(substitutions: { [key: string]: string[] }): Email; + setSections(sections: { [key: string]: string }): Email; + setUniqueArgs(uargs: { [key: string]: string }): Email; + setCategories(categories: string[]): Email; + setFilters(filters: any): Email; + setSmtpapiTos(tos: string[]): Email; + setTos(tos: string[]): Email; + setFromName(fromname: string): Email; + setCcs(ccs: string[]): Email; + setBccs(bcc: string[]): Email; + setDate(date: string): Email; + setSendAt(send_at: number): Email; + setSendEachAt(send_each_at: number[]): Email; + setASMGroupID(val: number): Email; } //#endregion @@ -146,18 +163,21 @@ declare namespace Sendgrid { interface Constructor { (api_user: string, api_key: string, options?: Options): Instance; + (api_key: string, option?: Options): Instance new (api_user: string, api_key: string, options?: Options): Instance; + new (api_key: string, options?: Options): Instance; } export interface Instance { version: string; api_user: string; api_key: string; + smtpapi: SmtpApi.Instance; options: OptionsExport; Email: typeof Email; - send(email: EmailOptions, callback: (err: Error, json: any) => any): void; - send(email: Email, callback: (err: Error, json: any) => any): void; + send(email: EmailOptions, callback: (err: Error, json: Object) => any): void; + send(email: Email, callback: (err: Error, json: Object) => any): void; } //#endregion From ccb4c316dcafde1bda8cd3aedbd2b95cbff20b47 Mon Sep 17 00:00:00 2001 From: Robin Joseph Date: Sat, 21 May 2016 08:26:37 -0700 Subject: [PATCH 096/402] allow objects for hapi's request.log (#9353) --- hapi/hapi-tests.ts | 1 + hapi/hapi.d.ts | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/hapi/hapi-tests.ts b/hapi/hapi-tests.ts index d45c03549a..743a4ad3ee 100644 --- a/hapi/hapi-tests.ts +++ b/hapi/hapi-tests.ts @@ -79,6 +79,7 @@ server.route({ method: 'GET', path: '/hello', handler: function (request: Hapi.Request, reply: Function) { + request.log('info', { route: '/hello' }, Date.now()); reply('hello world'); } }); diff --git a/hapi/hapi.d.ts b/hapi/hapi.d.ts index 9962dd6c62..05f4aa1047 100644 --- a/hapi/hapi.d.ts +++ b/hapi/hapi.d.ts @@ -1301,7 +1301,7 @@ declare module "hapi" { log(/** a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism for describing and filtering events.*/ tags: string | string[], /** an optional message string or object with the application data being logged.*/ - data?: string, + data?: any, /** an optional timestamp expressed in milliseconds. Defaults to Date.now() (now).*/ timestamp?: number): void; From 03fd25f9b0fdf12b5863ce01c9bde3b04184f37f Mon Sep 17 00:00:00 2001 From: Erick Ponce Date: Sat, 21 May 2016 12:26:53 -0300 Subject: [PATCH 097/402] Update ioredis.d.ts (#9362) Added new option dropBufferSupport that is used with hiredis parser --- ioredis/ioredis.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/ioredis/ioredis.d.ts b/ioredis/ioredis.d.ts index d8cd4b3c70..42a498addc 100644 --- a/ioredis/ioredis.d.ts +++ b/ioredis/ioredis.d.ts @@ -678,6 +678,10 @@ declare module IORedis { * default: false. */ readOnly?: boolean; + /** + * If you are using the hiredis parser, it's highly recommended to enable this option. Create another instance with dropBufferSupport disabled for other commands that you want to return binary instead of string: + */ + dropBufferSupport?: boolean; } interface ScanStreamOption { From bb7f67e2e1026054ab2d2d6d7c253a2478834d7d Mon Sep 17 00:00:00 2001 From: arcdev1 Date: Sat, 21 May 2016 11:32:51 -0400 Subject: [PATCH 098/402] add type defintions for correct md5 module (per npm) (#9347) * add type defintions for correct md5 module (per npm) * Corrected md5 to CybozuLabs-md5 * added typings for md5 (npm version) --- CybozuLabs-md5/CybozuLabs-md5-tests.ts | 9 ++++++ CybozuLabs-md5/CybozuLabs-md5.d.ts | 11 ++++++++ md5/md5-tests.ts | 38 +++++++++++++++++++++----- md5/md5.d.ts | 21 ++++++++------ 4 files changed, 64 insertions(+), 15 deletions(-) create mode 100644 CybozuLabs-md5/CybozuLabs-md5-tests.ts create mode 100644 CybozuLabs-md5/CybozuLabs-md5.d.ts diff --git a/CybozuLabs-md5/CybozuLabs-md5-tests.ts b/CybozuLabs-md5/CybozuLabs-md5-tests.ts new file mode 100644 index 0000000000..16dd05b059 --- /dev/null +++ b/CybozuLabs-md5/CybozuLabs-md5-tests.ts @@ -0,0 +1,9 @@ +/// + +var hash: string; +hash = CybozuLabs.MD5.calc("abc"); +hash = CybozuLabs.MD5.calc("abc", CybozuLabs.MD5.BY_ASCII); +hash = CybozuLabs.MD5.calc("abc", CybozuLabs.MD5.BY_UTF16); + +var version: string; +version = CybozuLabs.MD5.VERSION; \ No newline at end of file diff --git a/CybozuLabs-md5/CybozuLabs-md5.d.ts b/CybozuLabs-md5/CybozuLabs-md5.d.ts new file mode 100644 index 0000000000..6e1f31739d --- /dev/null +++ b/CybozuLabs-md5/CybozuLabs-md5.d.ts @@ -0,0 +1,11 @@ +// Type definitions for CybozuLabs.MD5 +// Project: http://labs.cybozu.co.jp/blog/mitsunari/2007/07/md5js_1.html +// Definitions by: MIZUNE Pine +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace CybozuLabs.MD5 { + var VERSION: string; + var BY_ASCII: number; + var BY_UTF16: number; + function calc(str: string, option?: number): string; +} diff --git a/md5/md5-tests.ts b/md5/md5-tests.ts index 360bb4b382..16e4ad35df 100644 --- a/md5/md5-tests.ts +++ b/md5/md5-tests.ts @@ -1,9 +1,33 @@ /// +/// +import fs =require("fs"); +import md5 = require("md5"); +/** + * API + * md5(message) + * message -- String or Buffer + * returns String + * + * Usage + **************************************************** + * var md5 = require('md5'); * + * console.log(md5('message')); * + **************************************************** + * This will print the following + * 78e731027d8fd50ed642340b7c9a63b3 + * + * It supports buffers, too + **************************************************** + * var fs = require('fs'); * + * var md5 = require('md5'); * + * * + * fs.readFile('example.txt', function(err, buf) { * + * console.log(md5(buf)); * + * }); * + * ************************************************** + */ +console.log(md5('message')); // should print 78e731027d8fd50ed642340b7c9a63b3 -var hash: string; -hash = CybozuLabs.MD5.calc("abc"); -hash = CybozuLabs.MD5.calc("abc", CybozuLabs.MD5.BY_ASCII); -hash = CybozuLabs.MD5.calc("abc", CybozuLabs.MD5.BY_UTF16); - -var version: string; -version = CybozuLabs.MD5.VERSION; \ No newline at end of file +fs.readFile('md5.d.ts', function(err: Error, buf: Buffer) { + console.log(md5(buf)); +}); \ No newline at end of file diff --git a/md5/md5.d.ts b/md5/md5.d.ts index 6e1f31739d..47529718a1 100644 --- a/md5/md5.d.ts +++ b/md5/md5.d.ts @@ -1,11 +1,16 @@ -// Type definitions for CybozuLabs.MD5 -// Project: http://labs.cybozu.co.jp/blog/mitsunari/2007/07/md5js_1.html -// Definitions by: MIZUNE Pine +// Type definitions for md5 v2.1.0 +// Project: https://github.com/pvorb/node-md5 +// Definitions by: Bill Sourour // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare namespace CybozuLabs.MD5 { - var VERSION: string; - var BY_ASCII: number; - var BY_UTF16: number; - function calc(str: string, option?: number): string; +/// +declare module 'md5' { +/** + * js function for hashing messages with MD5 + * + * @param {(string | Buffer)} message - a string or buffer to hash + * @returns {string} the resultant MD5 hash of the given message + */ + function main(message: string | Buffer): string; + export = main; } From 4ec043b45149ecc525f0f5cb447ebd3eec30d552 Mon Sep 17 00:00:00 2001 From: Florian Plattner Date: Sat, 21 May 2016 17:34:13 +0200 Subject: [PATCH 099/402] Update node schedule (#8827) * updated typings for node-schedule * some fixes * corrects spelling and references on node-schedule --- node-schedule/node-schedule-tests.ts | 130 +++++++++++--- node-schedule/node-schedule.d.ts | 246 +++++++++++++++++++-------- 2 files changed, 273 insertions(+), 103 deletions(-) diff --git a/node-schedule/node-schedule-tests.ts b/node-schedule/node-schedule-tests.ts index bc4dbbd743..bc8626767d 100644 --- a/node-schedule/node-schedule-tests.ts +++ b/node-schedule/node-schedule-tests.ts @@ -6,12 +6,85 @@ import nodeSchedule = require("node-schedule"); * Test for {@link Job} class. */ function testJob() { - var name: string = ''; - var job: Function = null; + var name:string = ''; + var jc:nodeSchedule.JobCallback = null; var callback: Function = null; - new nodeSchedule.Job(job, callback); - new nodeSchedule.Job(name, job, callback); + var jobSpec:nodeSchedule.Job = new nodeSchedule.Job(jc); + var job:nodeSchedule.Job = new nodeSchedule.Job(jc, callback); + var job:nodeSchedule.Job = new nodeSchedule.Job(name, jc, callback); + + var jobName:string = job.name; +} + +function testTrackInvocation() { + var job:nodeSchedule.Job = new nodeSchedule.Job(() => {}); + var success:boolean = job.trackInvocation( + new nodeSchedule.Invocation(job, new Date(), new nodeSchedule.RecurrenceRule(0, 0, 0, 0, 0, 0, 0)) + ); +} + +function testStopTrackingInvocation() { + var job:nodeSchedule.Job = new nodeSchedule.Job(() => {}); + var success = job.stopTrackingInvocation( + new nodeSchedule.Invocation(job, new Date(), new nodeSchedule.RecurrenceRule(0, 0, 0, 0, 0, 0, 0)) + ); +} + +function testTriggeredJobs() { + var job:nodeSchedule.Job = new nodeSchedule.Job(() => {}); + var triggeredJobs:number = job.triggeredJobs(); +} + +function testSetTriggeredJobs() { + var job:nodeSchedule.Job = new nodeSchedule.Job(() => {}); + job.setTriggeredJobs(19); +} + +function testCancel() { + var job:nodeSchedule.Job = new nodeSchedule.Job(() => {}); + var success:boolean = job.cancel(); + var success:boolean = job.cancel(true); +} + +function testCancelNext() { + var job:nodeSchedule.Job = new nodeSchedule.Job(() => {}); + var success:boolean = job.cancelNext(); + var success:boolean = job.cancelNext(true); +} + +function testReschedule() { + var job:nodeSchedule.Job = new nodeSchedule.Job(() => {}); + var success:boolean = job.reschedule(''); + var success:boolean = job.reschedule(1234); + var success:boolean = job.reschedule(new nodeSchedule.RecurrenceRule(0, 0, 0, 0, 0, 0, 0)); +} + +function testNextInvocation() { + var job:nodeSchedule.Job = new nodeSchedule.Job(() => {}); + var nextInvocation:Date = job.nextInvocation(); +} + +function testPendingInvocations() { + var job:nodeSchedule.Job = new nodeSchedule.Job(() => {}); + var pendingInvocations:nodeSchedule.Invocation[] = job.pendingInvocations(); +} + +function testInvoke() { + var job:nodeSchedule.Job = new nodeSchedule.Job(() => {}); + job.invoke(); +} + +function testRunOnDate() { + var job:nodeSchedule.Job = new nodeSchedule.Job(() => {}); + job.runOnDate(new Date()); +} + +function testSchedule() { + var job:nodeSchedule.Job = new nodeSchedule.Job(() => {}); + var success:boolean = job.schedule(new Date()); + success = job.schedule(''); + success = job.schedule(1234); } /** @@ -19,10 +92,10 @@ function testJob() { */ function testRange() { var range = new nodeSchedule.Range(0); - var twoParametersRange = new nodeSchedule.Range(0, 0); - var threeParametersRange = new nodeSchedule.Range(0, 0, 0); + var twoParametersRange:nodeSchedule.Range = new nodeSchedule.Range(0, 0); + var threeParametersRange:nodeSchedule.Range = new nodeSchedule.Range(0, 0, 0); - var contained: boolean = range.contains(0); + var contained:boolean = range.contains(0); } /** @@ -30,50 +103,51 @@ function testRange() { */ function testRecurrenceRule() { var range = new nodeSchedule.Range(0, 0, 0); - var rule: nodeSchedule.RecurrenceRule = { - date: 0, - dayOfWeek: [0, range], - hour: 0, - minute: 0, - month: 0, - second: 0, - year: 0 - } + var rule:nodeSchedule.RecurrenceRule = new nodeSchedule.RecurrenceRule(0, 0, 0, [0, range], 0, 0, 0); + var rule:nodeSchedule.RecurrenceRule = new nodeSchedule.RecurrenceRule(0, 0, 0, 0, 0, 0, 0); + + var nextInvocation:Date = rule.nextInvocationDate(new Date()); } /** * Test for {@link Invocation} class. */ function testInvocation() { - var job = new nodeSchedule.Job(); + var job = new nodeSchedule.Job(() => {}); var fireDate = new Date(); - var rule: nodeSchedule.RecurrenceRule = {}; + var rule: nodeSchedule.RecurrenceRule = new nodeSchedule.RecurrenceRule(0, 0, 0, 0, 0, 0, 0); var invocation = new nodeSchedule.Invocation(job, fireDate, rule); invocation.timerID = 0; } /** - * Test for {@link ScheduleJob} class. + * Test for {@link scheduleJob} class. */ function testScheduleJob() { - var callback: Function = null; - nodeSchedule.scheduleJob('', callback); + var callback: nodeSchedule.JobCallback = null; + var job:nodeSchedule.Job = nodeSchedule.scheduleJob('', callback); - var rule: nodeSchedule.RecurrenceRule = {}; - nodeSchedule.scheduleJob(rule, callback); + var rule: nodeSchedule.RecurrenceRule = new nodeSchedule.RecurrenceRule(0, 0, 0, 0, 0, 0, 0); + var job:nodeSchedule.Job = nodeSchedule.scheduleJob(rule, callback); var date: Date = new Date(); - nodeSchedule.scheduleJob(date, callback); + var job:nodeSchedule.Job = nodeSchedule.scheduleJob(date, callback); +} - var date: Date = new Date(); - nodeSchedule.scheduleJob(date, callback); +function testRescheduleJob() { + var job:nodeSchedule.Job = nodeSchedule.rescheduleJob(new nodeSchedule.Job(() => {}), new Date()); + job = nodeSchedule.rescheduleJob(new nodeSchedule.Job(() => {}), new nodeSchedule.RecurrenceRule(0, 0, 0, 0, 0, 0, 0)); + job = nodeSchedule.rescheduleJob(new nodeSchedule.Job(() => {}), ''); + job = nodeSchedule.rescheduleJob('', ''); } /** * Test for {@link cancelJob} function. */ function testCancelJob() { - var job = new nodeSchedule.Job(); - nodeSchedule.cancelJob(job); + var job = new nodeSchedule.Job(() => {}); + var success:boolean = nodeSchedule.cancelJob(job); + + success = nodeSchedule.cancelJob('jobName'); } diff --git a/node-schedule/node-schedule.d.ts b/node-schedule/node-schedule.d.ts index 17dbb8402a..5127eafb40 100644 --- a/node-schedule/node-schedule.d.ts +++ b/node-schedule/node-schedule.d.ts @@ -1,70 +1,120 @@ -// Type definitions for node-schedule +// Type definitions for node-schedule 1.1.0 // Project: https://github.com/tejasmanohar/node-schedule/ -// Definitions by: Cyril Schumacher +// Definitions by: Cyril Schumacher , Florian Plattner // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "node-schedule" { +/// + +declare module 'node-schedule' { import nodeSchedule = require('node-schedule'); + import {EventEmitter} from 'events'; /** - * Recurrence rules. + * The callback executed by a Job */ - export interface RecurrenceRule { + export interface JobCallback { + ():void; + } + + /** + * Scheduler jobs. + * + * @class + */ + export class Job extends EventEmitter { /** - * Day of the month. - * - * @public - * @type {number} + * This Job's name. read-only. */ - date?: number; + name:string; /** - * Day of the week. + * Use the function scheduleJob() to create new Job objects. * - * @public - * @type {number|Array} + * @constructor + * @internal + * @param {string|JobCallback} name either an optional name for this Job or this Job's callback + * @param {JobCallback|Function} job either this Job's callback or an optional callback function + * @param {Function} callback optional callback that is executed right before the JobCallback */ - dayOfWeek?: number|Array; + constructor(name: string|JobCallback, job?: JobCallback|Function, callback?: Function); /** - * Hour. - * - * @public - * @type {number} + * Adds an Invocation to this job. For internal use. + * @internal + * @param {Invocation} invokation + * @return {boolean} whether the invocation could be added */ - hour?: number; + trackInvocation(invokation:Invocation):boolean; /** - * Minute. - * - * @public - * @type {number} + * removes an Invocation from this Job's tracking list. For internal use. + * @internal + * @param invocation {Invocation} + * @return boolean whether the invocation was successful. Removing an Invocation that doesn't exist, returns false. */ - minute?: number; + stopTrackingInvocation(invocation:Invocation):boolean; /** - * Month. - * - * @public - * @type {number} + * @internal + * @return {number} the number of currently running instances of this Job. */ - month?: number; + triggeredJobs():number; /** - * Second. - * - * @public - * @type {number} + * set the number of currently running Jobs. + * @internal + * @param triggeredJobs */ - second?: number; + setTriggeredJobs(triggeredJobs:number):void; /** - * Year. - * - * @public - * @type {number} + * cancel all pending Invocations of this Job. + * @param reschedule {boolean} whether to reschedule the canceled Invocations. */ - year?: number; + cancel(reschedule?:boolean):boolean; + + /** + * cancel the next Invocation of this Job. + * @param reschedule {boolean} whether to reschedule the canceled Invocation. + * @return {boolean} whether cancelation was successful + */ + cancelNext(reschedule?:boolean):boolean; + + /** + * Changes the scheduling information for this Job. + * @param spec {RecurrenceRule|string|number} the + * @return {boolean} whether the reschedule was successful + */ + reschedule(spec:RecurrenceRule|string|number):boolean; + + /** + * Returns the Date on which this Job will be run next. + * @return {Date} + */ + nextInvocation():Date; + + /** + * @return Invocation[] a list of all pending Invocations + */ + pendingInvocations():Invocation[]; + + /** + * run this Job immediately. + */ + invoke():void; + + /** + * schedule this Job to be run on the specified date. + * @param date {Date} + */ + runOnDate(date:Date): void; + + /** + * set scheduling information + * @param {Date|string|number} date + * @public + */ + schedule(date: Date|string|number): boolean; } /** @@ -93,43 +143,74 @@ declare module "node-schedule" { } /** - * Scheduler jobs. - * - * @class + * Recurrence rules. */ - export class Job { + export class RecurrenceRule { /** - * Constructor. - * - * @constructor - * @param {RecurrenceRule} rule The rule. - * @param {callback} callback The callback. - */ - constructor(name?: string, job?: Function, callback?: Function); - - /** - * Constructor. - * - * @constructor - * @param {RecurrenceRule} rule The rule. - * @param - */ - constructor(job?: Function, callback?: Function); - - /** - * Attach an event handler function. + * Day of the month. * * @public - * @param {string} eventName The event name. - * @param {Function} handler The function to execute when the event is triggered. + * @type {number} */ - on(eventName: string, handler: Function): void; + date: number; /** + * Day of the week. * * @public + * @type {number|Array} */ - schedule(date: Date): void; + dayOfWeek: number|Array; + + /** + * Hour. + * + * @public + * @type {number} + */ + hour: number; + + /** + * Minute. + * + * @public + * @type {number} + */ + minute: number; + + /** + * Month. + * + * @public + * @type {number} + */ + month: number; + + /** + * Second. + * + * @public + * @type {number} + */ + second: number; + + /** + * Year. + * + * @public + * @type {number} + */ + year: number; + + constructor(year:number, + month:number, + date:number, + dayOfWeek:number|Array, + hour:number, + minute:number, + second:number); + + nextInvocationDate(base:Date):Date; } /** @@ -181,19 +262,34 @@ declare module "node-schedule" { constructor(job: Job, fireDate: Date, recurrenceRule: RecurrenceRule); } + /** + * Create a schedule job. + * + * @param {string|RecurrenceRule|Date} name either an optional name for the new Job or scheduling information + * @param {RecurrenceRule|Date|string} rule either the scheduling info or the JobCallback + * @param {JobCallback} callback The callback to be executed on each invocation. + */ + export function scheduleJob(name:string|RecurrenceRule|Date, rule: RecurrenceRule|Date|string|JobCallback, callback?: JobCallback): Job; + + /** + * Changes the timing of a Job, canceling all pending invocations. + * + * @param job {Job} + * @param spec {JobCallback} the new timing for this Job + * @return {Job} if the job could be rescheduled, {null} otherwise. + */ + export function rescheduleJob(job:Job|string, spec:RecurrenceRule|Date|string):Job; + + /** + * Dictionary of all Jobs, accessible by name. + */ + export let scheduledJobs:{[jobName:string]:Job}; + /** * Cancels the job. * * @param {Job} job The job. * @returns {boolean} {true} if the job has been cancelled with success, otherwise, {false}. */ - export function cancelJob(job: Job): boolean; - - /** - * Create a schedule job. - * - * @param {RecurrenceRule} rule The rule. - * @param {Function} callback The callback. - */ - export function scheduleJob(rule: RecurrenceRule|Date|string, callback: Function): void; + export function cancelJob(job: Job|string): boolean; } From 9d10809d055036af0a21989c508c7d8cccb97f0e Mon Sep 17 00:00:00 2001 From: Doug Miller Date: Sat, 21 May 2016 11:35:43 -0400 Subject: [PATCH 100/402] Added language and languages properties (#9372) --- i18next/i18next-tests.ts | 2 ++ i18next/i18next.d.ts | 4 ++++ 2 files changed, 6 insertions(+) diff --git a/i18next/i18next-tests.ts b/i18next/i18next-tests.ts index e46a9ed5bf..373b7394b4 100644 --- a/i18next/i18next-tests.ts +++ b/i18next/i18next-tests.ts @@ -62,3 +62,5 @@ i18n.t('helloWorld', { defaultValue: 'default', count: 10 }); +const currentLanguage:string = i18n.language; +const userLanguageCodes:string[] = i18n.languages; diff --git a/i18next/i18next.d.ts b/i18next/i18next.d.ts index 9f976fd751..5e2f8dcd20 100644 --- a/i18next/i18next.d.ts +++ b/i18next/i18next.d.ts @@ -94,6 +94,10 @@ declare namespace I18next { loadResources(callback?:(err:any) => void):void; + language:string; + + languages:string[]; + use(module:any):I18n; changeLanguage(lng:string, callback?:(err:any, t:TranslationFunction) => void):void; From 63abab7f6b5a5b244b07ac7e1d14c527de27339c Mon Sep 17 00:00:00 2001 From: developermj Date: Sat, 21 May 2016 08:37:27 -0700 Subject: [PATCH 101/402] Adding string to after option for dotdotdot as per documentation (#9373) --- dotdotdot/dotdotdot-tests.ts | 1 + dotdotdot/dotdotdot.d.ts | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/dotdotdot/dotdotdot-tests.ts b/dotdotdot/dotdotdot-tests.ts index 95fe346745..6920d3c2c0 100644 --- a/dotdotdot/dotdotdot-tests.ts +++ b/dotdotdot/dotdotdot-tests.ts @@ -4,6 +4,7 @@ $("span").dotdotdot({ ellipsis: ":::" }); $("span").dotdotdot({ wrap: "letter" }); $("span").dotdotdot({ fallbackToLetter: false }); +$("span").dotdotdot({ after: "a.after" }); $("span").dotdotdot({ after: $("#after") }); $("span").dotdotdot({ watch: true }); $("span").dotdotdot({ height: 42 }); diff --git a/dotdotdot/dotdotdot.d.ts b/dotdotdot/dotdotdot.d.ts index 6219340ba6..bedd6cecac 100644 --- a/dotdotdot/dotdotdot.d.ts +++ b/dotdotdot/dotdotdot.d.ts @@ -31,7 +31,7 @@ declare namespace JQueryDotDotDot { /** jQuery-selector for the element to keep and put after the ellipsis. * Default: null */ - after?: JQuery; + after?: string | JQuery; /** Whether to update the ellipsis: true/'window' * Default: false From 91b137179600e34f4d45a28e7dd8c297c1b825e4 Mon Sep 17 00:00:00 2001 From: Evan Sebastian Date: Sat, 21 May 2016 22:41:16 +0700 Subject: [PATCH 102/402] redux-actions: Un-restrict types of payload and reducer state (#9380) --- redux-actions/redux-actions-tests.ts | 37 ++++++++++++++++------------ redux-actions/redux-actions.d.ts | 25 ++++++++++--------- 2 files changed, 35 insertions(+), 27 deletions(-) diff --git a/redux-actions/redux-actions-tests.ts b/redux-actions/redux-actions-tests.ts index 3d97157a6c..61d89b06f4 100644 --- a/redux-actions/redux-actions-tests.ts +++ b/redux-actions/redux-actions-tests.ts @@ -13,14 +13,14 @@ const multiplyAction: (...args: number[]) => ReduxActions.Action = Redux const action: ReduxActions.Action = incrementAction(); -const actionHandler = ReduxActions.handleAction( +const actionHandler = ReduxActions.handleAction( 'INCREMENT', (state: number, action: ReduxActions.Action) => state + action.payload ); state = actionHandler(0, incrementAction()); -const actionHandlerWithReduceMap = ReduxActions.handleAction( +const actionHandlerWithReduceMap = ReduxActions.handleAction( 'MULTIPLY', { next(state: number, action: ReduxActions.Action) { return state * action.payload; @@ -31,14 +31,14 @@ const actionHandlerWithReduceMap = ReduxActions.handleAction( state = actionHandlerWithReduceMap(0, multiplyAction(10)); -const actionsHandler = ReduxActions.handleActions({ +const actionsHandler = ReduxActions.handleActions({ 'INCREMENT': (state: number, action: ReduxActions.Action) => state + action.payload, 'MULTIPLY': (state: number, action: ReduxActions.Action) => state * action.payload }); state = actionsHandler(0, { type: 'INCREMENT' }); -const actionsHandlerWithInitialState = ReduxActions.handleActions({ +const actionsHandlerWithInitialState = ReduxActions.handleActions({ 'INCREMENT': (state: number, action: ReduxActions.Action) => state + action.payload, 'MULTIPLY': (state: number, action: ReduxActions.Action) => state * action.payload }, 0); @@ -51,6 +51,10 @@ type TypedState = { value: number; }; +type TypedPayload = { + increase: number; +} + type MetaType = { remote: boolean }; @@ -68,28 +72,29 @@ const richerAction: ReduxActions.ActionMeta = { } }; -const typedIncrementAction: () => ReduxActions.Action = ReduxActions.createAction( +const typedIncrementAction: () => ReduxActions.Action = ReduxActions.createAction( 'INCREMENT', - () => ({ value: 1 }) + () => ({ increase: 1 }) ); -const typedActionHandler = ReduxActions.handleAction( +const typedActionHandler = ReduxActions.handleAction( 'INCREMENT', - (state: TypedState, action: ReduxActions.Action) => ({ value: state.value + 1 }) + (state: TypedState, action: ReduxActions.Action) => ({ value: state.value + 1 }) ); typedState = typedActionHandler({ value: 0 }, typedIncrementAction()); -const typedIncrementByActionWithMeta: (value: number) => ReduxActions.ActionMeta = ReduxActions.createAction( - 'INCREMENT_BY', - amount => ({ value: amount }), - amount => ({ remote: true }) -); +const typedIncrementByActionWithMeta: (value: number) => ReduxActions.ActionMeta = + ReduxActions.createAction( + 'INCREMENT_BY', + amount => ({ increase: amount }), + amount => ({ remote: true }) + ); -const typedActionHandlerWithReduceMap = ReduxActions.handleAction( +const typedActionHandlerWithReduceMap = ReduxActions.handleAction( 'INCREMENT_BY', { - next(state: TypedState, action: ReduxActions.Action) { - return { value: state.value + action.payload.value }; + next(state: TypedState, action: ReduxActions.Action) { + return { value: state.value + action.payload.increase }; }, throw(state: TypedState) { return state } } diff --git a/redux-actions/redux-actions.d.ts b/redux-actions/redux-actions.d.ts index e9e2cf83a0..efed0cab66 100644 --- a/redux-actions/redux-actions.d.ts +++ b/redux-actions/redux-actions.d.ts @@ -24,12 +24,12 @@ declare namespace ReduxActions { type MetaCreator = (...args: Input[]) => Payload; - type Reducer = (state: Payload, action: Action) => Payload; + type Reducer = (state: State, action: Action) => State; - type ReducerMeta = (state: Payload, action: ActionMeta) => Payload; + type ReducerMeta = (state: State, action: ActionMeta) => State; - type ReducerMap = { - [actionType: string]: Reducer + type ReducerMap = { + [actionType: string]: Reducer }; export function createAction( @@ -54,17 +54,20 @@ declare namespace ReduxActions { metaCreator: MetaCreator ): (...args: Input[]) => ActionMeta; - export function handleAction( + export function handleAction( actionType: string, - reducer: Reducer | ReducerMap - ): Reducer; + reducer: Reducer | ReducerMap + ): Reducer; - export function handleAction( + export function handleAction( actionType: string, - reducer: ReducerMeta | ReducerMap - ): Reducer; + reducer: ReducerMeta | ReducerMap + ): Reducer; - export function handleActions(reducerMap: ReducerMap, initialState?: Payload): Reducer; + export function handleActions( + reducerMap: ReducerMap, + initialState?: State + ): Reducer; } declare module 'redux-actions' { From 8ea257c7078cf1c9c0e4149f9abe1cb2c11470d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn?= Date: Sat, 21 May 2016 17:41:45 +0200 Subject: [PATCH 103/402] protractor-http-mock: Add runtime mocks and plugin support. (#9377) --- .../protractor-http-mock-tests.ts | 136 ++++++++++++----- .../protractor-http-mock.d.ts | 141 ++++++++++++------ 2 files changed, 196 insertions(+), 81 deletions(-) diff --git a/protractor-http-mock/protractor-http-mock-tests.ts b/protractor-http-mock/protractor-http-mock-tests.ts index e6620d015f..a72a9bce0d 100644 --- a/protractor-http-mock/protractor-http-mock-tests.ts +++ b/protractor-http-mock/protractor-http-mock-tests.ts @@ -8,15 +8,10 @@ function TestConfig() { } function TestCtorOverloads() { - let noParam: mock.ProtractorHttpMock = mock(); - let emptyArray: mock.ProtractorHttpMock = mock([]); - let mockFiles: mock.ProtractorHttpMock = mock(["mock1", "mock2"]); - let skipDefaults: mock.ProtractorHttpMock = mock([], true); - let del: mock.requests.Delete = { request: { - path: "path", - method: "DELETE" + path: 'path', + method: 'DELETE' }, response: { status: 400, @@ -25,15 +20,36 @@ function TestCtorOverloads() { }; let put: mock.requests.Put = { request: { - path: "path", - method: "PUT" + path: 'path', + method: 'PUT' }, response: { status: 400, data: 1 } }; + let plugin: mock.Plugin = { + match: (mockRequest: mock.requests.Delete, requestConfig: mock.requests.AllRequests) => { + if (requestConfig.request.method && mockRequest.request.method) { + return true; + } + + return false; + } + }; + + let noParam: mock.ProtractorHttpMock = mock(); + let emptyArray: mock.ProtractorHttpMock = mock([]); + let mockFiles: mock.ProtractorHttpMock = mock(['mock1', 'mock2']); let mocks: mock.ProtractorHttpMock = mock([del, put]); + + let mockFilesNpmPlugins: mock.ProtractorHttpMock = mock(['mock1'], ['plugin']); + let mocksWithNpmPlugins: mock.ProtractorHttpMock = mock([del, put], ['plugin']); + + let pluginMocks: mock.ProtractorHttpMock = mock([del, put], [plugin]); + + let mockFilesNpmPluginsSkipDefaults: mock.ProtractorHttpMock = mock(['mock1'], ['plugin'], true); + let skipDefaults: mock.ProtractorHttpMock = mock([del, put], [plugin], true); } function TestTeardown() { @@ -85,8 +101,9 @@ function TestDyanmicRemove() { function TestGetRequestDefinitions() { let getMinium: mock.requests.Get = { request: { - path: "path", - method: "GET" + path: 'path', + method: 'GET', + regex: true }, response: { data: 1, @@ -96,10 +113,11 @@ function TestGetRequestDefinitions() { let getParams: mock.requests.Get = { request: { - path: "path", - method: "GET", + path: 'path', + method: 'GET', + regex: true, params: { - param1: "param1", + param1: 'param1', param2: 2 } }, @@ -111,8 +129,9 @@ function TestGetRequestDefinitions() { let post: mock.requests.Post = { request: { - path: "path", - method: "POST" + path: 'path', + method: 'POST', + regex: true }, response: { data: 1, @@ -122,10 +141,11 @@ function TestGetRequestDefinitions() { let getQueryString: mock.requests.Get = { request: { - path: "path", - method: "GET", + path: 'path', + method: 'GET', + regex: true, queryString: { - query1: "query1", + query1: 'query1', query2: 2 } }, @@ -137,11 +157,12 @@ function TestGetRequestDefinitions() { let getHeaders: mock.requests.Get = { request: { - path: "path", - method: "GET", + path: 'path', + method: 'GET', + regex: true, headers: { - head1: "head1", - head2: "head2" + head1: 'head1', + head2: 'head2' } }, response: { @@ -154,8 +175,9 @@ function TestGetRequestDefinitions() { function TestPostRequestDefinitions() { let post: mock.requests.Post = { request: { - path: "path", - method: "POST" + path: 'path', + method: 'POST', + regex: true }, response: { data: 1, @@ -165,9 +187,10 @@ function TestPostRequestDefinitions() { let postData: mock.requests.PostData = { request: { - path: "path", - method: "POST", - data: "data" + path: 'path', + method: 'POST', + data: 'data', + regex: true }, response: { data: 1, @@ -179,8 +202,9 @@ function TestPostRequestDefinitions() { function TestHeadRequestDefinitions() { let head: mock.requests.Head = { request: { - path: "path", - method: "HEAD" + path: 'path', + method: 'HEAD', + regex: true }, response: { status: 500, @@ -192,8 +216,9 @@ function TestHeadRequestDefinitions() { function TestDeleteRequestDefinitions() { let del: mock.requests.Delete = { request: { - path: "path", - method: "DELETE" + path: 'path', + method: 'DELETE', + regex: true }, response: { status: 500, @@ -205,8 +230,9 @@ function TestDeleteRequestDefinitions() { function TestPutRequestDefinitions() { let put: mock.requests.Put = { request: { - path: "path", - method: "PUT" + path: 'path', + method: 'PUT', + regex: true }, response: { status: 500, @@ -218,8 +244,9 @@ function TestPutRequestDefinitions() { function TestPatchRequestDefinitions() { let patch: mock.requests.Patch = { request: { - path: "path", - method: "PATCH" + path: 'path', + method: 'PATCH', + regex: true }, response: { status: 500, @@ -231,8 +258,9 @@ function TestPatchRequestDefinitions() { function TestJsonpRequestDefinitions() { let jsonp: mock.requests.Jsonp = { request: { - path: "path", - method: "JSONP" + path: 'path', + method: 'JSONP', + regex: true }, response: { status: 500, @@ -240,3 +268,35 @@ function TestJsonpRequestDefinitions() { } }; } + +function TestRuntimeMocks() { + mock.add([{ + request: { + path: '/users', + method: 'GET', + params: { + name: 'Charlie' + } + }, + response: { + data: { + name: 'Override' + } + } + }]); + + mock.remove([{ + request: { + path: '/users', + method: 'GET', + params: { + name: 'Charlie' + } + }, + response: { + data: { + name: 'Override' + } + } + }]); +} diff --git a/protractor-http-mock/protractor-http-mock.d.ts b/protractor-http-mock/protractor-http-mock.d.ts index b953d8eb22..29d6dfb276 100644 --- a/protractor-http-mock/protractor-http-mock.d.ts +++ b/protractor-http-mock/protractor-http-mock.d.ts @@ -11,16 +11,37 @@ declare namespace mock { * Instantiate mock module. This must be done before the browser connects. * * @param mocks An array of mock modules to load into the application. + * @param plugins An array of Plugin objects. * @param skipDefaults Set true to skip loading of default mocks. */ - (mocks?: Array>, skipDefaults?: boolean): ProtractorHttpMock; + (mocks?: Array>, plugins?: Array, skipDefaults?: boolean): ProtractorHttpMock; + + /** + * Instantiate mock module. This must be done before the browser connects. + * + * @param mocks An array of mock modules to load into the application. + * @param plugins An array of NPM modules as strings. + * @param skipDefaults Set true to skip loading of default mocks. + */ + (mocks?: Array>, plugins?: Array, skipDefaults?: boolean): ProtractorHttpMock; /** * Instantiate mock modules from files. This must be done before the browser connects. * * @param mocks An array of mock module names relative to the rootDirectory configuration. + * @param plugins An array of Plugin objects. + * @param skipDefaults Set true to skip loading of default mocks. */ - (mocks: Array): ProtractorHttpMock; + (mocks: Array, plugins?: Array, skipDefaults?: boolean): ProtractorHttpMock; + + /** + * Instantiate mock modules from files. This must be done before the browser connects. + * + * @param mocks An array of mock module names relative to the rootDirectory configuration. + * @param plugins An array of NPM modules as strings. + * @param skipDefaults Set true to skip loading of default mocks. + */ + (mocks: Array, plugins?: Array, skipDefaults?: boolean): ProtractorHttpMock; /** * Clean up. @@ -59,22 +80,22 @@ declare namespace mock { }; /** - * Add mock dynamically. + * Add mocks during test execution. * Returns a promise that will be resolved with a true boolean - * when mocks have been added. + * when mocks are added. * * @param mocks An array of mock modules to load into the application. */ - add(mocks: Array>): webdriver.promise.Promise; + add(mocks: Array>): webdriver.promise.Promise; /** - * Remove mock dynamically. + * Remove mocks during test execution. * Returns a promise that will be resolved with a true boolean - * when mocks have been removed. + * when the supplied mocks are removed. * * @param mocks An array of mock modules to remove from the application. */ - remove(mocks: Array>): webdriver.promise.Promise; + remove(mocks: Array>): webdriver.promise.Promise; } /** @@ -82,7 +103,35 @@ declare namespace mock { */ interface ReceivedRequest { url: string; - method: string; + method: requests.Method; + } + + /** + * Plugin for custom matching logic. + */ + interface Plugin { + /** + * Match function. + * Return a truthy value to indicate successfull match. + * + * @param mockRequest The mock to compare request with. + * @param requestConfig The request object to compare mock with. + */ + match(mockRequest: requests.AllRequests, requestConfig: requests.AllRequests): boolean; + } + + /** + * Plugin for custom matching logic. + */ + interface Plugin { + /** + * Match function. + * Return a truthy value to indicate successfull match. + * + * @param mockRequest The mock to compare request with. + * @param requestConfig The request object to compare mock with. + */ + match(mockRequest: requests.AllRequests, requestConfig: requests.AllRequests): boolean; } namespace requests { @@ -92,26 +141,25 @@ declare namespace mock { type Method = "GET" | "POST" | "DELETE" | "PUT" | "HEAD" | "PATCH" | "JSONP"; /** - * Base request mock used for all mocks. + * All available request types. */ - interface BaseRequest { - request: { - method: Method; - path: string; - }; - response: { - status: number; - data: TResponse; - }; - } + type AllRequests = Get | + PostData | + Post | + Head | + Delete | + Put | + Patch | + Jsonp; /** * GET request mock. */ - interface Get extends BaseRequest { + interface Get { request: { method: Method; path: string; + regex?: boolean; params?: Object; queryString?: Object; headers?: Object; @@ -119,7 +167,7 @@ declare namespace mock { interceptedAnonymousRequest?: boolean; }; response: { - status: number; + status?: number; data: TResponse; }; } @@ -127,14 +175,15 @@ declare namespace mock { /** * POST request mock with payload. */ - interface PostData extends BaseRequest { + interface PostData { request: { - path: string; method: Method; + path: string; + regex?: boolean; data: TPayload; }; response: { - status: number; + status?: number; data: TResponse; }; } @@ -142,13 +191,14 @@ declare namespace mock { /** * POST request mock. */ - interface Post extends BaseRequest { + interface Post { request: { - path: string; method: Method; + path: string; + regex?: boolean; }; response: { - status: number; + status?: number; data: TResponse; }; } @@ -156,13 +206,14 @@ declare namespace mock { /** * HEAD request mock. */ - interface Head extends BaseRequest { + interface Head { request: { - path: string; method: Method; + path: string; + regex?: boolean; }; response: { - status: number; + status?: number; data: TResponse; }; } @@ -170,13 +221,14 @@ declare namespace mock { /** * HTTP Delete request mock. */ - interface Delete extends BaseRequest { + interface Delete { request: { - path: string; method: Method; + path: string; + regex?: boolean; }; response: { - status: number; + status?: number; data: TResponse; }; } @@ -184,13 +236,14 @@ declare namespace mock { /** * PUT request mock. */ - interface Put extends BaseRequest { + interface Put { request: { - path: string; method: Method; + path: string; + regex?: boolean; }; response: { - status: number; + status?: number; data: TResponse; }; } @@ -198,13 +251,14 @@ declare namespace mock { /** * PATCH request mock. */ - interface Patch extends BaseRequest { + interface Patch { request: { - path: string; method: Method; + path: string; + regex?: boolean; }; response: { - status: number; + status?: number; data: TResponse; }; } @@ -212,13 +266,14 @@ declare namespace mock { /** * JSONP request mock. */ - interface Jsonp extends BaseRequest { + interface Jsonp { request: { - path: string; method: Method; + path: string; + regex?: boolean; }; response: { - status: number; + status?: number; data: TResponse; }; } From 816f03f3e4a97c0f4b5dd12bb1302a1d3b8b9f7c Mon Sep 17 00:00:00 2001 From: Craig Younkins Date: Sat, 21 May 2016 11:42:29 -0400 Subject: [PATCH 104/402] Updated irc definitions to include connect callback as first argument and password config attribute (#9276) --- irc/irc-tests.ts | 108 ++++++++++++++++++++++++++++++----------------- irc/irc.d.ts | 8 +++- 2 files changed, 76 insertions(+), 40 deletions(-) diff --git a/irc/irc-tests.ts b/irc/irc-tests.ts index edda5e14fd..9e098f923c 100644 --- a/irc/irc-tests.ts +++ b/irc/irc-tests.ts @@ -3,52 +3,82 @@ import irc = require('irc'); -var bot = new irc.Client('irc.dollyfish.net.nz', 'nodebot', { - debug: true, - channels: ['#blah', '#test'] -}); +function test_bot() { + var bot = new irc.Client('irc.dollyfish.net.nz', 'nodebot', { + debug: true, + channels: ['#blah', '#test'] + }); -bot.addListener('error', ((message: irc.IMessage) => { - console.error('ERROR: %s: %s', message.command, message.args.join(' ')); -})); + bot.connect(function() { + console.log("Connected"); + }); -bot.addListener('message#blah', ((from: string, message: string) => { - console.log('<%s> %s', from, message); -})); + bot.addListener('error', ((message: irc.IMessage) => { + console.error('ERROR: %s: %s', message.command, message.args.join(' ')); + })); -bot.addListener('message', ((from: string, to: string, message: string) => { - console.log('%s => %s: %s', from, to, message); + bot.addListener('message#blah', ((from: string, message: string) => { + console.log('<%s> %s', from, message); + })); - if (to.match(/^[#&]/)) { - // channel message - if (message.match(/hello/i)) { - bot.say(to, 'Hello there ' + from); + bot.addListener('message', ((from: string, to: string, message: string) => { + console.log('%s => %s: %s', from, to, message); + + if (to.match(/^[#&]/)) { + // channel message + if (message.match(/hello/i)) { + bot.say(to, 'Hello there ' + from); + } + if (message.match(/dance/)) { + setTimeout(() => { bot.say(to, '\u0001ACTION dances: :D\\-<\u0001'); }, 1000); + setTimeout(() => { bot.say(to, '\u0001ACTION dances: :D|-<\u0001'); }, 2000); + setTimeout(() => { bot.say(to, '\u0001ACTION dances: :D/-<\u0001'); }, 3000); + setTimeout(() => { bot.say(to, '\u0001ACTION dances: :D|-<\u0001'); }, 4000); + } } - if (message.match(/dance/)) { - setTimeout(() => { bot.say(to, '\u0001ACTION dances: :D\\-<\u0001'); }, 1000); - setTimeout(() => { bot.say(to, '\u0001ACTION dances: :D|-<\u0001'); }, 2000); - setTimeout(() => { bot.say(to, '\u0001ACTION dances: :D/-<\u0001'); }, 3000); - setTimeout(() => { bot.say(to, '\u0001ACTION dances: :D|-<\u0001'); }, 4000); + else { + // private message + console.log('private message'); } - } - else { - // private message - console.log('private message'); - } -})); + })); -bot.addListener('pm', ((nick: string, message: string) => { - console.log('Got private message from %s: %s', nick, message); -})); + bot.addListener('pm', ((nick: string, message: string) => { + console.log('Got private message from %s: %s', nick, message); + })); -bot.addListener('join', ((channel: string, who: string) => { - console.log('%s has joined %s', who, channel); -})); + bot.addListener('join', ((channel: string, who: string) => { + console.log('%s has joined %s', who, channel); + })); -bot.addListener('part', ((channel: string, who: string, reason: string) => { - console.log('%s has left %s: %s', who, channel, reason); -})); + bot.addListener('part', ((channel: string, who: string, reason: string) => { + console.log('%s has left %s: %s', who, channel, reason); + })); -bot.addListener('kick', ((channel: string, who: string, by: string, reason: string) => { - console.log('%s was kicked from %s by %s: %s', who, channel, by, reason); -})); + bot.addListener('kick', ((channel: string, who: string, by: string, reason: string) => { + console.log('%s was kicked from %s by %s: %s', who, channel, by, reason); + })); +} + +function test_secure() { + var options = true; + + var bot = new irc.Client('chat.us.freenode.net', 'nodebot', { + port: 6697, + debug: true, + secure: options, + channels: ['#botwar'] + }); +} + +function test_connect() { + var bot = new irc.Client('chat.us.freenode.net', 'nodebot', { + port: 6697, + autoConnect: false + }); + + bot.connect(5); + + bot.connect(5, function() {}); + + bot.connect(function() {}); +} diff --git a/irc/irc.d.ts b/irc/irc.d.ts index 00dd3220e1..546ca7c3c0 100644 --- a/irc/irc.d.ts +++ b/irc/irc.d.ts @@ -194,7 +194,7 @@ declare module 'irc' { * @param callback */ public connect( - retryCount?: number, + retryCount?: number | handlers.IRaw, callback?: handlers.IRaw ): void; @@ -228,6 +228,12 @@ declare module 'irc' { */ userName?: string; + /** + * IRC username + * @default '' + */ + password?: string; + /** * IRC "real name" * @default 'nodeJS IRC client' From d55165c9814f35857ddd8b3083a01a47322174e7 Mon Sep 17 00:00:00 2001 From: Sam Vervaeck Date: Mon, 23 May 2016 05:14:22 +0200 Subject: [PATCH 105/402] Allow paths to be buffers in fs of node v6.x (#9359) * Allow buffers to be passed in fs for node v6.x * Fix wrongly typed index in fs.realpath Fixes the following errors: - node.d.ts(1426,62): error TS1023: An index signature parameter type must be 'string' or 'number'. - node.d.ts(1427,68): error TS1023: An index signature parameter type must be 'string' or 'number'. --- node/node.d.ts | 110 ++++++++++++++++++++++++------------------------- 1 file changed, 55 insertions(+), 55 deletions(-) diff --git a/node/node.d.ts b/node/node.d.ts index d34bd65b1d..4800997ea9 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -1386,78 +1386,78 @@ declare module "fs" { * @param newPath */ export function renameSync(oldPath: string, newPath: string): void; - export function truncate(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function truncate(path: string, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function truncateSync(path: string, len?: number): void; + export function truncate(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function truncate(path: string | Buffer, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function truncateSync(path: string | Buffer, len?: number): void; export function ftruncate(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; export function ftruncate(fd: number, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; export function ftruncateSync(fd: number, len?: number): void; - export function chown(path: string, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function chownSync(path: string, uid: number, gid: number): void; + export function chown(path: string | Buffer, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function chownSync(path: string | Buffer, uid: number, gid: number): void; export function fchown(fd: number, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; export function fchownSync(fd: number, uid: number, gid: number): void; - export function lchown(path: string, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function lchownSync(path: string, uid: number, gid: number): void; - export function chmod(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function chmod(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function chmodSync(path: string, mode: number): void; - export function chmodSync(path: string, mode: string): void; + export function lchown(path: string | Buffer, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function lchownSync(path: string | Buffer, uid: number, gid: number): void; + export function chmod(path: string | Buffer, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function chmod(path: string | Buffer, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function chmodSync(path: string | Buffer, mode: number): void; + export function chmodSync(path: string | Buffer, mode: string): void; export function fchmod(fd: number, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; export function fchmod(fd: number, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; export function fchmodSync(fd: number, mode: number): void; export function fchmodSync(fd: number, mode: string): void; - export function lchmod(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function lchmod(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function lchmodSync(path: string, mode: number): void; - export function lchmodSync(path: string, mode: string): void; - export function stat(path: string, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; - export function lstat(path: string, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; + export function lchmod(path: string | Buffer, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function lchmod(path: string | Buffer, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function lchmodSync(path: string | Buffer, mode: number): void; + export function lchmodSync(path: string | Buffer, mode: string): void; + export function stat(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; + export function lstat(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; export function fstat(fd: number, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; - export function statSync(path: string): Stats; - export function lstatSync(path: string): Stats; + export function statSync(path: string | Buffer): Stats; + export function lstatSync(path: string | Buffer): Stats; export function fstatSync(fd: number): Stats; - export function link(srcpath: string, dstpath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function linkSync(srcpath: string, dstpath: string): void; - export function symlink(srcpath: string, dstpath: string, type?: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function symlinkSync(srcpath: string, dstpath: string, type?: string): void; - export function readlink(path: string, callback?: (err: NodeJS.ErrnoException, linkString: string) => any): void; - export function readlinkSync(path: string): string; - export function realpath(path: string, callback?: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; - export function realpath(path: string, cache: {[path: string]: string}, callback: (err: NodeJS.ErrnoException, resolvedPath: string) =>any): void; - export function realpathSync(path: string, cache?: { [path: string]: string }): string; + export function link(srcpath: string | Buffer, dstpath: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function linkSync(srcpath: string | Buffer, dstpath: string | Buffer): void; + export function symlink(srcpath: string | Buffer, dstpath: string | Buffer, type?: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function symlinkSync(srcpath: string | Buffer, dstpath: string | Buffer, type?: string): void; + export function readlink(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, linkString: string) => any): void; + export function readlinkSync(path: string | Buffer): string; + export function realpath(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; + export function realpath(path: string | Buffer, cache: {[path: string]: string}, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; + export function realpathSync(path: string | Buffer, cache?: { [path: string]: string }): string; /* * Asynchronous unlink - deletes the file specified in {path} * * @param path * @param callback No arguments other than a possible exception are given to the completion callback. */ - export function unlink(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function unlink(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; /* * Synchronous unlink - deletes the file specified in {path} * * @param path */ - export function unlinkSync(path: string): void; + export function unlinkSync(path: string | Buffer): void; /* * Asynchronous rmdir - removes the directory specified in {path} * * @param path * @param callback No arguments other than a possible exception are given to the completion callback. */ - export function rmdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function rmdir(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; /* * Synchronous rmdir - removes the directory specified in {path} * * @param path */ - export function rmdirSync(path: string): void; + export function rmdirSync(path: string | Buffer): void; /* * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * * @param path * @param callback No arguments other than a possible exception are given to the completion callback. */ - export function mkdir(path: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function mkdir(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; /* * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * @@ -1465,7 +1465,7 @@ declare module "fs" { * @param mode * @param callback No arguments other than a possible exception are given to the completion callback. */ - export function mkdir(path: string, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function mkdir(path: string | Buffer, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; /* * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * @@ -1473,7 +1473,7 @@ declare module "fs" { * @param mode * @param callback No arguments other than a possible exception are given to the completion callback. */ - export function mkdir(path: string, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function mkdir(path: string | Buffer, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; /* * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * @@ -1481,7 +1481,7 @@ declare module "fs" { * @param mode * @param callback No arguments other than a possible exception are given to the completion callback. */ - export function mkdirSync(path: string, mode?: number): void; + export function mkdirSync(path: string | Buffer, mode?: number): void; /* * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. * @@ -1489,7 +1489,7 @@ declare module "fs" { * @param mode * @param callback No arguments other than a possible exception are given to the completion callback. */ - export function mkdirSync(path: string, mode?: string): void; + export function mkdirSync(path: string | Buffer, mode?: string): void; /* * Asynchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory. * @@ -1504,19 +1504,19 @@ declare module "fs" { * @returns Returns the created folder path. */ export function mkdtempSync(prefix: string): string; - export function readdir(path: string, callback?: (err: NodeJS.ErrnoException, files: string[]) => void): void; - export function readdirSync(path: string): string[]; + export function readdir(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, files: string[]) => void): void; + export function readdirSync(path: string | Buffer): string[]; export function close(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; export function closeSync(fd: number): void; - export function open(path: string, flags: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; - export function open(path: string, flags: string, mode: number, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; - export function open(path: string, flags: string, mode: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; - export function openSync(path: string, flags: string, mode?: number): number; - export function openSync(path: string, flags: string, mode?: string): number; - export function utimes(path: string, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function utimes(path: string, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function utimesSync(path: string, atime: number, mtime: number): void; - export function utimesSync(path: string, atime: Date, mtime: Date): void; + export function open(path: string | Buffer, flags: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; + export function open(path: string | Buffer, flags: string, mode: number, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; + export function open(path: string | Buffer, flags: string, mode: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void; + export function openSync(path: string | Buffer, flags: string, mode?: number): number; + export function openSync(path: string | Buffer, flags: string, mode?: string): number; + export function utimes(path: string | Buffer, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function utimes(path: string | Buffer, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function utimesSync(path: string | Buffer, atime: number, mtime: number): void; + export function utimesSync(path: string | Buffer, atime: Date, mtime: Date): void; export function futimes(fd: number, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; export function futimes(fd: number, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; export function futimesSync(fd: number, atime: number, mtime: number): void; @@ -1599,8 +1599,8 @@ declare module "fs" { export function unwatchFile(filename: string, listener?: (curr: Stats, prev: Stats) => void): void; export function watch(filename: string, listener?: (event: string, filename: string) => any): FSWatcher; export function watch(filename: string, options: { persistent?: boolean; }, listener?: (event: string, filename: string) => any): FSWatcher; - export function exists(path: string, callback?: (exists: boolean) => void): void; - export function existsSync(path: string): boolean; + export function exists(path: string | Buffer, callback?: (exists: boolean) => void): void; + export function existsSync(path: string | Buffer): boolean; /** Constant for fs.access(). File is visible to the calling process. */ export var F_OK: number; /** Constant for fs.access(). File can be read by the calling process. */ @@ -1610,18 +1610,18 @@ declare module "fs" { /** Constant for fs.access(). File can be executed by the calling process. */ export var X_OK: number; /** Tests a user's permissions for the file specified by path. */ - export function access(path: string, callback: (err: NodeJS.ErrnoException) => void): void; - export function access(path: string, mode: number, callback: (err: NodeJS.ErrnoException) => void): void; + export function access(path: string | Buffer, callback: (err: NodeJS.ErrnoException) => void): void; + export function access(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException) => void): void; /** Synchronous version of fs.access. This throws if any accessibility checks fail, and does nothing otherwise. */ - export function accessSync(path: string, mode ?: number): void; - export function createReadStream(path: string, options?: { + export function accessSync(path: string | Buffer, mode ?: number): void; + export function createReadStream(path: string | Buffer, options?: { flags?: string; encoding?: string; fd?: number; mode?: number; autoClose?: boolean; }): ReadStream; - export function createWriteStream(path: string, options?: { + export function createWriteStream(path: string | Buffer, options?: { flags?: string; encoding?: string; fd?: number; From b6b74cabd71164211e82d814d79a5527e0b92d8c Mon Sep 17 00:00:00 2001 From: Hiroyuki Wada Date: Mon, 23 May 2016 12:50:05 +0900 Subject: [PATCH 106/402] Add redirect option to whatwg-fetch (#9366) --- whatwg-fetch/whatwg-fetch-tests.ts | 3 ++- whatwg-fetch/whatwg-fetch.d.ts | 5 ++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/whatwg-fetch/whatwg-fetch-tests.ts b/whatwg-fetch/whatwg-fetch-tests.ts index 32e5b73a6d..8dbbd2964b 100644 --- a/whatwg-fetch/whatwg-fetch-tests.ts +++ b/whatwg-fetch/whatwg-fetch-tests.ts @@ -8,7 +8,8 @@ function test_fetchUrlWithOptions() { headers: headers, mode: 'same-origin', credentials: 'omit', - cache: 'default' + cache: 'default', + redirect: 'manual' }; handlePromise(window.fetch("http://www.andlabs.net/html5/uCOR.php", requestOptions)); } diff --git a/whatwg-fetch/whatwg-fetch.d.ts b/whatwg-fetch/whatwg-fetch.d.ts index 32e681bb9b..b1e667650f 100644 --- a/whatwg-fetch/whatwg-fetch.d.ts +++ b/whatwg-fetch/whatwg-fetch.d.ts @@ -11,6 +11,7 @@ declare class Request extends Body { context: RequestContext; referrer: string; mode: RequestMode; + redirect: RequestRedirect; credentials: RequestCredentials; cache: RequestCache; } @@ -20,6 +21,7 @@ interface RequestInit { headers?: HeaderInit|{ [index: string]: string }; body?: BodyInit; mode?: RequestMode; + redirect?: RequestRedirect; credentials?: RequestCredentials; cache?: RequestCache; } @@ -33,6 +35,7 @@ type RequestContext = "subresource" | "style" | "track" | "video" | "worker" | "xmlhttprequest" | "xslt"; type RequestMode = "same-origin" | "no-cors" | "cors"; +type RequestRedirect = "follow" | "error" | "manual"; type RequestCredentials = "omit" | "same-origin" | "include"; type RequestCache = "default" | "no-store" | "reload" | "no-cache" | @@ -70,7 +73,7 @@ declare class Response extends Body { clone(): Response; } -type ResponseType = "basic" | "cors" | "default" | "error" | "opaque"; +type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect"; interface ResponseInit { status: number; From 0710f0ad23b25148d5ad4bf60414c9121b49ed4c Mon Sep 17 00:00:00 2001 From: Milan Burda Date: Sun, 22 May 2016 20:54:12 -0700 Subject: [PATCH 107/402] Update to Electron 1.0.2 (#9371) --- github-electron/github-electron.d.ts | 189 ++++++++++++++++++++++++++- 1 file changed, 184 insertions(+), 5 deletions(-) diff --git a/github-electron/github-electron.d.ts b/github-electron/github-electron.d.ts index 11223154fb..235e7d55fb 100644 --- a/github-electron/github-electron.d.ts +++ b/github-electron/github-electron.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Electron v0.37.8 +// Type definitions for Electron v1.0.2 // Project: http://electron.atom.io/ // Definitions by: jedmao , rhysd , Milan Burda // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -96,6 +96,11 @@ declare namespace Electron { * Note: This is only implemented on OS X. */ on(event: 'activate', listener: Function): this; + /** + * Emitted during Handoff when an activity from a different device wants to be resumed. + * You should call event.preventDefault() if you want to handle this event. + */ + on(event: 'continue-activity', listener: (event: Event, type: string, userInfo: Object) => void): this; /** * Emitted when a browserWindow gets blurred. */ @@ -251,8 +256,7 @@ declare namespace Electron { /** * Removes the current executable as the default handler for a protocol (aka URI scheme). * - * Note: This is only implemented on Windows. - * On OS X, removing the app will automatically remove the app as the default protocol handler. + * Note: This is only implemented on OS X and Windows. */ removeAsDefaultProtocolClient(protocol: string): void; /** @@ -281,6 +285,22 @@ declare namespace Electron { * of your app is running, and other instances signal this instance and exit. */ makeSingleInstance(callback: (args: string[], workingDirectory: string) => void): boolean; + /** + * Creates an NSUserActivity and sets it as the current activity. + * The activity is eligible for Handoff to another device afterward. + * + * @param type Uniquely identifies the activity. Maps to NSUserActivity.activityType. + * @param userInfo App-specific state to store for use by another device. + * + * Note: This API is only available on Mac. + */ + setUserActivity(type: string, userInfo: Object): void; + /** + * @returns The type of the currently running activity. + * + * Note: This API is only available on Mac. + */ + getCurrentActivityType(): string; /** * Changes the Application User Model ID to id. */ @@ -348,6 +368,12 @@ declare namespace Electron { * Note: This API is only available on Mac. */ cancelBounce(id: number): void; + /** + * Bounces the Downloads stack if the filePath is inside the Downloads folder. + * + * Note: This API is only available on Mac. + */ + downloadFinished(filePath: string): void; /** * Sets the string to be displayed in the dock’s badging area. * @@ -1103,6 +1129,11 @@ declare namespace Electron { * Default: true. */ directWrite?: boolean; + /** + * Enables scroll bounce (rubber banding) effect on OS X. + * Default: false. + */ + scrollBounce?: boolean; /** * A list of feature strings separated by ",". */ @@ -1239,7 +1270,7 @@ declare namespace Electron { alwaysOnTop?: boolean; /** * Whether the window should show in fullscreen. - * When explicity set to false the fullscreen button will be hidden or disabled on OS X. + * When explicitly set to false the fullscreen button will be hidden or disabled on OS X. * Default: false. */ fullscreen?: boolean; @@ -1722,7 +1753,7 @@ declare namespace Electron { */ type?: 'none' | 'info' | 'error' | 'question' | 'warning'; /** - * Texts for buttons. + * Texts for buttons. On Windows, an empty array will result in one button labeled "OK". */ buttons?: string[]; /** @@ -2023,6 +2054,7 @@ declare namespace Electron { * Punctuations like ~, !, @, #, $, etc. * Plus * Space + * Tab * Backspace * Delete * Insert @@ -3284,6 +3316,10 @@ declare namespace Electron { * in a NativeImage, and the scale will hold scaling information for the image. */ on(event: 'cursor-changed', listener: (event: Event, type: CursorType, image?: NativeImage, scale?: number) => void): this; + /** + * Emitted when there is a new context menu that needs to be handled. + */ + on(event: 'context-menu', listener: (event: Event, params: ContextMenuParams) => void): this; on(event: string, listener: Function): this; /** * Loads the url in the window. @@ -3574,6 +3610,144 @@ declare namespace Electron { debugger: Debugger; } + interface ContextMenuParams { + /** + * x coodinate + */ + x: number; + /** + * y coodinate + */ + y: number; + /** + * URL of the link that encloses the node the context menu was invoked on. + */ + linkURL: string; + /** + * Text associated with the link. May be an empty string if the contents of the link are an image. + */ + linkText: string; + /** + * URL of the top level page that the context menu was invoked on. + */ + pageURL: string; + /** + * URL of the subframe that the context menu was invoked on. + */ + frameURL: string; + /** + * Source URL for the element that the context menu was invoked on. + * Elements with source URLs are images, audio and video. + */ + srcURL: string; + /** + * Type of the node the context menu was invoked on. + */ + mediaType: 'none' | 'image' | 'audio' | 'video' | 'canvas' | 'file' | 'plugin'; + /** + * Parameters for the media element the context menu was invoked on. + */ + mediaFlags: { + /** + * Wether the media element has crashed. + */ + inError: boolean; + /** + * Wether the media element is paused. + */ + isPaused: boolean; + /** + * Wether the media element is muted. + */ + isMuted: boolean; + /** + * Wether the media element has audio. + */ + hasAudio: boolean; + /** + * Wether the media element is looping. + */ + isLooping: boolean; + /** + * Wether the media element's controls are visible. + */ + isControlsVisible: boolean; + /** + * Wether the media element's controls are toggleable. + */ + canToggleControls: boolean; + /** + * Wether the media element can be rotated. + */ + canRotate: boolean; + } + /** + * Wether the context menu was invoked on an image which has non-empty contents. + */ + hasImageContents: boolean; + /** + * Wether the context is editable. + */ + isEditable: boolean; + /** + * These flags indicate wether the renderer believes it is able to perform the corresponding action. + */ + editFlags: { + /** + * Wether the renderer believes it can undo. + */ + canUndo: boolean; + /** + * Wether the renderer believes it can redo. + */ + canRedo: boolean; + /** + * Wether the renderer believes it can cut. + */ + canCut: boolean; + /** + * Wether the renderer believes it can copy + */ + canCopy: boolean; + /** + * Wether the renderer believes it can paste. + */ + canPaste: boolean; + /** + * Wether the renderer believes it can delete. + */ + canDelete: boolean; + /** + * Wether the renderer believes it can select all. + */ + canSelectAll: boolean; + } + /** + * Text of the selection that the context menu was invoked on. + */ + selectionText: string; + /** + * Title or alt text of the selection that the context was invoked on. + */ + titleText: string; + /** + * The misspelled word under the cursor, if any. + */ + misspelledWord: string; + /** + * The character encoding of the frame on which the menu was invoked. + */ + frameCharset: string; + /** + * If the context menu was invoked on an input field, the type of that field. + */ + inputFieldType: 'none' | 'plainText' | 'password' | 'other'; + /** + * Input source that invoked the context menu. + */ + menuSourceType: 'none' | 'mouse' | 'keyboard' | 'touch' | 'touchMenu'; + } + interface Headers { [key: string]: string; } @@ -4511,6 +4685,11 @@ declare namespace NodeJS { * If the app is running as a Windows Store app (appx), this value is true, for other builds it is undefined. */ windowsStore?: boolean; + /** + * When app is started by being passed as parameter to the default app, + * this value is true in the main process, otherwise it is undefined. + */ + defaultApp?: boolean; /** * Emitted when Electron has loaded its internal initialization script * and is beginning to load the web page or the main script. From da28561597153ac0605305fe85b39cc8288b40c7 Mon Sep 17 00:00:00 2001 From: Evan Sebastian Date: Mon, 23 May 2016 10:55:35 +0700 Subject: [PATCH 108/402] webpack: Add OccurrenceOrderPlugin as Webpack optimizer (#9365) * Add OccurrenceOrderPlugin * Add deprectation notice --- webpack/webpack-tests.ts | 1 + webpack/webpack.d.ts | 2 ++ 2 files changed, 3 insertions(+) diff --git a/webpack/webpack-tests.ts b/webpack/webpack-tests.ts index 9f2efe15c4..5af5d9be79 100644 --- a/webpack/webpack-tests.ts +++ b/webpack/webpack-tests.ts @@ -333,6 +333,7 @@ plugin = new webpack.optimize.DedupePlugin(); plugin = new webpack.optimize.LimitChunkCountPlugin(options); plugin = new webpack.optimize.MinChunkSizePlugin(options); plugin = new webpack.optimize.OccurenceOrderPlugin(preferEntry); +plugin = new webpack.optimize.OccurrenceOrderPlugin(preferEntry); plugin = new webpack.optimize.UglifyJsPlugin(options); plugin = new webpack.optimize.UglifyJsPlugin(); plugin = new webpack.optimize.UglifyJsPlugin({ diff --git a/webpack/webpack.d.ts b/webpack/webpack.d.ts index 035b49b014..e2ed2d1658 100644 --- a/webpack/webpack.d.ts +++ b/webpack/webpack.d.ts @@ -327,7 +327,9 @@ declare module "webpack" { * Assign the module and chunk ids by occurrence count. Ids that are used often get lower (shorter) ids. * This make ids predictable, reduces to total file size and is recommended. */ + // TODO: This is a typo, and will be removed in Webpack 2. OccurenceOrderPlugin: optimize.OccurenceOrderPluginStatic; + OccurrenceOrderPlugin: optimize.OccurenceOrderPluginStatic; /** * Minimize all JavaScript output of chunks. Loaders are switched into minimizing mode. * You can pass an object containing UglifyJs options. From d8b8632c611c9c307431d169f425d08bdb8b6a2f Mon Sep 17 00:00:00 2001 From: hookclaw Date: Mon, 23 May 2016 12:57:54 +0900 Subject: [PATCH 109/402] Add property "connected" (#9391) --- node/node.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/node/node.d.ts b/node/node.d.ts index 4800997ea9..8c30f25809 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -1021,6 +1021,7 @@ declare module "child_process" { pid: number; kill(signal?: string): void; send(message: any, sendHandle?: any): void; + connected: boolean; disconnect(): void; unref(): void; } From 80843c4d7ed6ca035a71a77d9e7e2f7d63d4ff9f Mon Sep 17 00:00:00 2001 From: hookclaw Date: Mon, 23 May 2016 13:00:18 +0900 Subject: [PATCH 110/402] Add "argv.d.ts" (#9392) --- argv/argv-tests.ts | 15 ++++++++++++ argv/argv.d.ts | 59 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 argv/argv-tests.ts create mode 100644 argv/argv.d.ts diff --git a/argv/argv-tests.ts b/argv/argv-tests.ts new file mode 100644 index 0000000000..6d73c53ec7 --- /dev/null +++ b/argv/argv-tests.ts @@ -0,0 +1,15 @@ +/// +import argv = require('argv'); +argv.version( 'v1.0' ); +argv.info( 'Special script info' ); +argv.clear() +.option({ + name: 'option', + short: 'o', + type: 'string', + description: 'Defines an option for your script', + example: "'script --opiton=value' or 'script -o value'" +}) +.run([ '--option=123', '-o', '123' ]); +argv.run(); +argv.help(); diff --git a/argv/argv.d.ts b/argv/argv.d.ts new file mode 100644 index 0000000000..182ffde861 --- /dev/null +++ b/argv/argv.d.ts @@ -0,0 +1,59 @@ +// Type definitions for argv +// Project: https://www.npmjs.com/package/argv +// Definitions by: Hookclaw +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare module "argv" { + // argv module + type args = { + targets:string[], + options:{[key:string]:any} + }; + + type helpOption = { + name: string, + type: string, + short?: string, + description?: string, + example?: string + }; + + type module = { + mod: string, + description: string, + options: {[key:string]:helpOption} + }; + + type typeFunction = (value:any, ...arglist:any[]) => any; + + type argv = { + + // Runs the arguments parser + run: ( argv?:string[] ) => args, + + // Adding options to definitions list + option: ( mod:helpOption|helpOption[] ) => argv, + + // Creating module + mod: ( object:module|module[] ) => argv, + + // Creates custom type function + type: ( name:string|{[key:string]:typeFunction}, callback?:typeFunction ) => any, + + // Setting version number, and auto setting version option + version: ( v:string ) => argv, + + // Description setup + info: ( mod:string, description?:module ) => argv, + + // Cleans out current options + clear: () => argv, + + // Prints out the help doc + help: ( mod?:string ) => argv + + }; + + var argv:argv; + + export = argv; +} From 4d47ff605fb6fce8afe46deb055992d06ca1240c Mon Sep 17 00:00:00 2001 From: Ryan Date: Sun, 22 May 2016 21:08:21 -0700 Subject: [PATCH 111/402] Adding arrows function to render function of dagre-d3 (#9398) --- dagre-d3/dagre-d3-tests.ts | 1 + dagre-d3/dagre-d3.d.ts | 3 +++ 2 files changed, 4 insertions(+) diff --git a/dagre-d3/dagre-d3-tests.ts b/dagre-d3/dagre-d3-tests.ts index 2ba8675436..ef5fddffac 100644 --- a/dagre-d3/dagre-d3-tests.ts +++ b/dagre-d3/dagre-d3-tests.ts @@ -14,5 +14,6 @@ namespace DagreD3Tests { const render = new dagreD3.render(); const svg = d3.select("svg"); + render.arrows()["arrowType"] = (parent: JQuery, id: string, edge: Dagre.Edge, type: string) => {}; render(svg, graph); } diff --git a/dagre-d3/dagre-d3.d.ts b/dagre-d3/dagre-d3.d.ts index 0bc71294c8..68e24c2fa5 100644 --- a/dagre-d3/dagre-d3.d.ts +++ b/dagre-d3/dagre-d3.d.ts @@ -5,6 +5,7 @@ /// /// +/// declare namespace Dagre { @@ -23,6 +24,8 @@ declare namespace Dagre { } interface Render { + // see http://cpettitt.github.io/project/dagre-d3/latest/demo/user-defined.html for example usage + arrows (): { [arrowStyleName: string]: (parent: JQuery, id: string, edge: Dagre.Edge, type: string) => void }; new (): Render; (selection: d3.Selection, g: Dagre.Graph): void; } From 21355aa58d3de0a04aacf8c3ede9c4ac4d95f140 Mon Sep 17 00:00:00 2001 From: Timofey Kachalov Date: Mon, 23 May 2016 07:09:47 +0300 Subject: [PATCH 112/402] estraverse d.ts (#9401) --- estraverse/estraverse-tests.ts | 59 ++++++++++++++++++++++++++++++++++ estraverse/estraverse.d.ts | 22 +++++++++++++ 2 files changed, 81 insertions(+) create mode 100644 estraverse/estraverse-tests.ts create mode 100644 estraverse/estraverse.d.ts diff --git a/estraverse/estraverse-tests.ts b/estraverse/estraverse-tests.ts new file mode 100644 index 0000000000..0650aa99e2 --- /dev/null +++ b/estraverse/estraverse-tests.ts @@ -0,0 +1,59 @@ +/// + +import * as estraverse from 'estraverse'; + +let ast: any = { + "type": "Program", + "body": [ + { + "type": "VariableDeclaration", + "declarations": [ + { + "type": "VariableDeclarator", + "id": { + "type": "Identifier", + "name": "answer" + }, + "init": { + "type": "BinaryExpression", + "operator": "*", + "left": { + "type": "Literal", + "value": 6, + "raw": "6" + }, + "right": { + "type": "Literal", + "value": 7, + "raw": "7" + } + } + } + ], + "kind": "var" + } + ], + "sourceType": "script" +}; + +estraverse.traverse(ast, { + enter: (node: any, parentNode: any) => { + if (node.type === 'Identifier') { + return estraverse.VisitorOption.Skip; + } + }, + leave: (node: any, parentNode: any) => {}, + fallback: 'iteration', + keys: { + TestExpression: ['argument'] + } +}); + +estraverse.replace(ast, { + enter: (node: any, parentNode: any) => { + return node; + }, + leave: (node: any, parentNode: any) => { + return node; + } +}); \ No newline at end of file diff --git a/estraverse/estraverse.d.ts b/estraverse/estraverse.d.ts new file mode 100644 index 0000000000..69b4d5d311 --- /dev/null +++ b/estraverse/estraverse.d.ts @@ -0,0 +1,22 @@ +// Type definitions for estraverse +// Project: https://github.com/estools/estraverse +// Definitions by: Sanex3339 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'estraverse' { + export interface Visitor { + enter?: (node: any, parentNode: any) => any; + leave?: (node: any, parentNode: any) => any; + + fallback?: string; + + keys?: {}; + } + + export enum VisitorOption { + Skip, Break, Remove + } + + export function traverse (ast: any, visitor: Visitor): any; + export function replace (ast: any, visitor: Visitor): any; +} \ No newline at end of file From e39e0817d02816f13be28f4a8c06335d7f6a6fe5 Mon Sep 17 00:00:00 2001 From: rubyboy Date: Mon, 23 May 2016 07:10:26 +0300 Subject: [PATCH 113/402] Updated atmosphere.js to have a default exported module. (#9355) --- atmosphere/atmosphere.d.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/atmosphere/atmosphere.d.ts b/atmosphere/atmosphere.d.ts index bf26ba0db4..239986b3a1 100644 --- a/atmosphere/atmosphere.d.ts +++ b/atmosphere/atmosphere.d.ts @@ -102,5 +102,6 @@ declare namespace Atmosphere { } declare var atmosphere:Atmosphere.Atmosphere; - - +declare module 'atmosphere' { + export = atmosphere; +} From c709db2e04240021432705634896bc3328dd573b Mon Sep 17 00:00:00 2001 From: Rajab Shakirov Date: Mon, 23 May 2016 07:11:52 +0300 Subject: [PATCH 114/402] update visibleTimeStart, visibleTimeEnd properties (#9405) * update visibleTimeStart, visibleTimeEnd properties * update to actual version number --- react-calendar-timeline/react-calendar-timeline.d.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/react-calendar-timeline/react-calendar-timeline.d.ts b/react-calendar-timeline/react-calendar-timeline.d.ts index 2309fcc3b2..f377d29610 100644 --- a/react-calendar-timeline/react-calendar-timeline.d.ts +++ b/react-calendar-timeline/react-calendar-timeline.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-calendar-timeline v0.7.9 +// Type definitions for react-calendar-timeline v0.8.1 // Project: https://github.com/namespace-ee/react-calendar-timeline // Definitions by: Rajab Shakirov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -9,7 +9,7 @@ declare module "react-calendar-timeline" { interface ReactCalendarTimeline { groups: { id: number; - title: string; + title: any; // string | Element (__React.ClassicComponentClass); }[]; items:{ id: number; @@ -58,8 +58,8 @@ declare module "react-calendar-timeline" { moveResizeValidator?(action:any, itemId:any, time:any): any; defaultTimeStart?: any; defaultTimeEnd?: any; - visibleTimeStart?: any; - visibleTimeEnd?: any; + visibleTimeStart?: number; + visibleTimeEnd?: number; onTimeChange?(visibleTimeStart:any, visibleTimeEnd:any): any; onTimeInit?(visibleTimeStart:any, visibleTimeEnd:any): any; onBoundsChange?(canvasTimeStart:any, canvasTimeEnd:any): any; @@ -67,4 +67,4 @@ declare module "react-calendar-timeline" { } let ReactCalendarTimeline : __React.ClassicComponentClass; export default ReactCalendarTimeline; -} \ No newline at end of file +} From e69daec7f79c0c25c4653f866e5cadb5bb7a01ca Mon Sep 17 00:00:00 2001 From: Denis Shelomovskij Date: Mon, 23 May 2016 07:13:17 +0300 Subject: [PATCH 115/402] Fix `LoaderHandler.add` signature. (#9410) Also specify `LoaderHandler.handlers` element type. --- threejs/three.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/threejs/three.d.ts b/threejs/three.d.ts index 144302d423..ce1825c3e8 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -1928,9 +1928,9 @@ declare namespace THREE { } export interface LoaderHandler{ - handlers: any[]; + handlers: (RegExp | Loader)[]; - add(regex: string, loader: Loader): void; + add(regex: RegExp, loader: Loader): void; get(file: string): Loader; } From 9081e075b730c9948b643a6c38d6deb18cb0ebdd Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Mon, 23 May 2016 17:25:06 -0700 Subject: [PATCH 116/402] Fix extend erro for `NodeBuffer` With change https://github.com/Microsoft/TypeScript/pull/8515, `Uint8Array.fill` method now returns `this`. Fixing definition of `NodeBuffer` to maintain extends relationship with `Uint8Array` --- node/node-4.d.ts | 2 +- node/node.d.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/node/node-4.d.ts b/node/node-4.d.ts index a9d4709a91..0cd3c54a17 100644 --- a/node/node-4.d.ts +++ b/node/node-4.d.ts @@ -465,7 +465,7 @@ interface NodeBuffer extends Uint8Array { writeFloatBE(value: number, offset: number, noAssert?: boolean): number; writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; - fill(value: any, offset?: number, end?: number): Buffer; + fill(value: any, offset?: number, end?: number): this; // TODO: encoding param indexOf(value: string | number | Buffer, byteOffset?: number): number; // TODO: entries diff --git a/node/node.d.ts b/node/node.d.ts index 8c30f25809..42621d50c4 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -465,7 +465,7 @@ interface NodeBuffer extends Uint8Array { writeFloatBE(value: number, offset: number, noAssert?: boolean): number; writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; - fill(value: any, offset?: number, end?: number): Buffer; + fill(value: any, offset?: number, end?: number): this; // TODO: encoding param indexOf(value: string | number | Buffer, byteOffset?: number): number; // TODO: entries From 94b221dd73f1ed85741ac114bbbea9f36c16a59a Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Mon, 23 May 2016 17:27:55 -0700 Subject: [PATCH 117/402] Remove unreachable code --- node/node-0.11-tests.ts | 3 ++- node/node-0.12-tests.ts | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/node/node-0.11-tests.ts b/node/node-0.11-tests.ts index 8609639a8c..66c0c9ec7c 100644 --- a/node/node-0.11-tests.ts +++ b/node/node-0.11-tests.ts @@ -24,7 +24,8 @@ assert.notStrictEqual(2, "2", "uses === comparator"); assert.throws(() => { throw "a hammer at your face"; }, undefined, "DODGED IT"); assert.doesNotThrow(() => { - if (false) { throw "a hammer at your face"; } + const b = false; + if (b) { throw "a hammer at your face"; } }, undefined, "What the...*crunch*"); //////////////////////////////////////////////////// diff --git a/node/node-0.12-tests.ts b/node/node-0.12-tests.ts index 2560181896..989b69dab0 100644 --- a/node/node-0.12-tests.ts +++ b/node/node-0.12-tests.ts @@ -26,7 +26,8 @@ assert.notStrictEqual(2, "2", "uses === comparator"); assert.throws(() => { throw "a hammer at your face"; }, undefined, "DODGED IT"); assert.doesNotThrow(() => { - if (false) { throw "a hammer at your face"; } + const b = false; + if (b) { throw "a hammer at your face"; } }, undefined, "What the...*crunch*"); //////////////////////////////////////////////////// From 9fb3c230e09653f0038cf5a600f9b273f2bf17b7 Mon Sep 17 00:00:00 2001 From: Tanguy Krotoff Date: Tue, 24 May 2016 15:48:47 +0200 Subject: [PATCH 118/402] Add core.version (#9383) See https://github.com/zloirock/core-js/blob/v2.4.0/modules/_core.js#L1 See https://github.com/zloirock/core-js/blob/v2.4.0/library/modules/_core.js#L1 --- core-js/core-js-tests.ts | 2 ++ core-js/core-js.d.ts | 2 ++ 2 files changed, 4 insertions(+) diff --git a/core-js/core-js-tests.ts b/core-js/core-js-tests.ts index bc690d434c..965acc6855 100644 --- a/core-js/core-js-tests.ts +++ b/core-js/core-js-tests.ts @@ -500,3 +500,5 @@ s = s.unescapeHTML(); // ############################################################################################# promiseOfVoid = delay(i); + +console.log('core-js version number:', core.version); diff --git a/core-js/core-js.d.ts b/core-js/core-js.d.ts index 16441df233..2c1fa4bd99 100644 --- a/core-js/core-js.d.ts +++ b/core-js/core-js.d.ts @@ -1266,6 +1266,8 @@ interface String { declare function delay(msec: number): Promise; declare namespace core { + var version: string; + namespace Reflect { function apply(target: Function, thisArgument: any, argumentsList: ArrayLike): any; function construct(target: Function, argumentsList: ArrayLike): any; From 8a851abfad7b2dafbf53ec1ee31d1adb899164ea Mon Sep 17 00:00:00 2001 From: Pei-Tang Huang Date: Tue, 24 May 2016 21:50:36 +0800 Subject: [PATCH 119/402] Html2canvas 0.5 (#9293) * Merge function with optional argument. * Align function to 0.5.0 (by replacing callback by Promise.) * Declare module for easier import. * Format. * Update version and author information. * Use ES6 Promise directly. Since DefinitelyTyped recommend compilation with `--target es6` and `--noImplicitAny` options. * Revert "Use ES6 Promise directly." Projects targeting es5 wouldn't compile due to the leak of ES6 Promise. This reverts commit 7d022d153c0601384d920671a3150fa7bcacd166. * Fixed header format. --- html2canvas/html2canvas.d.ts | 38 +++++++++++++++++++++--------------- 1 file changed, 22 insertions(+), 16 deletions(-) diff --git a/html2canvas/html2canvas.d.ts b/html2canvas/html2canvas.d.ts index 1d5fd82fe7..e1fcbc7a1b 100644 --- a/html2canvas/html2canvas.d.ts +++ b/html2canvas/html2canvas.d.ts @@ -1,6 +1,6 @@ -// Type definitions for html2canvas.js v0.4.1 +// Type definitions for html2canvas.js v0.5.0-bata.4 // Project: https://github.com/niklasvh/html2canvas -// Definitions by: Richard Hepburn +// Definitions by: Richard Hepburn , Pei-Tang Huang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -36,26 +36,14 @@ declare namespace Html2Canvas { /** Whether to attempt to load cross-origin images as CORS served, before reverting back to proxy. */ useCORS?: boolean; - + /** Use svg powered rendering where available (FF11+). */ svgRendering?: boolean; - - /** Callback providing the rendered canvas element after rendering */ - onrendered?(canvas: HTMLCanvasElement): void; } } interface Html2CanvasStatic { - /** - * Renders an HTML element to a canvas so that a screenshot can be generated. - * - * The screenshot is based on the DOM and as such may not be 100% accurate to the real representation as it does not make an actual screenshot, - * but builds the screenshot based on the information available on the page. - * - * @param {HTMLElement} element The HTML element which will be rendered to the canvas. Use the root element to render the entire window. - */ - (element: HTMLElement): void; /** * Renders an HTML element to a canvas so that a screenshot can be generated. * @@ -65,7 +53,25 @@ interface Html2CanvasStatic { * @param {HTMLElement} element The HTML element which will be rendered to the canvas. Use the root element to render the entire window. * @param {Html2CanvasOptions} options The options object that controls how the element will be rendered. */ - (element: HTMLElement, options: Html2Canvas.Html2CanvasOptions): void; + (element: HTMLElement, options?: Html2Canvas.Html2CanvasOptions): Html2CanvasPromise; +} + +// FIXME: +// Find out a way to dependent on real Promise interface. +// And remove following custome Promise interface. +interface Html2CanvasThenable { + then(onFulfilled?: (value: R) => U | Html2CanvasThenable, onRejected?: (error: any) => U | Html2CanvasThenable): Html2CanvasThenable; + then(onFulfilled?: (value: R) => U | Html2CanvasThenable, onRejected?: (error: any) => void): Html2CanvasThenable; +} + +interface Html2CanvasPromise extends Html2CanvasThenable { + then(onFulfilled?: (value: R) => U | Html2CanvasThenable, onRejected?: (error: any) => U | Html2CanvasThenable): Html2CanvasPromise; + then(onFulfilled?: (value: R) => U | Html2CanvasThenable, onRejected?: (error: any) => void): Html2CanvasPromise; + catch(onRejected?: (error: any) => U | Html2CanvasThenable): Html2CanvasPromise; +} + +declare module 'html2canvas' { + export = html2canvas; } declare var html2canvas: Html2CanvasStatic; From 1751c28d19510f44b61abad6e219b2b82e0cba30 Mon Sep 17 00:00:00 2001 From: Telshin Date: Tue, 24 May 2016 06:52:21 -0700 Subject: [PATCH 120/402] React-GA typing files (#9397) --- react-ga/react-ga-tests.tsx | 53 +++++++++++++++++++++++++++++++++++++ react-ga/react-ga.d.ts | 27 +++++++++++++++++++ 2 files changed, 80 insertions(+) create mode 100644 react-ga/react-ga-tests.tsx create mode 100644 react-ga/react-ga.d.ts diff --git a/react-ga/react-ga-tests.tsx b/react-ga/react-ga-tests.tsx new file mode 100644 index 0000000000..2248665dd9 --- /dev/null +++ b/react-ga/react-ga-tests.tsx @@ -0,0 +1,53 @@ +/// +/// + +describe("Testing react-ga initialize object", () => { + it("Able to initialize react-ga object", () => { + let ga = __reactGA; + ga.initialize("UA-65432-1"); + }); + it("Able to initailize react-ga object", () => { + let ga = __reactGA; + + let options: __reactGA.InitializeOptions = { + debug: true, + } + + ga.initialize("UA-65432-1", options); + }); +}); + +describe("Testing react-ga pageview calls", () => { + it("Able to make pageview calls", () => { + let ga = __reactGA; + ga.initialize("UA-65432-1"); + + ga.pageview("http://telshin.com"); + }); +}); + +describe("Testing react-ga modal calls", () => { + it("Able to make modal calls", () => { + let ga = __reactGA; + ga.initialize("UA-65432-1"); + + ga.modalview("Test modal"); + }); +}); + +describe("Testing react-ga event calls", () => { + it("Able to make event calls", () => { + let ga = __reactGA; + ga.initialize("UA-65432-1"); + + let options: __reactGA.EventArgs = { + category: "Test", + action: "CI", + label: "Running Jasmine tests for react-ga typscript library", + value: 4, + nonInteraction: true, + } + + ga.event(options); + }); +}); \ No newline at end of file diff --git a/react-ga/react-ga.d.ts b/react-ga/react-ga.d.ts new file mode 100644 index 0000000000..3a80651dc1 --- /dev/null +++ b/react-ga/react-ga.d.ts @@ -0,0 +1,27 @@ +// Type definitions for react-fa v1.4.1 +// Project: https://github.com/react-ga/react-ga +// Definitions by: Tim Aldridge +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace __reactGA { + export interface EventArgs { + category: string; + action: string; + label?: string; + value?: number; + nonInteraction?: boolean; + } + + export interface InitializeOptions { + debug?: boolean; + } + + export function initialize(trackingCode: string, options?: InitializeOptions): void; + export function pageview(path: string): void; + export function modalview(name: string): void; + export function event(args: EventArgs): void; +} + +declare module 'react-ga' { + export = __reactGA; +} From 5f9cf2d84c5b8e1df2f51202900ef081ea2b0f16 Mon Sep 17 00:00:00 2001 From: cjbarth Date: Tue, 24 May 2016 09:53:46 -0400 Subject: [PATCH 121/402] Update Options.ca to use same type as NodeJs (#9399) ca: A string, Buffer or array of strings or Buffers of trusted certificates in PEM format. --- request/request.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/request/request.d.ts b/request/request.d.ts index aaeba2caca..547ee625de 100644 --- a/request/request.d.ts +++ b/request/request.d.ts @@ -110,7 +110,7 @@ declare module 'request' { key?: Buffer; cert?: Buffer; passphrase?: string; - ca?: Buffer; + ca?: string | Buffer | string[] | Buffer[]; har?: HttpArchiveRequest; useQuerystring?: boolean; } From d456e7ccb07a53c47bdd63957e8785402c19c579 Mon Sep 17 00:00:00 2001 From: Sean Kelley Date: Tue, 24 May 2016 06:56:08 -0700 Subject: [PATCH 122/402] Inferrable _.assign*, _.extend*, _.defaults (#9388) * Change the signatures of the _.assign* functions to use intersection types, following 4e4ffc7e. * Redefine _.extend and _.extendWith from scratch by copy-paste-renaming _.assignIn and _.assignInWith (respectively). * Uncomment lodash/extendWith module since it exists now. * Redefine _.defaults using 6ff5a95d0 as a template. * Flip the order of _.defaults intersected types so earlier arguments take precedence when a field is mentioned multiple times. Also fix an extraneous type parameter on an _.assign overload. * Rewrite most of the tests to remove the TResult parameter where appropriate. Add extendWith tests separate from extend tests. * Fix bug with _.defaults where the explicit wrapper variant would return an implicit wrapper. * Update lodash tests to remove a bunch of now-unnecessary type specification. --- lodash/lodash-tests.ts | 695 ++++++++++++++++++++++----------------- lodash/lodash.d.ts | 713 ++++++++++++++++++++++++----------------- 2 files changed, 823 insertions(+), 585 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 2d5f5b50f3..7c63f5be44 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -8014,12 +8014,12 @@ namespace TestRandom { // _.assign namespace TestAssign { - interface Obj {a: string}; - interface S1 {a: number}; - interface S2 {b: number}; - interface S3 {c: number}; - interface S4 {d: number}; - interface S5 {e: number}; + interface Obj { a: string }; + interface S1 { a: number }; + interface S2 { b: number }; + interface S3 { c: number }; + interface S4 { d: number }; + interface S5 { e: number }; let obj: Obj; let s1: S1; @@ -8033,37 +8033,37 @@ namespace TestAssign { { let result: Obj; - result = _.assign(obj); + result = _.assign(obj); } { - let result: {a: number}; + let result: { a: number }; - result = _.assign(obj, s1); + result = _.assign(obj, s1); } { - let result: {a: number, b: number}; + let result: { a: number, b: number }; - result = _.assign(obj, s1, s2); + result = _.assign(obj, s1, s2); } { - let result: {a: number, b: number, c: number}; + let result: { a: number, b: number, c: number }; - result = _.assign(obj, s1, s2, s3); + result = _.assign(obj, s1, s2, s3); } { - let result: {a: number, b: number, c: number, d: number}; + let result: { a: number, b: number, c: number, d: number }; - result = _.assign(obj, s1, s2, s3, s4); + result = _.assign(obj, s1, s2, s3, s4); } { - let result: {a: number, b: number, c: number, d: number, e: number}; + let result: { a: number, b: number, c: number, d: number, e: number }; - result = _.assign(obj, s1, s2, s3, s4, s5); + result = _.assign<{ a: number, b: number, c: number, d: number, e: number }>(obj, s1, s2, s3, s4, s5); } { @@ -8073,33 +8073,33 @@ namespace TestAssign { } { - let result: _.LoDashImplicitObjectWrapper<{a: number}>; + let result: _.LoDashImplicitObjectWrapper<{ a: number }>; - result = _(obj).assign(s1); + result = _(obj).assign(s1); } { - let result: _.LoDashImplicitObjectWrapper<{a: number, b: number}>; + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number }>; - result = _(obj).assign(s1, s2); + result = _(obj).assign(s1, s2); } { - let result: _.LoDashImplicitObjectWrapper<{a: number, b: number, c: number}>; + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number, c: number }>; - result = _(obj).assign(s1, s2, s3); + result = _(obj).assign(s1, s2, s3); } { - let result: _.LoDashImplicitObjectWrapper<{a: number, b: number, c: number, d: number}>; + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number, c: number, d: number }>; - result = _(obj).assign(s1, s2, s3, s4); + result = _(obj).assign(s1, s2, s3, s4); } { - let result: _.LoDashImplicitObjectWrapper<{a: number, b: number, c: number, d: number, e: number}>; + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number, c: number, d: number, e: number }>; - result = _(obj).assign<{a: number, b: number, c: number, d: number, e: number}>(s1, s2, s3, s4, s5); + result = _(obj).assign<{ a: number, b: number, c: number, d: number, e: number }>(s1, s2, s3, s4, s5); } { @@ -8109,44 +8109,44 @@ namespace TestAssign { } { - let result: _.LoDashExplicitObjectWrapper<{a: number}>; + let result: _.LoDashExplicitObjectWrapper<{ a: number }>; - result = _(obj).chain().assign(s1); + result = _(obj).chain().assign(s1); } { - let result: _.LoDashExplicitObjectWrapper<{a: number, b: number}>; + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number }>; - result = _(obj).chain().assign(s1, s2); + result = _(obj).chain().assign(s1, s2); } { - let result: _.LoDashExplicitObjectWrapper<{a: number, b: number, c: number}>; + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number }>; - result = _(obj).chain().assign(s1, s2, s3); + result = _(obj).chain().assign(s1, s2, s3); } { - let result: _.LoDashExplicitObjectWrapper<{a: number, b: number, c: number, d: number}>; + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number, d: number }>; - result = _(obj).chain().assign(s1, s2, s3, s4); + result = _(obj).chain().assign(s1, s2, s3, s4); } { - let result: _.LoDashExplicitObjectWrapper<{a: number, b: number, c: number, d: number, e: number}>; + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number, d: number, e: number }>; - result = _(obj).chain().assign<{a: number, b: number, c: number, d: number, e: number}>(s1, s2, s3, s4, s5); + result = _(obj).chain().assign<{ a: number, b: number, c: number, d: number, e: number }>(s1, s2, s3, s4, s5); } } // _.assignWith namespace TestAssignWith { - interface Obj {a: string}; - interface S1 {a: number}; - interface S2 {b: number}; - interface S3 {c: number}; - interface S4 {d: number}; - interface S5 {e: number}; + interface Obj { a: string }; + interface S1 { a: number }; + interface S2 { b: number }; + interface S3 { c: number }; + interface S4 { d: number }; + interface S5 { e: number }; let obj: Obj; let s1: S1; @@ -8160,32 +8160,32 @@ namespace TestAssignWith { { let result: Obj; - result = _.assignWith(obj); + result = _.assignWith(obj); } { - let result: {a: number}; - result = _.assignWith(obj, s1, customizer); + let result: { a: number }; + result = _.assignWith(obj, s1, customizer); } { - let result: {a: number, b: number}; - result = _.assignWith(obj, s1, s2, customizer); + let result: { a: number, b: number }; + result = _.assignWith(obj, s1, s2, customizer); } { - let result: {a: number, b: number, c: number}; - result = _.assignWith(obj, s1, s2, s3, customizer); + let result: { a: number, b: number, c: number }; + result = _.assignWith(obj, s1, s2, s3, customizer); } { - let result: {a: number, b: number, c: number, d: number}; - result = _.assignWith(obj, s1, s2, s3, s4, customizer); + let result: { a: number, b: number, c: number, d: number }; + result = _.assignWith(obj, s1, s2, s3, s4, customizer); } { - let result: {a: number, b: number, c: number, d: number, e: number}; - result = _.assignWith(obj, s1, s2, s3, s4, s5, customizer); + let result: { a: number, b: number, c: number, d: number, e: number }; + result = _.assignWith<{ a: number, b: number, c: number, d: number, e: number }>(obj, s1, s2, s3, s4, s5, customizer); } { @@ -8195,28 +8195,28 @@ namespace TestAssignWith { } { - let result: _.LoDashImplicitObjectWrapper<{a: number}>; - result = _(obj).assignWith(s1, customizer); + let result: _.LoDashImplicitObjectWrapper<{ a: number }>; + result = _(obj).assignWith(s1, customizer); } { - let result: _.LoDashImplicitObjectWrapper<{a: number, b: number}>; - result = _(obj).assignWith(s1, s2, customizer); + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number }>; + result = _(obj).assignWith(s1, s2, customizer); } { - let result: _.LoDashImplicitObjectWrapper<{a: number, b: number, c: number}>; - result = _(obj).assignWith(s1, s2, s3, customizer); + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number, c: number }>; + result = _(obj).assignWith(s1, s2, s3, customizer); } { - let result: _.LoDashImplicitObjectWrapper<{a: number, b: number, c: number, d: number}>; - result = _(obj).assignWith(s1, s2, s3, s4, customizer); + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number, c: number, d: number }>; + result = _(obj).assignWith(s1, s2, s3, s4, customizer); } { - let result: _.LoDashImplicitObjectWrapper<{a: number, b: number, c: number, d: number, e: number}>; - result = _(obj).assignWith<{a: number, b: number, c: number, d: number, e: number}>(s1, s2, s3, s4, s5, customizer); + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number, c: number, d: number, e: number }>; + result = _(obj).assignWith<{ a: number, b: number, c: number, d: number, e: number }>(s1, s2, s3, s4, s5, customizer); } { @@ -8226,39 +8226,39 @@ namespace TestAssignWith { } { - let result: _.LoDashExplicitObjectWrapper<{a: number}>; - result = _(obj).chain().assignWith(s1, customizer); + let result: _.LoDashExplicitObjectWrapper<{ a: number }>; + result = _(obj).chain().assignWith(s1, customizer); } { - let result: _.LoDashExplicitObjectWrapper<{a: number, b: number}>; - result = _(obj).chain().assignWith(s1, s2, customizer); + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number }>; + result = _(obj).chain().assignWith(s1, s2, customizer); } { - let result: _.LoDashExplicitObjectWrapper<{a: number, b: number, c: number}>; - result = _(obj).chain().assignWith(s1, s2, s3, customizer); + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number }>; + result = _(obj).chain().assignWith(s1, s2, s3, customizer); } { - let result: _.LoDashExplicitObjectWrapper<{a: number, b: number, c: number, d: number}>; - result = _(obj).chain().assignWith(s1, s2, s3, s4, customizer); + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number, d: number }>; + result = _(obj).chain().assignWith(s1, s2, s3, s4, customizer); } { - let result: _.LoDashExplicitObjectWrapper<{a: number, b: number, c: number, d: number, e: number}>; - result = _(obj).chain().assignWith<{a: number, b: number, c: number, d: number, e: number}>(s1, s2, s3, s4, s5, customizer); + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number, d: number, e: number }>; + result = _(obj).chain().assignWith<{ a: number, b: number, c: number, d: number, e: number }>(s1, s2, s3, s4, s5, customizer); } } // _.assignIn namespace TestAssignIn { - interface Obj {a: string}; - interface S1 {a: number}; - interface S2 {b: number}; - interface S3 {c: number}; - interface S4 {d: number}; - interface S5 {e: number}; + interface Obj { a: string }; + interface S1 { a: number }; + interface S2 { b: number }; + interface S3 { c: number }; + interface S4 { d: number }; + interface S5 { e: number }; let obj: Obj; let s1: S1; @@ -8272,37 +8272,37 @@ namespace TestAssignIn { { let result: Obj; - result = _.assignIn(obj); + result = _.assignIn(obj); } { - let result: {a: number}; + let result: { a: number }; - result = _.assignIn(obj, s1); + result = _.assignIn(obj, s1); } { - let result: {a: number, b: number}; + let result: { a: number, b: number }; - result = _.assignIn(obj, s1, s2); + result = _.assignIn(obj, s1, s2); } { - let result: {a: number, b: number, c: number}; + let result: { a: number, b: number, c: number }; - result = _.assignIn(obj, s1, s2, s3); + result = _.assignIn(obj, s1, s2, s3); } { - let result: {a: number, b: number, c: number, d: number}; + let result: { a: number, b: number, c: number, d: number }; - result = _.assignIn(obj, s1, s2, s3, s4); + result = _.assignIn(obj, s1, s2, s3, s4); } { - let result: {a: number, b: number, c: number, d: number, e: number}; + let result: { a: number, b: number, c: number, d: number, e: number }; - result = _.assignIn(obj, s1, s2, s3, s4, s5); + result = _.assignIn<{ a: number, b: number, c: number, d: number, e: number }>(obj, s1, s2, s3, s4, s5); } { @@ -8312,33 +8312,33 @@ namespace TestAssignIn { } { - let result: _.LoDashImplicitObjectWrapper<{a: number}>; + let result: _.LoDashImplicitObjectWrapper<{ a: number }>; - result = _(obj).assignIn(s1); + result = _(obj).assignIn(s1); } { - let result: _.LoDashImplicitObjectWrapper<{a: number, b: number}>; + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number }>; - result = _(obj).assignIn(s1, s2); + result = _(obj).assignIn(s1, s2); } { - let result: _.LoDashImplicitObjectWrapper<{a: number, b: number, c: number}>; + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number, c: number }>; - result = _(obj).assignIn(s1, s2, s3); + result = _(obj).assignIn(s1, s2, s3); } { - let result: _.LoDashImplicitObjectWrapper<{a: number, b: number, c: number, d: number}>; + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number, c: number, d: number }>; - result = _(obj).assignIn(s1, s2, s3, s4); + result = _(obj).assignIn(s1, s2, s3, s4); } { - let result: _.LoDashImplicitObjectWrapper<{a: number, b: number, c: number, d: number, e: number}>; + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number, c: number, d: number, e: number }>; - result = _(obj).assignIn<{a: number, b: number, c: number, d: number, e: number}>(s1, s2, s3, s4, s5); + result = _(obj).assignIn<{ a: number, b: number, c: number, d: number, e: number }>(s1, s2, s3, s4, s5); } { @@ -8348,44 +8348,44 @@ namespace TestAssignIn { } { - let result: _.LoDashExplicitObjectWrapper<{a: number}>; + let result: _.LoDashExplicitObjectWrapper<{ a: number }>; - result = _(obj).chain().assignIn(s1); + result = _(obj).chain().assignIn(s1); } { - let result: _.LoDashExplicitObjectWrapper<{a: number, b: number}>; + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number }>; - result = _(obj).chain().assignIn(s1, s2); + result = _(obj).chain().assignIn(s1, s2); } { - let result: _.LoDashExplicitObjectWrapper<{a: number, b: number, c: number}>; + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number }>; - result = _(obj).chain().assignIn(s1, s2, s3); + result = _(obj).chain().assignIn(s1, s2, s3); } { - let result: _.LoDashExplicitObjectWrapper<{a: number, b: number, c: number, d: number}>; + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number, d: number }>; - result = _(obj).chain().assignIn(s1, s2, s3, s4); + result = _(obj).chain().assignIn(s1, s2, s3, s4); } { - let result: _.LoDashExplicitObjectWrapper<{a: number, b: number, c: number, d: number, e: number}>; + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number, d: number, e: number }>; - result = _(obj).chain().assignIn<{a: number, b: number, c: number, d: number, e: number}>(s1, s2, s3, s4, s5); + result = _(obj).chain().assignIn<{ a: number, b: number, c: number, d: number, e: number }>(s1, s2, s3, s4, s5); } } // _.assignInWith namespace TestAssignInWith { - interface Obj {a: string}; - interface S1 {a: number}; - interface S2 {b: number}; - interface S3 {c: number}; - interface S4 {d: number}; - interface S5 {e: number}; + interface Obj { a: string }; + interface S1 { a: number }; + interface S2 { b: number }; + interface S3 { c: number }; + interface S4 { d: number }; + interface S5 { e: number }; let obj: Obj; let s1: S1; @@ -8399,32 +8399,32 @@ namespace TestAssignInWith { { let result: Obj; - result = _.assignInWith(obj); + result = _.assignInWith(obj); } { - let result: {a: number}; - result = _.assignInWith(obj, s1, customizer); + let result: { a: number }; + result = _.assignInWith(obj, s1, customizer); } { - let result: {a: number, b: number}; - result = _.assignInWith(obj, s1, s2, customizer); + let result: { a: number, b: number }; + result = _.assignInWith(obj, s1, s2, customizer); } { - let result: {a: number, b: number, c: number}; - result = _.assignInWith(obj, s1, s2, s3, customizer); + let result: { a: number, b: number, c: number }; + result = _.assignInWith(obj, s1, s2, s3, customizer); } { - let result: {a: number, b: number, c: number, d: number}; - result = _.assignInWith(obj, s1, s2, s3, s4, customizer); + let result: { a: number, b: number, c: number, d: number }; + result = _.assignInWith(obj, s1, s2, s3, s4, customizer); } { - let result: {a: number, b: number, c: number, d: number, e: number}; - result = _.assignInWith(obj, s1, s2, s3, s4, s5, customizer); + let result: { a: number, b: number, c: number, d: number, e: number }; + result = _.assignInWith<{ a: number, b: number, c: number, d: number, e: number }>(obj, s1, s2, s3, s4, s5, customizer); } { @@ -8434,28 +8434,28 @@ namespace TestAssignInWith { } { - let result: _.LoDashImplicitObjectWrapper<{a: number}>; - result = _(obj).assignInWith(s1, customizer); + let result: _.LoDashImplicitObjectWrapper<{ a: number }>; + result = _(obj).assignInWith(s1, customizer); } { - let result: _.LoDashImplicitObjectWrapper<{a: number, b: number}>; - result = _(obj).assignInWith(s1, s2, customizer); + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number }>; + result = _(obj).assignInWith(s1, s2, customizer); } { - let result: _.LoDashImplicitObjectWrapper<{a: number, b: number, c: number}>; - result = _(obj).assignInWith(s1, s2, s3, customizer); + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number, c: number }>; + result = _(obj).assignInWith(s1, s2, s3, customizer); } { - let result: _.LoDashImplicitObjectWrapper<{a: number, b: number, c: number, d: number}>; - result = _(obj).assignInWith(s1, s2, s3, s4, customizer); + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number, c: number, d: number }>; + result = _(obj).assignInWith(s1, s2, s3, s4, customizer); } { - let result: _.LoDashImplicitObjectWrapper<{a: number, b: number, c: number, d: number, e: number}>; - result = _(obj).assignInWith<{a: number, b: number, c: number, d: number, e: number}>(s1, s2, s3, s4, s5, customizer); + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number, c: number, d: number, e: number }>; + result = _(obj).assignInWith<{ a: number, b: number, c: number, d: number, e: number }>(s1, s2, s3, s4, s5, customizer); } { @@ -8465,28 +8465,28 @@ namespace TestAssignInWith { } { - let result: _.LoDashExplicitObjectWrapper<{a: number}>; - result = _(obj).chain().assignInWith(s1, customizer); + let result: _.LoDashExplicitObjectWrapper<{ a: number }>; + result = _(obj).chain().assignInWith(s1, customizer); } { - let result: _.LoDashExplicitObjectWrapper<{a: number, b: number}>; - result = _(obj).chain().assignInWith(s1, s2, customizer); + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number }>; + result = _(obj).chain().assignInWith(s1, s2, customizer); } { - let result: _.LoDashExplicitObjectWrapper<{a: number, b: number, c: number}>; - result = _(obj).chain().assignInWith(s1, s2, s3, customizer); + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number }>; + result = _(obj).chain().assignInWith(s1, s2, s3, customizer); } { - let result: _.LoDashExplicitObjectWrapper<{a: number, b: number, c: number, d: number}>; - result = _(obj).chain().assignInWith(s1, s2, s3, s4, customizer); + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number, d: number }>; + result = _(obj).chain().assignInWith(s1, s2, s3, s4, customizer); } { - let result: _.LoDashExplicitObjectWrapper<{a: number, b: number, c: number, d: number, e: number}>; - result = _(obj).chain().assignInWith<{a: number, b: number, c: number, d: number, e: number}>(s1, s2, s3, s4, s5, customizer); + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number, d: number, e: number }>; + result = _(obj).chain().assignInWith<{ a: number, b: number, c: number, d: number, e: number }>(s1, s2, s3, s4, s5, customizer); } } @@ -8520,151 +8520,153 @@ namespace TestCreate { } } + // _.defaults namespace TestDefaults { - interface Obj {a: string}; - interface S1 {a: number}; - interface S2 {b: number}; - interface S3 {c: number}; - interface S4 {d: number}; - interface S5 {e: number}; + interface Obj { a: string }; + interface S1 { a: number }; + interface S2 { b: number }; + interface S3 { c: number }; + interface S4 { d: number }; + interface S5 { e: number }; - let obj: Obj; - let s1: S1; - let s2: S2; - let s3: S3; - let s4: S4; - let s5: S5; + let obj: Obj; + let s1: S1; + let s2: S2; + let s3: S3; + let s4: S4; + let s5: S5; - { - let result: Obj; + { + let result: Obj; - result = _.defaults(obj); - } + result = _.defaults(obj); + } - { - let result: {a: string}; + { + let result: { a: string }; - result = _.defaults(obj, s1); - } + result = _.defaults(obj, s1); + } - { - let result: {a: string, b: number}; + { + let result: { a: string, b: number }; - result = _.defaults(obj, s1, s2); - } + result = _.defaults(obj, s1, s2); + } - { - let result: {a: string, b: number, c: number}; + { + let result: { a: string, b: number, c: number }; - result = _.defaults(obj, s1, s2, s3); - } + result = _.defaults(obj, s1, s2, s3); + } - { - let result: {a: string, b: number, c: number, d: number}; + { + let result: { a: string, b: number, c: number, d: number }; - result = _.defaults(obj, s1, s2, s3, s4); - } + result = _.defaults(obj, s1, s2, s3, s4); + } - { - let result: {a: string, b: number, c: number, d: number, e: number}; + { + let result: { a: string, b: number, c: number, d: number, e: number }; - result = _.defaults(obj, s1, s2, s3, s4, s5); - } + result = _.defaults<{ a: string, b: number, c: number, d: number, e: number }>(obj, s1, s2, s3, s4, s5); + } - { - let result: _.LoDashImplicitObjectWrapper; + { + let result: _.LoDashImplicitObjectWrapper; - result = _(obj).defaults(); - } + result = _(obj).defaults(); + } - { - let result: _.LoDashImplicitObjectWrapper<{a: string}>; + { + let result: _.LoDashImplicitObjectWrapper<{ a: string }>; - result = _(obj).defaults(s1); - } + result = _(obj).defaults(s1); + } - { - let result: _.LoDashImplicitObjectWrapper<{a: string, b: number}>; + { + let result: _.LoDashImplicitObjectWrapper<{ a: string, b: number }>; - result = _(obj).defaults(s1, s2); - } + result = _(obj).defaults(s1, s2); + } - { - let result: _.LoDashImplicitObjectWrapper<{a: string, b: number, c: number}>; + { + let result: _.LoDashImplicitObjectWrapper<{ a: string, b: number, c: number }>; - result = _(obj).defaults(s1, s2, s3); - } + result = _(obj).defaults(s1, s2, s3); + } - { - let result: _.LoDashImplicitObjectWrapper<{a: string, b: number, c: number, d: number}>; + { + let result: _.LoDashImplicitObjectWrapper<{ a: string, b: number, c: number, d: number }>; - result = _(obj).defaults(s1, s2, s3, s4); - } + result = _(obj).defaults(s1, s2, s3, s4); + } - { - let result: _.LoDashImplicitObjectWrapper<{a: string, b: number, c: number, d: number, e: number}>; + { + let result: _.LoDashImplicitObjectWrapper<{ a: string, b: number, c: number, d: number, e: number }>; - result = _(obj).defaults<{a: string, b: number, c: number, d: number, e: number}>(s1, s2, s3, s4, s5); - } + result = _(obj).defaults<{ a: string, b: number, c: number, d: number, e: number }>(s1, s2, s3, s4, s5); + } - { - let result: _.LoDashExplicitObjectWrapper; + { + let result: _.LoDashExplicitObjectWrapper; - result = _(obj).chain().defaults(); - } + result = _(obj).chain().defaults(); + } - { - let result: _.LoDashExplicitObjectWrapper<{a: string}>; + { + let result: _.LoDashExplicitObjectWrapper<{ a: string }>; - result = _(obj).chain().defaults(s1); - } + result = _(obj).chain().defaults(s1); + } - { - let result: _.LoDashExplicitObjectWrapper<{a: string, b: number}>; + { + let result: _.LoDashExplicitObjectWrapper<{ a: string, b: number }>; - result = _(obj).chain().defaults(s1, s2); - } + result = _(obj).chain().defaults(s1, s2); + } - { - let result: _.LoDashExplicitObjectWrapper<{a: string, b: number, c: number}>; + { + let result: _.LoDashExplicitObjectWrapper<{ a: string, b: number, c: number }>; - result = _(obj).chain().defaults(s1, s2, s3); - } + result = _(obj).chain().defaults(s1, s2, s3); + } - { - let result: _.LoDashExplicitObjectWrapper<{a: string, b: number, c: number, d: number}>; + { + let result: _.LoDashExplicitObjectWrapper<{ a: string, b: number, c: number, d: number }>; - result = _(obj).chain().defaults(s1, s2, s3, s4); - } + result = _(obj).chain().defaults(s1, s2, s3, s4); + } - { - let result: _.LoDashExplicitObjectWrapper<{a: string, b: number, c: number, d: number, e: number}>; + { + let result: _.LoDashExplicitObjectWrapper<{ a: string, b: number, c: number, d: number, e: number }>; - result = _(obj).chain().defaults<{a: string, b: number, c: number, d: number, e: number}>(s1, s2, s3, s4, s5); - } + result = _(obj).chain().defaults<{ a: string, b: number, c: number, d: number, e: number }>(s1, s2, s3, s4, s5); + } } //_.defaultsDeep interface DefaultsDeepResult { - user: { - name: string; - age: number; - } + user: { + name: string; + age: number; + } } -var TestDefaultsDeepObject = {'user': {'name': 'barney'}}; -var TestDefaultsDeepSource = {'user': {'name': 'fred', 'age': 36}}; +var TestDefaultsDeepObject = { 'user': { 'name': 'barney' } }; +var TestDefaultsDeepSource = { 'user': { 'name': 'fred', 'age': 36 } }; result = _.defaultsDeep(TestDefaultsDeepObject, TestDefaultsDeepSource); result = _(TestDefaultsDeepObject).defaultsDeep(TestDefaultsDeepSource).value(); + // _.extend namespace TestExtend { - type Obj = {a: string}; - type S1 = {a: number}; - type S2 = {b: number}; - type S3 = {c: number}; - type S4 = {d: number}; - type S5 = {e: number}; + type Obj = { a: string }; + type S1 = { a: number }; + type S2 = { b: number }; + type S3 = { c: number }; + type S4 = { d: number }; + type S5 = { e: number }; let obj: Obj; let s1: S1; @@ -8678,42 +8680,37 @@ namespace TestExtend { { let result: Obj; - result = _.extend(obj); + result = _.extend(obj); } { - let result: {a: number}; + let result: { a: number }; - result = _.extend(obj, s1); - result = _.extend(obj, s1, customizer); + result = _.extend(obj, s1); } { - let result: {a: number, b: number}; + let result: { a: number, b: number }; - result = _.extend(obj, s1, s2); - result = _.extend(obj, s1, s2, customizer); + result = _.extend(obj, s1, s2); } { - let result: {a: number, b: number, c: number}; + let result: { a: number, b: number, c: number }; - result = _.extend(obj, s1, s2, s3); - result = _.extend(obj, s1, s2, s3, customizer); + result = _.extend(obj, s1, s2, s3); } { - let result: {a: number, b: number, c: number, d: number}; + let result: { a: number, b: number, c: number, d: number }; - result = _.extend(obj, s1, s2, s3, s4); - result = _.extend(obj, s1, s2, s3, s4, customizer); + result = _.extend(obj, s1, s2, s3, s4); } { - let result: {a: number, b: number, c: number, d: number, e: number}; + let result: { a: number, b: number, c: number, d: number, e: number }; - result = _.extend(obj, s1, s2, s3, s4, s5); - result = _.extend(obj, s1, s2, s3, s4, s5, customizer); + result = _.extend<{ a: number, b: number, c: number, d: number, e: number }>(obj, s1, s2, s3, s4, s5); } { @@ -8723,38 +8720,33 @@ namespace TestExtend { } { - let result: _.LoDashImplicitObjectWrapper<{a: number}>; + let result: _.LoDashImplicitObjectWrapper<{ a: number }>; - result = _(obj).extend(s1); - result = _(obj).extend(s1, customizer); + result = _(obj).extend(s1); } { - let result: _.LoDashImplicitObjectWrapper<{a: number, b: number}>; + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number }>; - result = _(obj).extend(s1, s2); - result = _(obj).extend(s1, s2, customizer); + result = _(obj).extend(s1, s2); } { - let result: _.LoDashImplicitObjectWrapper<{a: number, b: number, c: number}>; + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number, c: number }>; - result = _(obj).extend(s1, s2, s3); - result = _(obj).extend(s1, s2, s3, customizer); + result = _(obj).extend(s1, s2, s3); } { - let result: _.LoDashImplicitObjectWrapper<{a: number, b: number, c: number, d: number}>; + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number, c: number, d: number }>; - result = _(obj).extend(s1, s2, s3, s4); - result = _(obj).extend(s1, s2, s3, s4, customizer); + result = _(obj).extend(s1, s2, s3, s4); } { - let result: _.LoDashImplicitObjectWrapper<{a: number, b: number, c: number, d: number, e: number}>; + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number, c: number, d: number, e: number }>; - result = _(obj).extend(s1, s2, s3, s4, s5); - result = _(obj).extend(s1, s2, s3, s4, s5, customizer); + result = _(obj).extend<{ a: number, b: number, c: number, d: number, e: number }>(s1, s2, s3, s4, s5); } { @@ -8764,38 +8756,161 @@ namespace TestExtend { } { - let result: _.LoDashExplicitObjectWrapper<{a: number}>; + let result: _.LoDashExplicitObjectWrapper<{ a: number }>; - result = _(obj).chain().extend(s1); - result = _(obj).chain().extend(s1, customizer); + result = _(obj).chain().extend(s1); } { - let result: _.LoDashExplicitObjectWrapper<{a: number, b: number}>; + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number }>; - result = _(obj).chain().extend(s1, s2); - result = _(obj).chain().extend(s1, s2, customizer); + result = _(obj).chain().extend(s1, s2); } { - let result: _.LoDashExplicitObjectWrapper<{a: number, b: number, c: number}>; + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number }>; - result = _(obj).chain().extend(s1, s2, s3); - result = _(obj).chain().extend(s1, s2, s3, customizer); + result = _(obj).chain().extend(s1, s2, s3); } { - let result: _.LoDashExplicitObjectWrapper<{a: number, b: number, c: number, d: number}>; + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number, d: number }>; - result = _(obj).chain().extend(s1, s2, s3, s4); - result = _(obj).chain().extend(s1, s2, s3, s4, customizer); + result = _(obj).chain().extend(s1, s2, s3, s4); } { - let result: _.LoDashExplicitObjectWrapper<{a: number, b: number, c: number, d: number, e: number}>; + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number, d: number, e: number }>; - result = _(obj).chain().extend(s1, s2, s3, s4, s5); - result = _(obj).chain().extend(s1, s2, s3, s4, s5, customizer); + result = _(obj).chain().extend<{ a: number, b: number, c: number, d: number, e: number }>(s1, s2, s3, s4, s5); + } +} + + +// _.extendWith +namespace TestExtendWith { + type Obj = { a: string }; + type S1 = { a: number }; + type S2 = { b: number }; + type S3 = { c: number }; + type S4 = { d: number }; + type S5 = { e: number }; + + let obj: Obj; + let s1: S1; + let s2: S2; + let s3: S3; + let s4: S4; + let s5: S5; + + let customizer: (objectValue: any, sourceValue: any, key?: string, object?: {}, source?: {}) => any; + + { + let result: Obj; + + result = _.extendWith(obj); + } + + { + let result: { a: number }; + + result = _.extendWith(obj, s1, customizer); + } + + { + let result: { a: number, b: number }; + + result = _.extendWith(obj, s1, s2, customizer); + } + + { + let result: { a: number, b: number, c: number }; + + result = _.extendWith(obj, s1, s2, s3, customizer); + } + + { + let result: { a: number, b: number, c: number, d: number }; + + result = _.extendWith(obj, s1, s2, s3, s4, customizer); + } + + { + let result: { a: number, b: number, c: number, d: number, e: number }; + + result = _.extendWith<{ a: number, b: number, c: number, d: number, e: number }>(obj, s1, s2, s3, s4, s5, customizer); + } + + { + let result: _.LoDashImplicitObjectWrapper; + + result = _(obj).extendWith(); + } + + { + let result: _.LoDashImplicitObjectWrapper<{ a: number }>; + + result = _(obj).extendWith(s1, customizer); + } + + { + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number }>; + + result = _(obj).extendWith(s1, s2, customizer); + } + + { + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number, c: number }>; + + result = _(obj).extendWith(s1, s2, s3, customizer); + } + + { + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number, c: number, d: number }>; + + result = _(obj).extendWith(s1, s2, s3, s4, customizer); + } + + { + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number, c: number, d: number, e: number }>; + + result = _(obj).extendWith<{ a: number, b: number, c: number, d: number, e: number }>(s1, s2, s3, s4, s5, customizer); + } + + { + let result: _.LoDashExplicitObjectWrapper; + + result = _(obj).chain().extendWith(); + } + + { + let result: _.LoDashExplicitObjectWrapper<{ a: number }>; + + result = _(obj).chain().extendWith(s1, customizer); + } + + { + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number }>; + + result = _(obj).chain().extendWith(s1, s2, customizer); + } + + { + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number }>; + + result = _(obj).chain().extendWith(s1, s2, s3, customizer); + } + + { + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number, d: number }>; + + result = _(obj).chain().extendWith(s1, s2, s3, s4, customizer); + } + + { + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number, d: number, e: number }>; + + result = _(obj).chain().extendWith<{ a: number, b: number, c: number, d: number, e: number }>(s1, s2, s3, s4, s5, customizer); } } diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 1e39d223f0..8407681ab2 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -13761,53 +13761,52 @@ declare module _ { * _.assign({ 'a': 1 }, new Foo, new Bar); * // => { 'a': 1, 'c': 3, 'e': 5 } */ - assign( + assign( object: TObject, source: TSource - ): TResult; + ): TObject & TSource; /** * @see assign */ - assign( + assign( object: TObject, source1: TSource1, source2: TSource2 - ): TResult; + ): TObject & TSource1 & TSource2; /** * @see assign */ - assign( + assign( object: TObject, source1: TSource1, source2: TSource2, source3: TSource3 - ): TResult; + ): TObject & TSource1 & TSource2 & TSource3; /** * @see assign */ - assign - ( + assign( object: TObject, source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4 - ): TResult; + ): TObject & TSource1 & TSource2 & TSource3 & TSource4; /** * @see _.assign */ - assign(object: TObject): TObject; + assign(object: TObject): TObject; /** * @see _.assign */ - assign( - object: TObject, ...otherArgs: any[] + assign( + object: any, + ...otherArgs: any[] ): TResult; } @@ -13815,36 +13814,36 @@ declare module _ { /** * @see _.assign */ - assign( + assign( source: TSource - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitObjectWrapper; /** * @see assign */ - assign( + assign( source1: TSource1, source2: TSource2 - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitObjectWrapper; /** * @see assign */ - assign( + assign( source1: TSource1, source2: TSource2, source3: TSource3 - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitObjectWrapper; /** * @see assign */ - assign( + assign( source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4 - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitObjectWrapper; /** * @see _.assign @@ -13854,43 +13853,43 @@ declare module _ { /** * @see _.assign */ - assign(...otherArgs: any[]): LoDashImplicitObjectWrapper; + assign(...otherArgs: any[]): LoDashImplicitObjectWrapper; } interface LoDashExplicitObjectWrapper { /** * @see _.assign */ - assign( + assign( source: TSource - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitObjectWrapper; /** * @see assign */ - assign( + assign( source1: TSource1, source2: TSource2 - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitObjectWrapper; /** * @see assign */ - assign( + assign( source1: TSource1, source2: TSource2, source3: TSource3 - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitObjectWrapper; /** * @see assign */ - assign( + assign( source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4 - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitObjectWrapper; /** * @see _.assign @@ -13900,7 +13899,7 @@ declare module _ { /** * @see _.assign */ - assign(...otherArgs: any[]): LoDashExplicitObjectWrapper; + assign(...otherArgs: any[]): LoDashExplicitObjectWrapper; } //_.assignWith @@ -13935,57 +13934,56 @@ declare module _ { * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ - assignWith( + assignWith( object: TObject, source: TSource, customizer: AssignCustomizer - ): TResult; + ): TObject & TSource; /** * @see assignWith */ - assignWith( + assignWith( object: TObject, source1: TSource1, source2: TSource2, customizer: AssignCustomizer - ): TResult; + ): TObject & TSource1 & TSource2; /** * @see assignWith */ - assignWith( + assignWith( object: TObject, source1: TSource1, source2: TSource2, source3: TSource3, customizer: AssignCustomizer - ): TResult; + ): TObject & TSource1 & TSource2 & TSource3; /** * @see assignWith */ - assignWith - ( + assignWith( object: TObject, source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4, customizer: AssignCustomizer - ): TResult; + ): TObject & TSource1 & TSource2 & TSource3 & TSource4; /** * @see _.assignWith */ - assignWith(object: TObject): TObject; + assignWith(object: TObject): TObject; /** * @see _.assignWith */ - assignWith( - object: TObject, ...otherArgs: any[] + assignWith( + object: any, + ...otherArgs: any[] ): TResult; } @@ -13993,40 +13991,40 @@ declare module _ { /** * @see _.assignWith */ - assignWith( + assignWith( source: TSource, customizer: AssignCustomizer - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitObjectWrapper; /** * @see assignWith */ - assignWith( + assignWith( source1: TSource1, source2: TSource2, customizer: AssignCustomizer - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitObjectWrapper; /** * @see assignWith */ - assignWith( + assignWith( source1: TSource1, source2: TSource2, source3: TSource3, customizer: AssignCustomizer - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitObjectWrapper; /** * @see assignWith */ - assignWith( + assignWith( source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4, customizer: AssignCustomizer - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitObjectWrapper; /** * @see _.assignWith @@ -14036,47 +14034,47 @@ declare module _ { /** * @see _.assignWith */ - assignWith(...otherArgs: any[]): LoDashImplicitObjectWrapper; + assignWith(...otherArgs: any[]): LoDashImplicitObjectWrapper; } interface LoDashExplicitObjectWrapper { /** * @see _.assignWith */ - assignWith( + assignWith( source: TSource, customizer: AssignCustomizer - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitObjectWrapper; /** * @see assignWith */ - assignWith( + assignWith( source1: TSource1, source2: TSource2, customizer: AssignCustomizer - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitObjectWrapper; /** * @see assignWith */ - assignWith( + assignWith( source1: TSource1, source2: TSource2, source3: TSource3, customizer: AssignCustomizer - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitObjectWrapper; /** * @see assignWith */ - assignWith( + assignWith( source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4, customizer: AssignCustomizer - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitObjectWrapper; /** * @see _.assignWith @@ -14086,7 +14084,7 @@ declare module _ { /** * @see _.assignWith */ - assignWith(...otherArgs: any[]): LoDashExplicitObjectWrapper; + assignWith(...otherArgs: any[]): LoDashExplicitObjectWrapper; } //_.assignIn @@ -14120,53 +14118,52 @@ declare module _ { * _.assignIn({ 'a': 1 }, new Foo, new Bar); * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5 } */ - assignIn( + assignIn( object: TObject, source: TSource - ): TResult; + ): TObject & TSource; /** * @see assignIn */ - assignIn( + assignIn( object: TObject, source1: TSource1, source2: TSource2 - ): TResult; + ): TObject & TSource1 & TSource2; /** * @see assignIn */ - assignIn( + assignIn( object: TObject, source1: TSource1, source2: TSource2, source3: TSource3 - ): TResult; + ): TObject & TSource1 & TSource2 & TSource3; /** * @see assignIn */ - assignIn - ( + assignIn( object: TObject, source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4 - ): TResult; + ): TObject & TSource1 & TSource2 & TSource3 & TSource4; /** * @see _.assignIn */ - assignIn(object: TObject): TObject; + assignIn(object: TObject): TObject; /** * @see _.assignIn */ - assignIn( - object: TObject, ...otherArgs: any[] + assignIn( + object: any, + ...otherArgs: any[] ): TResult; } @@ -14174,36 +14171,36 @@ declare module _ { /** * @see _.assignIn */ - assignIn( + assignIn( source: TSource - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitObjectWrapper; /** * @see assignIn */ - assignIn( + assignIn( source1: TSource1, source2: TSource2 - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitObjectWrapper; /** * @see assignIn */ - assignIn( + assignIn( source1: TSource1, source2: TSource2, source3: TSource3 - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitObjectWrapper; /** * @see assignIn */ - assignIn( + assignIn( source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4 - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitObjectWrapper; /** * @see _.assignIn @@ -14213,43 +14210,43 @@ declare module _ { /** * @see _.assignIn */ - assignIn(...otherArgs: any[]): LoDashImplicitObjectWrapper; + assignIn(...otherArgs: any[]): LoDashImplicitObjectWrapper; } interface LoDashExplicitObjectWrapper { /** * @see _.assignIn */ - assignIn( + assignIn( source: TSource - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitObjectWrapper; /** * @see assignIn */ - assignIn( + assignIn( source1: TSource1, source2: TSource2 - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitObjectWrapper; /** * @see assignIn */ - assignIn( + assignIn( source1: TSource1, source2: TSource2, source3: TSource3 - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitObjectWrapper; /** * @see assignIn */ - assignIn( + assignIn( source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4 - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitObjectWrapper; /** * @see _.assignIn @@ -14259,7 +14256,7 @@ declare module _ { /** * @see _.assignIn */ - assignIn(...otherArgs: any[]): LoDashExplicitObjectWrapper; + assignIn(...otherArgs: any[]): LoDashExplicitObjectWrapper; } //_.assignInWith @@ -14295,57 +14292,56 @@ declare module _ { * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ - assignInWith( + assignInWith( object: TObject, source: TSource, customizer: AssignCustomizer - ): TResult; + ): TObject & TSource; /** * @see assignInWith */ - assignInWith( + assignInWith( object: TObject, source1: TSource1, source2: TSource2, customizer: AssignCustomizer - ): TResult; + ): TObject & TSource1 & TSource2; /** * @see assignInWith */ - assignInWith( + assignInWith( object: TObject, source1: TSource1, source2: TSource2, source3: TSource3, customizer: AssignCustomizer - ): TResult; + ): TObject & TSource1 & TSource2 & TSource3; /** * @see assignInWith */ - assignInWith - ( + assignInWith( object: TObject, source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4, customizer: AssignCustomizer - ): TResult; + ): TObject & TSource1 & TSource2 & TSource3 & TSource4; /** * @see _.assignInWith */ - assignInWith(object: TObject): TObject; + assignInWith(object: TObject): TObject; /** * @see _.assignInWith */ - assignInWith( - object: TObject, ...otherArgs: any[] + assignInWith( + object: any, + ...otherArgs: any[] ): TResult; } @@ -14353,40 +14349,40 @@ declare module _ { /** * @see _.assignInWith */ - assignInWith( + assignInWith( source: TSource, customizer: AssignCustomizer - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitObjectWrapper; /** * @see assignInWith */ - assignInWith( + assignInWith( source1: TSource1, source2: TSource2, customizer: AssignCustomizer - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitObjectWrapper; /** * @see assignInWith */ - assignInWith( + assignInWith( source1: TSource1, source2: TSource2, source3: TSource3, customizer: AssignCustomizer - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitObjectWrapper; /** * @see assignInWith */ - assignInWith( + assignInWith( source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4, customizer: AssignCustomizer - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitObjectWrapper; /** * @see _.assignInWith @@ -14396,47 +14392,47 @@ declare module _ { /** * @see _.assignInWith */ - assignInWith(...otherArgs: any[]): LoDashImplicitObjectWrapper; + assignInWith(...otherArgs: any[]): LoDashImplicitObjectWrapper; } interface LoDashExplicitObjectWrapper { /** * @see _.assignInWith */ - assignInWith( + assignInWith( source: TSource, customizer: AssignCustomizer - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitObjectWrapper; /** * @see assignInWith */ - assignInWith( + assignInWith( source1: TSource1, source2: TSource2, customizer: AssignCustomizer - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitObjectWrapper; /** * @see assignInWith */ - assignInWith( + assignInWith( source1: TSource1, source2: TSource2, source3: TSource3, customizer: AssignCustomizer - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitObjectWrapper; /** * @see assignInWith */ - assignInWith( + assignInWith( source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4, customizer: AssignCustomizer - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitObjectWrapper; /** * @see _.assignInWith @@ -14446,7 +14442,7 @@ declare module _ { /** * @see _.assignInWith */ - assignInWith(...otherArgs: any[]): LoDashExplicitObjectWrapper; + assignInWith(...otherArgs: any[]): LoDashExplicitObjectWrapper; } //_.create @@ -14479,6 +14475,7 @@ declare module _ { create(properties?: U): LoDashExplicitObjectWrapper; } + //_.defaults interface LoDashStatic { /** @@ -14492,59 +14489,52 @@ declare module _ { * @param sources The source objects. * @return The destination object. */ - defaults( - object: Obj, - ...sources: {}[] - ): TResult; + defaults( + object: TObject, + source: TSource + ): TSource & TObject; /** * @see _.defaults */ - defaults( - object: Obj, - source1: S1, - ...sources: {}[] - ): TResult; + defaults( + object: TObject, + source1: TSource1, + source2: TSource2 + ): TSource2 & TSource1 & TObject; /** * @see _.defaults */ - defaults( - object: Obj, - source1: S1, - source2: S2, - ...sources: {}[] - ): TResult; + defaults( + object: TObject, + source1: TSource1, + source2: TSource2, + source3: TSource3 + ): TSource3 & TSource2 & TSource1 & TObject; /** * @see _.defaults */ - defaults( - object: Obj, - source1: S1, - source2: S2, - source3: S3, - ...sources: {}[] - ): TResult; + defaults( + object: TObject, + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4 + ): TSource4 & TSource3 & TSource2 & TSource1 & TObject; /** * @see _.defaults */ - defaults( - object: Obj, - source1: S1, - source2: S2, - source3: S3, - source4: S4, - ...sources: {}[] - ): TResult; + defaults(object: TObject): TObject; /** * @see _.defaults */ - defaults( - object: {}, - ...sources: {}[] + defaults( + object: any, + ...sources: any[] ): TResult; } @@ -14552,40 +14542,36 @@ declare module _ { /** * @see _.defaults */ - defaults( - source1: S1, - ...sources: {}[] - ): LoDashImplicitObjectWrapper; + defaults( + source: TSource + ): LoDashImplicitObjectWrapper; /** * @see _.defaults */ - defaults( - source1: S1, - source2: S2, - ...sources: {}[] - ): LoDashImplicitObjectWrapper; + defaults( + source1: TSource1, + source2: TSource2 + ): LoDashImplicitObjectWrapper; /** * @see _.defaults */ - defaults( - source1: S1, - source2: S2, - source3: S3, - ...sources: {}[] - ): LoDashImplicitObjectWrapper; + defaults( + source1: TSource1, + source2: TSource2, + source3: TSource3 + ): LoDashImplicitObjectWrapper; /** * @see _.defaults */ - defaults( - source1: S1, - source2: S2, - source3: S3, - source4: S4, - ...sources: {}[] - ): LoDashImplicitObjectWrapper; + defaults( + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4 + ): LoDashImplicitObjectWrapper; /** * @see _.defaults @@ -14595,47 +14581,43 @@ declare module _ { /** * @see _.defaults */ - defaults(...sources: {}[]): LoDashImplicitObjectWrapper; + defaults(...sources: any[]): LoDashImplicitObjectWrapper; } interface LoDashExplicitObjectWrapper { /** * @see _.defaults */ - defaults( - source1: S1, - ...sources: {}[] - ): LoDashExplicitObjectWrapper; + defaults( + source: TSource + ): LoDashExplicitObjectWrapper; /** * @see _.defaults */ - defaults( - source1: S1, - source2: S2, - ...sources: {}[] - ): LoDashExplicitObjectWrapper; + defaults( + source1: TSource1, + source2: TSource2 + ): LoDashExplicitObjectWrapper; /** * @see _.defaults */ - defaults( - source1: S1, - source2: S2, - source3: S3, - ...sources: {}[] - ): LoDashExplicitObjectWrapper; + defaults( + source1: TSource1, + source2: TSource2, + source3: TSource3 + ): LoDashExplicitObjectWrapper; /** * @see _.defaults */ - defaults( - source1: S1, - source2: S2, - source3: S3, - source4: S4, - ...sources: {}[] - ): LoDashExplicitObjectWrapper; + defaults( + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4 + ): LoDashExplicitObjectWrapper; /** * @see _.defaults @@ -14645,7 +14627,7 @@ declare module _ { /** * @see _.defaults */ - defaults(...sources: {}[]): LoDashExplicitObjectWrapper; + defaults(...sources: any[]): LoDashExplicitObjectWrapper; } //_.defaultsDeep @@ -14668,163 +14650,307 @@ declare module _ { defaultsDeep(...sources: any[]): LoDashImplicitObjectWrapper } - //_.extend + // _.extend interface LoDashStatic { /** - * @see assign + * @see _.assignIn */ - extend( + extend( object: TObject, - source: TSource, - customizer?: AssignCustomizer - ): TResult; + source: TSource + ): TObject & TSource; /** - * @see assign + * @see _.assignIn */ - extend( + extend( + object: TObject, + source1: TSource1, + source2: TSource2 + ): TObject & TSource1 & TSource2; + + /** + * @see _.assignIn + */ + extend( object: TObject, source1: TSource1, source2: TSource2, - customizer?: AssignCustomizer - ): TResult; + source3: TSource3 + ): TObject & TSource1 & TSource2 & TSource3; /** - * @see assign + * @see _.assignIn */ - extend( + extend( object: TObject, source1: TSource1, source2: TSource2, source3: TSource3, - customizer?: AssignCustomizer - ): TResult; + source4: TSource4 + ): TObject & TSource1 & TSource2 & TSource3 & TSource4; /** - * @see assign + * @see _.assignIn */ - extend - ( - object: TObject, - source1: TSource1, - source2: TSource2, - source3: TSource3, - source4: TSource4, - customizer?: AssignCustomizer - ): TResult; + extend(object: TObject): TObject; /** - * @see _.assign + * @see _.assignIn */ - extend(object: TObject): TObject; - - /** - * @see _.assign - */ - extend( - object: TObject, ...otherArgs: any[] + extend( + object: any, + ...otherArgs: any[] ): TResult; } interface LoDashImplicitObjectWrapper { /** - * @see _.assign + * @see _.assignIn */ - extend( - source: TSource, - customizer?: AssignCustomizer - ): LoDashImplicitObjectWrapper; + extend( + source: TSource + ): LoDashImplicitObjectWrapper; /** - * @see assign + * @see _.assignIn */ - extend( + extend( + source1: TSource1, + source2: TSource2 + ): LoDashImplicitObjectWrapper; + + /** + * @see _.assignIn + */ + extend( source1: TSource1, source2: TSource2, - customizer?: AssignCustomizer - ): LoDashImplicitObjectWrapper; + source3: TSource3 + ): LoDashImplicitObjectWrapper; /** - * @see assign + * @see _.assignIn */ - extend( + extend( source1: TSource1, source2: TSource2, source3: TSource3, - customizer?: AssignCustomizer - ): LoDashImplicitObjectWrapper; + source4: TSource4 + ): LoDashImplicitObjectWrapper; /** - * @see assign - */ - extend( - source1: TSource1, - source2: TSource2, - source3: TSource3, - source4: TSource4, - customizer?: AssignCustomizer - ): LoDashImplicitObjectWrapper; - - /** - * @see _.assign + * @see _.assignIn */ extend(): LoDashImplicitObjectWrapper; /** - * @see _.assign + * @see _.assignIn */ - extend(...otherArgs: any[]): LoDashImplicitObjectWrapper; + extend(...otherArgs: any[]): LoDashImplicitObjectWrapper; } interface LoDashExplicitObjectWrapper { /** - * @see _.assign + * @see _.assignIn */ - extend( - source: TSource, - customizer?: AssignCustomizer - ): LoDashExplicitObjectWrapper; + extend( + source: TSource + ): LoDashExplicitObjectWrapper; /** - * @see assign + * @see _.assignIn */ - extend( + extend( + source1: TSource1, + source2: TSource2 + ): LoDashExplicitObjectWrapper; + + /** + * @see _.assignIn + */ + extend( source1: TSource1, source2: TSource2, - customizer?: AssignCustomizer - ): LoDashExplicitObjectWrapper; + source3: TSource3 + ): LoDashExplicitObjectWrapper; /** - * @see assign + * @see _.assignIn */ - extend( + extend( source1: TSource1, source2: TSource2, source3: TSource3, - customizer?: AssignCustomizer - ): LoDashExplicitObjectWrapper; + source4: TSource4 + ): LoDashExplicitObjectWrapper; /** - * @see assign - */ - extend( - source1: TSource1, - source2: TSource2, - source3: TSource3, - source4: TSource4, - customizer?: AssignCustomizer - ): LoDashExplicitObjectWrapper; - - /** - * @see _.assign + * @see _.assignIn */ extend(): LoDashExplicitObjectWrapper; /** - * @see _.assign + * @see _.assignIn */ - extend(...otherArgs: any[]): LoDashExplicitObjectWrapper; + extend(...otherArgs: any[]): LoDashExplicitObjectWrapper; + } + + interface LoDashStatic { + /** + * @see _.assignInWith + */ + extendWith( + object: TObject, + source: TSource, + customizer: AssignCustomizer + ): TObject & TSource; + + /** + * @see _.assignInWith + */ + extendWith( + object: TObject, + source1: TSource1, + source2: TSource2, + customizer: AssignCustomizer + ): TObject & TSource1 & TSource2; + + /** + * @see _.assignInWith + */ + extendWith( + object: TObject, + source1: TSource1, + source2: TSource2, + source3: TSource3, + customizer: AssignCustomizer + ): TObject & TSource1 & TSource2 & TSource3; + + /** + * @see _.assignInWith + */ + extendWith( + object: TObject, + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4, + customizer: AssignCustomizer + ): TObject & TSource1 & TSource2 & TSource3 & TSource4; + + /** + * @see _.assignInWith + */ + extendWith(object: TObject): TObject; + + /** + * @see _.assignInWith + */ + extendWith( + object: any, + ...otherArgs: any[] + ): TResult; + } + + interface LoDashImplicitObjectWrapper { + /** + * @see _.assignInWith + */ + extendWith( + source: TSource, + customizer: AssignCustomizer + ): LoDashImplicitObjectWrapper; + + /** + * @see _.assignInWith + */ + extendWith( + source1: TSource1, + source2: TSource2, + customizer: AssignCustomizer + ): LoDashImplicitObjectWrapper; + + /** + * @see _.assignInWith + */ + extendWith( + source1: TSource1, + source2: TSource2, + source3: TSource3, + customizer: AssignCustomizer + ): LoDashImplicitObjectWrapper; + + /** + * @see _.assignInWith + */ + extendWith( + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4, + customizer: AssignCustomizer + ): LoDashImplicitObjectWrapper; + + /** + * @see _.assignInWith + */ + extendWith(): LoDashImplicitObjectWrapper; + + /** + * @see _.assignInWith + */ + extendWith(...otherArgs: any[]): LoDashImplicitObjectWrapper; + } + + interface LoDashExplicitObjectWrapper { + /** + * @see _.assignInWith + */ + extendWith( + source: TSource, + customizer: AssignCustomizer + ): LoDashExplicitObjectWrapper; + + /** + * @see _.assignInWith + */ + extendWith( + source1: TSource1, + source2: TSource2, + customizer: AssignCustomizer + ): LoDashExplicitObjectWrapper; + + /** + * @see _.assignInWith + */ + extendWith( + source1: TSource1, + source2: TSource2, + source3: TSource3, + customizer: AssignCustomizer + ): LoDashExplicitObjectWrapper; + + /** + * @see _.assignInWith + */ + extendWith( + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4, + customizer: AssignCustomizer + ): LoDashExplicitObjectWrapper; + + /** + * @see _.assignInWith + */ + extendWith(): LoDashExplicitObjectWrapper; + + /** + * @see _.assignInWith + */ + extendWith(...otherArgs: any[]): LoDashExplicitObjectWrapper; } //_.findKey @@ -19907,15 +20033,12 @@ declare module "lodash/extend" { export = extend; } -/** -* uncoment it if definition exists -*/ -/* + declare module "lodash/extendWith" { const extendWith: typeof _.extendWith; export = extendWith; } -*/ + declare module "lodash/add" { const add: typeof _.add; From b32c4f463dce4e9506d7aa9ab219e917b711499a Mon Sep 17 00:00:00 2001 From: Yonezawa-T2 Date: Tue, 24 May 2016 22:56:40 +0900 Subject: [PATCH 123/402] Updates kii-cloud-sdk v2.4.3 -> v2.4.4. (#9400) Adds `getPendingEmailAddress` and `getPendingPhoneNumber`. --- kii-cloud-sdk/kii-cloud-sdk.d.ts | 40 +++++++++++++++++++++++++++++--- 1 file changed, 37 insertions(+), 3 deletions(-) diff --git a/kii-cloud-sdk/kii-cloud-sdk.d.ts b/kii-cloud-sdk/kii-cloud-sdk.d.ts index 970061e8d1..550aa736fa 100644 --- a/kii-cloud-sdk/kii-cloud-sdk.d.ts +++ b/kii-cloud-sdk/kii-cloud-sdk.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Kii Cloud SDK v2.4.3 +// Type definitions for Kii Cloud SDK v2.4.4 // Project: http://en.kii.com/ // Definitions by: Kii Consortium // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -6059,6 +6059,18 @@ declare namespace KiiCloud { */ getEmailAddress(): string; + /** + * Get the email of this user that has not been verified. + * When the user's email has been changed and email verification is required in you app configuration, + * New email is stored as pending email. + * After the new email has been verified, the address can be obtained by {@link KiiUser.getEmailAddress} + * + * @return User's new email address has not been verified. + * null if no pending email field is included in refresh + * response or undefined when no refresh operation has been done before. + */ + getPendingEmailAddress(): string; + /** * Get the phone number associated with this user * @@ -6066,6 +6078,18 @@ declare namespace KiiCloud { */ getPhoneNumber(): string; + /** + * Get the phone of this user that has not been verified. + * When the user's phone has been changed and phone verification is required in you app configuration, + * New phone is stored as pending phone. + * After the new phone has been verified, the address can be obtained by {@link KiiUser.getPhoneNumber} + * + * @return User's new phone number has not been verified. + * null if no pending phone field is included in refresh + * response or undefined when no refresh operation has been done before. + */ + getPendingPhoneNumber(): string; + /** * Get the country code associated with this user * @@ -7126,7 +7150,12 @@ declare namespace KiiCloud { ownerOfGroups(callbacks?: { success(theUser: KiiUser, groupList: KiiGroup[]): any; failure(theUser: KiiUser, anErrorString: string): any; }): Promise<[KiiUser, KiiGroup[]]>; /** - * Updates the user's phone number on the server + * Change phone number of logged in user. + * If the phone number verification is required by your app configuration, + * User's phone number would not changed to new one until the new phone number verification has been done. + * In this case, new phone can be obtained by {@link KiiUser#getPendingPhoneNumber()}. + * This API does not refresh the KiiUser automatically. + * Please execute {@link KiiUser#refresh()} before checking the value of {@link KiiUser#getPhoneNumber()} or {@link KiiUser#getPendingPhoneNumber()}. * * @param newPhoneNumber The new phone number to change to * @param callbacks An object with callback methods defined @@ -7169,7 +7198,12 @@ declare namespace KiiCloud { changePhone(newPhoneNumber: string, callbacks?: { success(theUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; }): Promise; /** - * Updates the user's email address on the server + * Change email of logged in user. + * If the email address verification is required by your app configuration, + * User's email would not changed to new one until the new email verification has been done. + * In this case, new mail address can be obtained by {@link KiiUser#getPendingEmailAddress()}. + * This API does not refresh the KiiUser automatically. + * Please execute {@link KiiUser#refresh()} before checking the value of {@link KiiUser#getEmailAddress()} or {@link KiiUser#getPendingEmailAddress()} * * @param newEmail The new email address to change to * @param callbacks An object with callback methods defined From 10dc219acc06f971dd55530fc7b02969bd52a5a6 Mon Sep 17 00:00:00 2001 From: Dmitry Pesterev Date: Tue, 24 May 2016 19:00:13 +0500 Subject: [PATCH 124/402] Updated jquery.tooltipster to 3.3.0 (#9406) * Definitions for jquery.tooltipster 3.3.0 * Updated tests to test type union in content * Version --- .../jquery.tooltipster-tests.ts | 10 +++-- jquery.tooltipster/jquery.tooltipster.d.ts | 41 ++++++++++++++----- 2 files changed, 37 insertions(+), 14 deletions(-) diff --git a/jquery.tooltipster/jquery.tooltipster-tests.ts b/jquery.tooltipster/jquery.tooltipster-tests.ts index 8a8f29acae..21a5446c12 100644 --- a/jquery.tooltipster/jquery.tooltipster-tests.ts +++ b/jquery.tooltipster/jquery.tooltipster-tests.ts @@ -1,8 +1,8 @@ /// -// Type definition tests for jQuery Tooltipster 3.0.5 +// Type definition tests for jQuery Tooltipster 3.3.0 // Project: https://github.com/iamceege/tooltipster -// Definitions by: Patrick Magee +// Definitions by: Patrick Magee , Dmitry Pesterev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // Tests taken from the getting started section of the Tooltipster website @@ -13,6 +13,10 @@ $(document).ready(function () { $('#my-tooltip').tooltipster({ content: $(' This text is in bold case !') }); + + $('#my-tooltip').tooltipster({ + content: 'string test' + }); }); @@ -191,4 +195,4 @@ $(document).ready(function () { }); }); -$('#my-special-tooltip').tooltipster('content', 'My new content'); \ No newline at end of file +$('#my-special-tooltip').tooltipster('content', 'My new content'); diff --git a/jquery.tooltipster/jquery.tooltipster.d.ts b/jquery.tooltipster/jquery.tooltipster.d.ts index a4df0a36e3..13260f15fe 100644 --- a/jquery.tooltipster/jquery.tooltipster.d.ts +++ b/jquery.tooltipster/jquery.tooltipster.d.ts @@ -1,6 +1,6 @@ -// Type definitions for jQuery Tooltipster 3.0.5 +// Type definitions for jQuery Tooltipster 3.3.0 // Project: https://github.com/iamceege/tooltipster -// Definitions by: Patrick Magee +// Definitions by: Patrick Magee , Dmitry Pesterev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -21,14 +21,13 @@ interface JQueryTooltipsterOptions { */ arrowColor?: any; /** - * If autoClose is set to false, the tooltip will never close unless you call the 'close' method yourself. Default: true + * If autoClose is set to false, the tooltip will never close unless you call the 'hide' method yourself. Default: true */ autoClose?: boolean; /** * If set, this will override the content of the tooltip. Default: null - * @type string, jQuery object */ - content?: any; + content?: string | JQuery; /** * If the content of the tooltip is provided as a string, it is displayed as plain text by default. If this content should actually be interpreted as HTML, set this option to true. Default: false */ @@ -38,15 +37,19 @@ interface JQueryTooltipsterOptions { */ contentCloning?: boolean; /** + * Tooltipster logs notices into the console when you're doing something you ideally shouldn't be doing. Set to false to disable logging. Default: true + */ + debug?: boolean; + /** * Delay how long it takes (in milliseconds) for the tooltip to start animating in. Default: 200 */ delay?: number; /** - * Set a fixed width for the tooltip. The tooltip will always be a consistent width - no matter your content size. Default: 0 (auto width) + * Set a minimum width for the tooltip. Default: 0 (auto width) */ - fixedWidth?: number; + minWidth?: number; /** - * Set a max width for the tooltip. If the tooltip ends up being smaller than the set max width, the tooltip's width will be set automatically. Default: 0 (no max width) + * Set a maximum width for the tooltip. Default: null (no max width) */ maxWidth?: number; /** @@ -66,10 +69,13 @@ interface JQueryTooltipsterOptions { */ functionAfter?: (origin) => void; /** - * If using the iconDesktop or iconTouch options, this sets the content for your icon. Default: '(?)' - * @type string, jQuery object + * If true, the tooltip will close if its origin is clicked. This option only applies when 'trigger' is 'hover' and 'autoClose' is false. Default: false */ - icon?: any; + hideOnClick?: boolean; + /** + * If using the iconDesktop or iconTouch options, this sets the content for your icon. Default: '(?)' + */ + icon?: string | JQuery; /** * If you provide a jQuery object to the 'icon' option, this sets if it is a clone of this object that should actually be used. Default: true */ @@ -95,6 +101,10 @@ interface JQueryTooltipsterOptions { */ interactiveTolerance?: number; /** + * Allows you to put multiple tooltips on a single element. Read further instructions down this page. Default: false + */ + multiple?: boolean; + /** * Offsets the tooltip (in pixels) farther left/right from the origin. Default: 0 */ offsetX?: number; @@ -116,6 +126,15 @@ interface JQueryTooltipsterOptions { */ positionTracker?: boolean; /** + * Called after the tooltip has been repositioned by the position tracker (if enabled). Default: A function that will close the tooltip if the trigger is 'hover' and autoClose is false. + */ + positionTrackerCallback?: (origin) => void; + /** + * Specify if a TITLE attribute should be restored on the HTML element after a call to the 'destroy' method. This attribute may be omitted, or be restored with the value that existed before Tooltipster was initialized, or be restored with the stringified value of the current content. Note: in case of multiple tooltips on a single element, only the last destroyed tooltip may trigger a restoration. Default: 'current' + * 'none', 'previous' or 'current' + */ + restoration?: string; + /** * Set the speed of the animation. Default: 350 */ speed?: number; From dfa9185e5b2004b3a1fa7538a943df309ec115c8 Mon Sep 17 00:00:00 2001 From: Timofey Kachalov Date: Tue, 24 May 2016 17:00:38 +0300 Subject: [PATCH 125/402] Escodegen precedence (#9402) * Added Precedence enum * Added test for Precedence enum * Added Precedence enum * fixed test --- escodegen/escodegen-tests.ts | 2 ++ escodegen/escodegen.d.ts | 29 +++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/escodegen/escodegen-tests.ts b/escodegen/escodegen-tests.ts index 247ea2e02d..f6c18cf5cd 100644 --- a/escodegen/escodegen-tests.ts +++ b/escodegen/escodegen-tests.ts @@ -49,6 +49,8 @@ let generateOptions: escodegen.GenerateOptions = { verbatim: " " }; +let precedence: escodegen.Precedence = escodegen.Precedence.Primary; + let myCode: string = escodegen.generate({}, generateOptions); let ast: any = escodegen.attachComments({}, {}, {}); diff --git a/escodegen/escodegen.d.ts b/escodegen/escodegen.d.ts index dac9311c6b..b72cfdedc6 100644 --- a/escodegen/escodegen.d.ts +++ b/escodegen/escodegen.d.ts @@ -135,6 +135,35 @@ declare module 'escodegen' { */ verbatim?: string; } + + /** + * https://github.com/estools/escodegen/commit/adf113333cd4888cf59bfc4f957df98bf7db82b6 + */ + export enum Precedence { + Sequence, + Yield, + Await, + Assignment, + Conditional, + ArrowFunction, + LogicalOR, + LogicalAND, + BitwiseOR, + BitwiseXOR, + BitwiseAND, + Equality, + Relational, + BitwiseSHIFT, + Additive, + Multiplicative, + Unary, + Postfix, + Call, + New, + TaggedTemplate, + Member, + Primary + } /** * Produces given Abstract Syntax Tree as javascript code From ffe35810b4b38652bbb9f890f57555337e7da0c8 Mon Sep 17 00:00:00 2001 From: Dan Marshall Date: Tue, 24 May 2016 07:01:41 -0700 Subject: [PATCH 126/402] Maker.js 0.8.0 and Bezier-js (#9408) * Added definitions for Bezier.Js * updates for maker.js and bezier.js * removed copyright * deleted bezierjs * Added definitions for Bezier.Js * updates for maker.js and bezier.js * deleted bezierjs * changed name to DefinitelyTyped * update tests for 0.8.0 * rename to bezier-js * add pdfkit reference * public clockwise --- bezier-js/bezier-js-tests.ts | 95 +++++ bezier-js/bezier-js.d.ts | 197 +++++++++++ maker.js/makerjs-tests.ts | 11 +- maker.js/makerjs.d.ts | 661 +++++++++++++++++++++++++++++------ 4 files changed, 849 insertions(+), 115 deletions(-) create mode 100644 bezier-js/bezier-js-tests.ts create mode 100644 bezier-js/bezier-js.d.ts diff --git a/bezier-js/bezier-js-tests.ts b/bezier-js/bezier-js-tests.ts new file mode 100644 index 0000000000..1814d67dc0 --- /dev/null +++ b/bezier-js/bezier-js-tests.ts @@ -0,0 +1,95 @@ +/// + +function test() { + + var bezierjs: typeof BezierJs; + + var bezier = new bezierjs.Bezier([1,2,3,4]); + var cap = new bezierjs.BezierCap([]); + var point: BezierJs.Point = { x: 0, y: 0 }; + var utils = bezier.getUtils(); + var line: BezierJs.Line = { p1: { x:0, y: 0}, p2: {x:1, y: 1}}; + var abc: BezierJs.ABC = { A: null, B: null, C: null }; + var arc: BezierJs.Arc = { e: 0, s: 0, x: 0, y: 0, r: 1 }; + var bbox: BezierJs.BBox = bezier.bbox(); + var closest: BezierJs.Closest = { mdist: 1, mpos: 0 }; + var inflection: BezierJs.Inflection = { values: null, x: [0], y: [0], z:[0] }; + var minmax: BezierJs.MinMax = { min: 0, max: 0 }; + var offset: BezierJs.Offset = { x: 0, y: 0, c: point, n: point }; + var pair: BezierJs.Pair = { left: bezier, right: bezier }; + var poly: BezierJs.PolyBezier = bezier.outline(1); + var projection: BezierJs.Projection = { x: 0, y: 0, t: 9, d: 4 }; + var shape: BezierJs.Shape = { startcap: cap, endcap: cap, forward: bezier, back: bezier, bbox: bbox }; + var split: BezierJs.Split = { left: bezier, right: bezier, span: [point] }; + + bezier.arcs(); + bezier.clockwise; + bezier.compute(.5); + bezier.computedirection(); + bezier.curveintersects([bezier], [bezier]); + bezier.derivative(0); + bezier.get(1); + bezier.getLUT()[0].x; + bezier.hull(0); + bezier.inflections().values; + bezier.intersects(bezier); + bezier.length(); + bezier.lineIntersects(line); + bezier.normal(0); + bezier.offset(1,2); + bezier.on(point, 0); + bezier.order = 5; + bezier.outlineshapes(1,3); + bezier.overlaps(bezier); + bezier.point(9); + bezier.project(point); + bezier.raise(); + bezier.reduce(); + bezier.scale(4); + bezier.selfintersects(); + bezier.simple(); + bezier.split(0, 1); + bezier.toSVG(); + bezier.update(); + + cap.virtual = true; + + poly.addCurve(bezier); + poly.bbox(); + poly.curve(7); + poly.curves[0]._3d; + poly.length(); + poly.offset(9).points[0].y; + poly.points[0]; + + utils.abcratio(0, 1); + utils.align([point], line); + utils.angle(point, point, point); + utils.approximately(5, 7, .001); + utils.arcfn(1, function(){}); + utils.bboxoverlap(bbox, bbox); + utils.between(0, 0, 1); + utils.closest([point], point); + utils.copy({}); + utils.dist(point, point); + utils.droots([9]); + utils.expandbox(bbox, bbox); + utils.findbbox([bezier]); + utils.getccenter(point, point, point); + utils.getminmax(bezier, 'x', [0]); + utils.length(function(){}); + utils.lerp(1, point, point); + utils.lli(offset, offset); + utils.lli4(point, point, point, point); + utils.lli8(0, 0, 0, 0, 0, 0, 0, 0); + utils.makeline(point, point); + utils.makeshape(bezier, bezier); + utils.map(0, 0, 0, 0, 0); + utils.pairiteration(bezier, bezier); + utils.pointsToString([point]); + utils.projectionratio(0, 0); + utils.roots([point], line); + utils.round(.999, .001); + utils.shapeintersections(shape, bbox, shape, bbox); + +} \ No newline at end of file diff --git a/bezier-js/bezier-js.d.ts b/bezier-js/bezier-js.d.ts new file mode 100644 index 0000000000..7d54a19d95 --- /dev/null +++ b/bezier-js/bezier-js.d.ts @@ -0,0 +1,197 @@ +// Type definitions for Bezier.js +// Project: https://github.com/Pomax/bezierjs +// Definitions by: Dan Marshall +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare module BezierJs { + interface Point { + x: number; + y: number; + z?: number; + } + interface Projection extends Point { + t?: number; + d?: number; + } + interface Inflection { + x: number[]; + y: number[]; + z?: number[]; + values: number[]; + } + interface Offset extends Point { + c: Point; + n: Point; + } + interface Pair { + left: Bezier; + right: Bezier; + } + interface Split extends Pair { + span: Point[]; + _t1?: number; + _t2?: number; + } + interface MinMax { + min: number; + mid?: number; + max: number; + size?: number; + } + interface BBox { + x: MinMax; + y: MinMax; + z?: MinMax; + } + interface Line { + p1: Point; + p2: Point; + } + interface Arc extends Point { + e: number; + r: number; + s: number; + } + interface Shape { + startcap: BezierCap; + forward: Bezier; + back: Bezier; + endcap: BezierCap; + bbox: BBox; + } + interface ABC { + A: Point; + B: Point; + C: Point; + } + interface Closest { + mdist: number; + mpos: number; + } + /** + * Bezier curve constructor. The constructor argument can be one of three things: + * + * 1. array/4 of {x:..., y:..., z:...}, z optional + * 2. numerical array/8 ordered x1,y1,x2,y2,x3,y3,x4,y4 + * 3. numerical array/12 ordered x1,y1,z1,x2,y2,z2,x3,y3,z3,x4,y4,z4 + * + */ + class Bezier { + clockwise: boolean; + private _linear; + _3d: boolean; + _t1: number; + _t2: number; + _lut: Point[]; + dpoints: Point[][]; + order: number; + points: Point[]; + dims: string[]; + dimlen: number; + constructor(points: Point[]); + constructor(coords: number[]); + constructor(n1: number, n2: number, n3: number, n4: number, n5: number, n6: number, n7: number, n8: number); + constructor(p1: Point, p2: Point, p3: Point, p4?: Point); + static fromSVG(svgString: string): Bezier; + static getABC(n: number, S: Point, B: Point, E: Point, t: number): ABC; + static quadraticFromPoints(p1: Point, p2: Point, p3: Point, t: number): Bezier; + static cubicFromPoints(S: Point, B: Point, E: Point, t: number, d1: number): Bezier; + static getUtils(): typeof utils; + getUtils(): typeof utils; + valueOf(): string; + toString(): string; + toSVG(): string; + update(): void; + computedirection(): void; + length(): number; + getLUT(steps?: number): Point[]; + on(point: Point, error: number): number; + project(point: Point): Projection; + get(t: number): Point; + point(idx: number): Point; + compute(t: number): Point; + raise(): Bezier; + derivative(t: number): Point; + inflections(): number[]; + normal(t: number): Point; + private __normal2(t); + private __normal3(t); + private __normal(t); + hull(t: number): Point[]; + split(t1: number, t2?: number): Bezier | Split; + extrema(): Inflection; + bbox(): BBox; + overlaps(curve: Bezier): boolean; + offset(t: number, d?: number): Offset | Bezier[]; + simple(): boolean; + reduce(): any[]; + scale(d: Function): Bezier; + scale(d: number): Bezier; + outline(d1: number, d2?: number, d3?: number, d4?: number): PolyBezier; + outlineshapes(d1: number, d2: number): Shape[]; + intersects(curve: Bezier): string[] | number[]; + intersects(curve: Line): string[] | number[]; + lineIntersects(line: Line): number[]; + selfintersects(): string[]; + curveintersects(c1: Bezier[], c2: Bezier[]): string[]; + arcs(errorThreshold?: number): Arc[]; + private _error(pc, np1, s, e); + private _iterate(errorThreshold, circles); + } + class BezierCap extends Bezier { + virtual: boolean; + } +} +declare module BezierJs.utils { + var Tvalues: number[]; + var Cvalues: number[]; + function arcfn(t: number, derivativeFn: Function): number; + function between(v: number, m: number, M: number): boolean; + function approximately(a: number, b: number, precision?: number): boolean; + function length(derivativeFn: Function): number; + function map(v: number, ds: number, de: number, ts: number, te: number): number; + function lerp(r: number, v1: Point, v2: Point): Point; + function pointToString(p: Point): string; + function pointsToString(points: Point[]): string; + function copy(obj: Object): any; + function angle(o: Point, v1: Point, v2: Point): number; + function round(v: number, d: number): number; + function dist(p1: Point, p2: Point): number; + function closest(LUT: Point[], point: Point): Closest; + function abcratio(t: number, n: number): number; + function projectionratio(t: number, n: number): number; + function lli8(x1: number, y1: number, x2: number, y2: number, x3: number, y3: number, x4: number, y4: number): Point; + function lli4(p1: Point, p2: Point, p3: Point, p4: Point): Point; + function lli(v1: Offset, v2: Offset): Point; + function makeline(p1: Point, p2: Point): Bezier; + function findbbox(sections: Bezier[]): BBox; + function shapeintersections(s1: Shape, bbox1: BBox, s2: Shape, bbox2: BBox): string[][] | number[][]; + function makeshape(forward: Bezier, back: Bezier): Shape; + function getminmax(curve: Bezier, d: string, list: number[]): MinMax; + function align(points: Point[], line: Line): Point[]; + function roots(points: Point[], line: Line): number[]; + function droots(p: number[]): number[]; + function inflections(points: Point[]): number[]; + function bboxoverlap(b1: BBox, b2: BBox): boolean; + function expandbox(bbox: BBox, _bbox: BBox): void; + function pairiteration(c1: Bezier, c2: Bezier): string[]; + function getccenter(p1: Point, p2: Point, p3: Point): Arc; +} +declare module BezierJs { + /** + * Poly Bezier + * @param {[type]} curves [description] + */ + class PolyBezier { + curves: Bezier[]; + private _3d; + points: Point[]; + constructor(curves: Bezier[]); + valueOf(): string; + toString(): string; + addCurve(curve: Bezier): void; + length(): number; + curve(idx: number): Bezier; + bbox(): BBox; + offset(d: number): PolyBezier; + } +} diff --git a/maker.js/makerjs-tests.ts b/maker.js/makerjs-tests.ts index e314f09669..ef32f885ff 100644 --- a/maker.js/makerjs-tests.ts +++ b/maker.js/makerjs-tests.ts @@ -25,11 +25,11 @@ function test() { } function testAngle() { - makerjs.angle.areEqual(12, 13); makerjs.angle.mirror(45, true, false); makerjs.angle.noRevolutions(90); makerjs.angle.ofArcEnd(paths.arc); makerjs.angle.ofArcMiddle(paths.arc); + makerjs.angle.ofArcSpan(paths.arc); makerjs.angle.ofLineInDegrees(paths.line); makerjs.angle.ofPointInDegrees([0,0], [1,1]); makerjs.angle.ofPointInRadians([0,0], [1,1]); @@ -67,7 +67,9 @@ function test() { } function testMeasure() { - makerjs.measure.arcAngle(paths.arc); + makerjs.measure.isPointEqual(p1, p2); + makerjs.measure.isPathEqual(paths.line, paths.circle, 4); + makerjs.measure.isAngleEqual(12, 13); makerjs.measure.isArcConcaveTowardsPoint(paths.arc, [0,0]); makerjs.measure.isBetween(7, 8, 9, false); makerjs.measure.isBetweenArcAngles(7, paths.arc, false); @@ -119,7 +121,6 @@ function test() { } function testPath() { - makerjs.path.areEqual(paths.line, paths.circle, 4); makerjs.path.breakAtPoint(paths.arc, [0,0]).type; makerjs.path.dogbone(paths.line, paths.line, 7); makerjs.path.fillet(paths.arc, paths.line, 4); @@ -129,7 +130,6 @@ function test() { makerjs.path.moveRelative(paths.circle, [0,0]); makerjs.path.rotate(paths.line, 5, [0,0]); makerjs.path.scale(paths.arc, 8); - makerjs.path.slopeIntersectionPoint(paths.line, paths.line); } function testPaths() { @@ -156,8 +156,6 @@ function test() { function testPoint() { makerjs.point.add(p1, p2); - makerjs.point.areEqual(p1, p2); - makerjs.point.areEqualRounded(p1, p2); makerjs.point.average(p1, p2); makerjs.point.clone(p1); makerjs.point.closest([0,0], [p1, p2]); @@ -170,7 +168,6 @@ function test() { makerjs.point.rotate(p1, 5, p2); makerjs.point.rounded(p1); makerjs.point.scale(p2, 8); - makerjs.point.serialize(p1); makerjs.point.subtract(p2, p1); makerjs.point.zero(); } diff --git a/maker.js/makerjs.d.ts b/maker.js/makerjs.d.ts index fdfade36da..28db25f854 100644 --- a/maker.js/makerjs.d.ts +++ b/maker.js/makerjs.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/Microsoft/maker.js // Definitions by: Dan Marshall // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// /** * Root module for Maker.js. * @@ -37,6 +38,13 @@ declare namespace MakerJs { * @param accuracy Optional exemplar of number of decimal places. */ function round(n: number, accuracy?: number): number; + /** + * Create a string representation of a route array. + * + * @param route Array of strings which are segments of a route. + * @returns String of the flattened array. + */ + function createRouteKey(route: string[]): string; /** * Clone an object. * @@ -89,6 +97,12 @@ declare namespace MakerJs { */ high: IPoint; } + /** + * A map of measurements. + */ + interface IMeasureMap { + [key: string]: IMeasure; + } /** * A line, curved line or other simple two dimensional shape. */ @@ -181,7 +195,6 @@ declare namespace MakerJs { function isPathArc(item: any): boolean; /** * A map of functions which accept a path as a parameter. - * @private */ interface IPathFunctionMap { /** @@ -191,7 +204,6 @@ declare namespace MakerJs { } /** * A map of functions which accept a path and an origin point as parameters. - * @private */ interface IPathOriginFunctionMap { /** @@ -213,10 +225,31 @@ declare namespace MakerJs { Circle: string; Arc: string; }; + /** + * Slope and y-intercept of a line. + */ + interface ISlope { + /** + * Boolean to see if line has slope or is vertical. + */ + hasSlope: boolean; + /** + * Optional value of non-vertical slope. + */ + slope?: number; + /** + * Line used to calculate this slope. + */ + line: IPathLine; + /** + * Optional value of y when x = 0. + */ + yIntercept?: number; + } /** * Options to pass to path.intersection() */ - interface IPathIntersectionOptions { + interface IPathIntersectionBaseOptions { /** * Optional boolean to only return deep intersections, i.e. not on an end point or tangent. */ @@ -226,6 +259,19 @@ declare namespace MakerJs { */ out_AreOverlapped?: boolean; } + /** + * Options to pass to path.intersection() + */ + interface IPathIntersectionOptions extends IPathIntersectionBaseOptions { + /** + * Optional boolean to only return deep intersections, i.e. not on an end point or tangent. + */ + path1Offset?: IPoint; + /** + * Optional output variable which will be set to true if the paths are overlapped. + */ + path2Offset?: IPoint; + } /** * An intersection of two paths. */ @@ -268,6 +314,14 @@ declare namespace MakerJs { * Point which is known to be outside of the model. */ farPoint?: IPoint; + /** + * Cached measurements for model A. + */ + measureA?: measure.Atlas; + /** + * Cached measurements for model B. + */ + measureB?: measure.Atlas; } /** * Options to pass to model.findLoops. @@ -278,6 +332,19 @@ declare namespace MakerJs { */ removeFromOriginal?: boolean; } + /** + * Options to pass to model.simplify() + */ + interface ISimplifyOptions { + /** + * Optional + */ + pointMatchingDistance?: number; + /** + * Optional + */ + scalarMatchingDistance?: number; + } /** * A path that may be indicated to "flow" in either direction between its endpoints. */ @@ -370,11 +437,104 @@ declare namespace MakerJs { pathId: string; } /** - * Path and its reference id within a model + * A route to either a path or a model, and the absolute offset of it. */ - interface IRefPathInModel extends IRefPathIdInModel { + interface IRouteOffset { + layer: string; + offset: IPoint; + route: string[]; + routeKey: string; + } + /** + * A path reference in a walk. + */ + interface IWalkPath extends IRefPathIdInModel, IRouteOffset { pathContext: IPath; } + /** + * Callback signature for path in model.walk(). + */ + interface IWalkPathCallback { + (context: IWalkPath): void; + } + /** + * A link in a chain, with direction of flow. + */ + interface IChainLink { + /** + * Reference to the path. + */ + walkedPath: IWalkPath; + /** + * Path flows forwards or reverse. + */ + reversed: boolean; + /** + * The endpoints of the path, in absolute coords. + */ + endPoints: IPoint[]; + } + /** + * A chain of paths which connect end to end. + */ + interface IChain { + /** + * The links in this chain. + */ + links: IChainLink[]; + /** + * Flag if this chain forms a loop end to end. + */ + endless?: boolean; + } + /** + * Callback to model.findChains() with resulting array of chains and unchained paths. + */ + interface IChainCallback { + (chains: IChain[], loose: IWalkPath[], layer: string): void; + } + /** + * Options to pass to model.findLoops. + */ + interface IFindChainsOptions extends IPointMatchOptions { + /** + * Flag to separate chains by layers. + */ + byLayers?: boolean; + } + /** + * Reference to a model within a model. + */ + interface IRefModelInModel { + parentModel: IModel; + childId: string; + childModel: IModel; + } + /** + * A model reference in a walk. + */ + interface IWalkModel extends IRefModelInModel, IRouteOffset { + } + /** + * Callback signature for model.walk(). + */ + interface IWalkModelCallback { + (context: IWalkModel): void; + } + /** + * Callback signature for model.walk(), which may return false to halt any further walking. + */ + interface IWalkModelCancellableCallback { + (context: IWalkModel): boolean; + } + /** + * Options to pass to model.walk(). + */ + interface IWalkOptions { + onPath?: IWalkPathCallback; + beforeChildWalk?: IWalkModelCancellableCallback; + afterChildWalk?: IWalkModelCallback; + } /** * Describes a parameter and its limits. */ @@ -425,14 +585,6 @@ declare namespace MakerJs { } } declare namespace MakerJs.angle { - /** - * Find out if two angles are equal. - * - * @param a First angle. - * @param b Second angle. - * @returns true if angles are the same, false if they are not - */ - function areEqual(angle1: number, angle2: number, accuracy?: number): boolean; /** * Ensures an angle is not greater than 360 * @@ -469,6 +621,13 @@ declare namespace MakerJs.angle { * @returns Middle angle of arc. */ function ofArcMiddle(arc: IPathArc, ratio?: number): number; + /** + * Total angle of an arc between its start and end angles. + * + * @param arc The arc to measure. + * @returns Angle of arc. + */ + function ofArcSpan(arc: IPathArc): number; /** * Angle of a line path. * @@ -512,23 +671,6 @@ declare namespace MakerJs.point { * @returns A new point object. */ function add(a: IPoint, b: IPoint, subtract?: boolean): IPoint; - /** - * Find out if two points are equal. - * - * @param a First point. - * @param b Second point. - * @returns true if points are the same, false if they are not - */ - function areEqual(a: IPoint, b: IPoint, withinDistance?: number): boolean; - /** - * Find out if two points are equal after rounding. - * - * @param a First point. - * @param b Second point. - * @param accuracy Optional exemplar of number of decimal places. - * @returns true if points are the same, false if they are not - */ - function areEqualRounded(a: IPoint, b: IPoint, accuracy?: number): boolean; /** * Get the average of two points. * @@ -580,7 +722,16 @@ declare namespace MakerJs.point { * @param pathContext The path object. * @returns Array with 2 elements: [0] is the point object corresponding to the origin, [1] is the point object corresponding to the end. */ - function fromPathEnds(pathContext: IPath): IPoint[]; + function fromPathEnds(pathContext: IPath, pathOffset?: IPoint): IPoint[]; + /** + * Calculates the intersection of slopes of two lines. + * + * @param lineA First line to use for slope. + * @param lineB Second line to use for slope. + * @param options Optional IPathIntersectionOptions. + * @returns point of intersection of the two slopes, or null if the slopes did not intersect. + */ + function fromSlopeIntersection(lineA: IPathLine, lineB: IPathLine, options?: IPathIntersectionBaseOptions): IPoint; /** * Get the middle point of a path. * @@ -623,14 +774,6 @@ declare namespace MakerJs.point { * @returns A new point. */ function scale(pointToScale: IPoint, scaleValue: number): IPoint; - /** - * Get a string representation of a point. - * - * @param pointContext The point to serialize. - * @param accuracy Optional exemplar of number of decimal places. - * @returns String representing the point. - */ - function serialize(pointContext: IPoint, accuracy?: number): string; /** * Subtract a point from another point, and return the result as a new point. Shortcut to Add(a, b, subtract = true). * @@ -649,13 +792,12 @@ declare namespace MakerJs.point { } declare namespace MakerJs.path { /** - * Find out if two paths are equal. + * Create a clone of a path. This is faster than cloneObject. * - * @param a First path. - * @param b Second path. - * @returns true if paths are the same, false if they are not + * @param pathToClone The path to clone. + * @returns Cloned path. */ - function areEqual(path1: IPath, path2: IPath, withinPointDistance?: number): boolean; + function clone(pathToClone: IPath): IPath; /** * Create a clone of a path, mirrored on either or both x and y axes. * @@ -679,9 +821,18 @@ 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). */ - function moveRelative(pathToMove: IPath, delta: IPoint): IPath; + function moveRelative(pathToMove: IPath, delta: IPoint, subtract?: boolean): IPath; + /** + * Move some paths relatively during a task execution, then unmove them. + * + * @param pathsToMove The paths to move. + * @param deltas The x & y adjustments as a point object array. + * @param task The function to call while the paths are temporarily moved. + */ + function moveTemporary(pathsToMove: IPath[], deltas: IPoint[], task: Function): void; /** * Rotate a path. * @@ -715,11 +866,6 @@ declare namespace MakerJs.path { declare namespace MakerJs.paths { /** * Class for arc path. - * - * @param origin The center point of the arc. - * @param radius The radius of the arc. - * @param startAngle The start angle of the arc. - * @param endAngle The end angle of the arc. */ class Arc implements IPathArc { origin: IPoint; @@ -727,19 +873,71 @@ declare namespace MakerJs.paths { startAngle: number; endAngle: number; type: string; + /** + * Class for arc path, created from origin point, radius, start angle, and end angle. + * + * @param origin The center point of the arc. + * @param radius The radius of the arc. + * @param startAngle The start angle of the arc. + * @param endAngle The end angle of the arc. + */ constructor(origin: IPoint, radius: number, startAngle: number, endAngle: number); + /** + * Class for arc path, created from 2 points, radius, large Arc flag, and clockwise flag. + * + * @param pointA First end point of the arc. + * @param pointB Second end point of the arc. + * @param radius The radius of the arc. + * @param largeArc Boolean flag to indicate clockwise direction. + * @param clockwise Boolean flag to indicate clockwise direction. + */ + constructor(pointA: IPoint, pointB: IPoint, radius: number, largeArc: boolean, clockwise: boolean); + /** + * Class for arc path, created from 2 points and optional boolean flag indicating clockwise. + * + * @param pointA First end point of the arc. + * @param pointB Second end point of the arc. + * @param clockwise Boolean flag to indicate clockwise direction. + */ + constructor(pointA: IPoint, pointB: IPoint, clockwise?: boolean); + /** + * Class for arc path, created from 3 points. + * + * @param pointA First end point of the arc. + * @param pointB Middle point on the arc. + * @param pointC Second end point of the arc. + */ + constructor(pointA: IPoint, pointB: IPoint, pointC: IPoint); } /** * Class for circle path. - * - * @param origin The center point of the circle. - * @param radius The radius of the circle. */ class Circle implements IPathCircle { + type: string; origin: IPoint; radius: number; - type: string; + /** + * Class for circle path, created from origin point and radius. + * + * @param origin The center point of the circle. + * @param radius The radius of the circle. + */ constructor(origin: IPoint, radius: number); + /** + * Class for circle path, created from 2 points. + * + * @param pointA First point on the circle. + * @param pointB Second point on the circle. + */ + constructor(pointA: IPoint, pointB: IPoint); + /** + * Class for circle path, created from 3 points. + * + * @param pointA First point on the circle. + * @param pointB Second point on the circle. + * @param pointC Third point on the circle. + */ + constructor(pointA: IPoint, pointB: IPoint, pointC: IPoint); } /** * Class for line path. @@ -832,6 +1030,14 @@ declare namespace MakerJs.model { * @returns The original model (for chaining). */ function moveRelative(modelToMove: IModel, delta: IPoint): IModel; + /** + * Prefix the ids of paths in a model. + * + * @param modelToPrefix The model to prefix. + * @param prefix The prefix to prepend on paths ids. + * @returns The original model (for chaining). + */ + function prefixPathIds(modelToPrefix: IModel, prefix: string): IModel; /** * Rotate a model. * @@ -865,6 +1071,15 @@ declare namespace MakerJs.model { * @param callback Callback for each path. */ function walkPaths(modelContext: IModel, callback: IModelPathCallback): void; + /** + * Recursively walk through all paths for a given model. + * + * @param modelContext The model to walk. + * @param pathCallback Callback for each path. + * @param modelCallbackBeforeWalk Callback for each model prior to recursion, which can cancel the recursion if it returns false. + * @param modelCallbackAfterWalk Callback for each model after recursion. + */ + function walk(modelContext: IModel, options: IWalkOptions): void; } declare namespace MakerJs.model { /** @@ -875,7 +1090,7 @@ declare namespace MakerJs.model { * @param farPoint Optional point of reference which is outside the bounds of the modelContext. * @returns Boolean true if the path is inside of the modelContext. */ - function isPathInsideModel(pathContext: IPath, modelContext: IModel, farPoint?: IPoint): boolean; + function isPathInsideModel(pathContext: IPath, modelContext: IModel, pathOffset?: IPoint, farPoint?: IPoint, measureAtlas?: measure.Atlas): boolean; /** * Break a model's paths everywhere they intersect with another path. * @@ -884,7 +1099,7 @@ declare namespace MakerJs.model { */ function breakPathsAtIntersections(modelToBreak: IModel, modelToIntersect?: IModel): void; /** - * Combine 2 models. The models should be originated, and every path within each model should be part of a loop. + * Combine 2 models. * * @param modelA First model to combine. * @param modelB Second model to combine. @@ -896,6 +1111,106 @@ declare namespace MakerJs.model { * @param farPoint Optional point of reference which is outside the bounds of both models. */ function combine(modelA: IModel, modelB: IModel, includeAInsideB?: boolean, includeAOutsideB?: boolean, includeBInsideA?: boolean, includeBOutsideA?: boolean, options?: ICombineOptions): void; + /** + * Combine 2 models, resulting in a intersection. + * + * @param modelA First model to combine. + * @param modelB Second model to combine. + */ + function combineIntersection(modelA: IModel, modelB: IModel): void; + /** + * Combine 2 models, resulting in a subtraction of B from A. + * + * @param modelA First model to combine. + * @param modelB Second model to combine. + */ + function combineSubtraction(modelA: IModel, modelB: IModel): void; + /** + * Combine 2 models, resulting in a union. + * + * @param modelA First model to combine. + * @param modelB Second model to combine. + */ + function combineUnion(modelA: IModel, modelB: IModel): void; +} +declare namespace MakerJs { + /** + * Compare keys to see if they are equal. + */ + interface ICollectionKeyComparer { + (a: K, b: K): boolean; + } + /** + * A collection for items that share a common key. + */ + interface ICollection { + key: K; + items: T[]; + } + /** + * Collects items that share a common key. + */ + class Collector { + private comparer; + collections: ICollection[]; + constructor(comparer?: ICollectionKeyComparer); + addItemToCollection(key: K, item: T): void; + findCollection(key: K, action?: (index: number) => void): T[]; + removeCollection(key: K): boolean; + removeItemFromCollection(key: K, item: T): boolean; + getCollectionsOfMultiple(cb: (key: K, items: T[]) => void): void; + } +} +declare namespace MakerJs.model { + /** + * Simplify a model's paths by reducing redundancy: combine multiple overlapping paths into a single path. The model must be originated. + * + * @param modelContext The originated model to search for similar paths. + * @param options Optional options object. + * @returns The simplified model (for chaining). + */ + function simplify(modelToSimplify: IModel, options?: ISimplifyOptions): IModel; +} +declare namespace MakerJs.path { + /** + * Expand path by creating a model which surrounds it. + * + * @param pathToExpand Path to expand. + * @param expansion Distance to expand. + * @param isolateCaps Optional flag to put the end caps into a separate model named "caps". + * @returns Model which surrounds the path. + */ + function expand(pathToExpand: IPath, expansion: number, isolateCaps?: boolean): IModel; + /** + * Represent an arc using straight lines. + * + * @param arc Arc to straighten. + * @param bevel Optional flag to bevel the angle to prevent it from being too sharp. + * @param prefix Optional prefix to apply to path ids. + * @returns Model of straight lines with same endpoints as the arc. + */ + function straighten(arc: IPathArc, bevel?: boolean, prefix?: string): IModel; +} +declare namespace MakerJs.model { + /** + * Expand all paths in a model, then combine the resulting expansions. + * + * @param modelToExpand Model to expand. + * @param distance Distance to expand. + * @param joints Number of points at a joint between paths. Use 0 for round joints, 1 for pointed joints, 2 for beveled joints. + * @returns Model which surrounds the paths of the original model. + */ + function expandPaths(modelToExpand: IModel, distance: number, joints?: number, combineOptions?: ICombineOptions): IModel; + /** + * Outline a model by a specified distance. Useful for accommodating for kerf. + * + * @param modelToOutline Model to outline. + * @param distance Distance to outline. + * @param joints Number of points at a joint between paths. Use 0 for round joints, 1 for pointed joints, 2 for beveled joints. + * @param inside Optional boolean to draw lines inside the model instead of outside. + * @returns Model which surrounds the paths outside of the original model. + */ + function outline(modelToOutline: IModel, distance: number, joints?: number, inside?: boolean): IModel; } declare namespace MakerJs.units { /** @@ -909,12 +1224,48 @@ declare namespace MakerJs.units { } declare namespace MakerJs.measure { /** - * Total angle of an arc between its start and end angles. + * Find out if two angles are equal. * - * @param arc The arc to measure. - * @returns Angle of arc. + * @param angleA First angle. + * @param angleB Second angle. + * @returns true if angles are the same, false if they are not */ - function arcAngle(arc: IPathArc): number; + function isAngleEqual(angleA: number, angleB: number, accuracy?: number): boolean; + /** + * Find out if two paths are equal. + * + * @param pathA First path. + * @param pathB Second path. + * @returns true if paths are the same, false if they are not + */ + function isPathEqual(pathA: IPath, pathB: IPath, withinPointDistance?: number, pathAOffset?: IPoint, pathBOffset?: IPoint): boolean; + /** + * Find out if two points are equal. + * + * @param a First point. + * @param b Second point. + * @returns true if points are the same, false if they are not + */ + function isPointEqual(a: IPoint, b: IPoint, withinDistance?: number): boolean; + /** + * Check for slope equality. + * + * @param slopeA The ISlope to test. + * @param slopeB The ISlope to check for equality. + * @returns Boolean true if slopes are equal. + */ + function isSlopeEqual(slopeA: ISlope, slopeB: ISlope): boolean; +} +declare namespace MakerJs.measure { + /** + * Increase a measurement by an additional measurement. + * + * @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). + */ + function increase(baseMeasure: IMeasure, addMeasure: IMeasure): IMeasure; /** * Check for arc being concave or convex towards a given point. * @@ -923,16 +1274,25 @@ declare namespace MakerJs.measure { * @returns Boolean true if arc is concave towards point. */ function isArcConcaveTowardsPoint(arc: IPathArc, towardsPoint: IPoint): boolean; + /** + * Check for arc overlapping another arc. + * + * @param arcA The arc to test. + * @param arcB The arc to check for overlap. + * @param excludeTangents Boolean to exclude exact endpoints and only look for deep overlaps. + * @returns Boolean true if arc1 is overlapped with arcB. + */ + function isArcOverlapping(arcA: IPathArc, arcB: IPathArc, excludeTangents: boolean): boolean; /** * Check if a given number is between two given limits. * * @param valueInQuestion The number to test. - * @param limit1 First limit. - * @param limit2 Second limit. + * @param limitA First limit. + * @param limitB Second limit. * @param exclusive Flag to exclude equaling the limits. * @returns Boolean true if value is between (or equal to) the limits. */ - function isBetween(valueInQuestion: number, limit1: number, limit2: number, exclusive: boolean): boolean; + function isBetween(valueInQuestion: number, limitA: number, limitB: number, exclusive: boolean): boolean; /** * Check if a given angle is between an arc's start and end angles. * @@ -951,6 +1311,27 @@ declare namespace MakerJs.measure { * @returns Boolean true if point is between (or equal to) the line's origin and end points. */ function isBetweenPoints(pointInQuestion: IPoint, line: IPathLine, exclusive: boolean): boolean; + /** + * Check for line overlapping another line. + * + * @param lineA The line to test. + * @param lineB The line to check for overlap. + * @param excludeTangents Boolean to exclude exact endpoints and only look for deep overlaps. + * @returns Boolean true if line1 is overlapped with lineB. + */ + function isLineOverlapping(lineA: IPathLine, lineB: IPathLine, excludeTangents: boolean): boolean; + /** + * Check for measurement overlapping another measurement. + * + * @param measureA The measurement to test. + * @param measureB The measurement to check for overlap. + * @returns Boolean true if measure1 is overlapped with measureB. + */ + function isMeasurementOverlapping(measureA: IMeasure, measureB: IMeasure): boolean; + /** + * Gets the slope of a line. + */ + function lineSlope(line: IPathLine): ISlope; /** * Calculates the distance between two points. * @@ -965,7 +1346,7 @@ declare namespace MakerJs.measure { * @param pathToMeasure The path to measure. * @returns object with low and high points. */ - function pathExtents(pathToMeasure: IPath): IMeasure; + function pathExtents(pathToMeasure: IPath, addOffset?: IPoint): IMeasure; /** * Measures the length of a path. * @@ -977,9 +1358,38 @@ declare namespace MakerJs.measure { * Measures the smallest rectangle which contains a model. * * @param modelToMeasure The model to measure. + * @param atlas Optional atlas to save measurements. * @returns object with low and high points. */ - function modelExtents(modelToMeasure: IModel): IMeasure; + function modelExtents(modelToMeasure: IModel, atlas?: measure.Atlas): IMeasure; + /** + * A list of maps of measurements. + * + * @param modelToMeasure The model to measure. + * @param atlas Optional atlas to save measurements. + * @returns object with low and high points. + */ + class Atlas { + modelContext: IModel; + /** + * Flag that models have been measured. + */ + modelsMeasured: boolean; + /** + * Map of model measurements, mapped by routeKey. + */ + modelMap: IMeasureMap; + /** + * Map of path measurements, mapped by routeKey. + */ + pathMap: IMeasureMap; + /** + * Constructor. + * @param modelContext The model to measure. + */ + constructor(modelContext: IModel); + measureModels(): void; + } } declare namespace MakerJs.exporter { /** @@ -1050,12 +1460,12 @@ declare namespace MakerJs.solvers { /** * Solves for the angle of a triangle when you know lengths of 3 sides. * - * @param length1 Length of side of triangle, opposite of the angle you are trying to find. - * @param length2 Length of any other side of the triangle. - * @param length3 Length of the remaining side of the triangle. + * @param lengthA Length of side of triangle, opposite of the angle you are trying to find. + * @param lengthB Length of any other side of the triangle. + * @param lengthC Length of the remaining side of the triangle. * @returns Angle opposite of the side represented by the first parameter. */ - function solveTriangleSSS(length1: number, length2: number, length3: number): number; + function solveTriangleSSS(lengthA: number, lengthB: number, lengthC: number): number; /** * Solves for the length of a side of a triangle when you know length of one side and 2 angles. * @@ -1076,33 +1486,24 @@ declare namespace MakerJs.path { * @returns IPathIntersection object, with points(s) of intersection (and angles, when a path is an arc or circle); or null if the paths did not intersect. */ function intersection(path1: IPath, path2: IPath, options?: IPathIntersectionOptions): IPathIntersection; - /** - * Calculates the intersection of slopes of two lines. - * - * @param line1 First line to use for slope. - * @param line2 Second line to use for slope. - * @param options Optional IPathIntersectionOptions. - * @returns point of intersection of the two slopes, or null if the slopes did not intersect. - */ - function slopeIntersectionPoint(line1: IPathLine, line2: IPathLine, options?: IPathIntersectionOptions): IPoint; } declare namespace MakerJs.path { /** * Adds a round corner to the outside angle between 2 lines. The lines must meet at one point. * - * @param line1 First line to fillet, which will be modified to fit the fillet. - * @param line2 Second line to fillet, which will be modified to fit the fillet. + * @param lineA First line to fillet, which will be modified to fit the fillet. + * @param lineB Second line to fillet, which will be modified to fit the fillet. * @returns Arc path object of the new fillet. */ - function dogbone(line1: IPathLine, line2: IPathLine, filletRadius: number, options?: IPointMatchOptions): IPathArc; + function dogbone(lineA: IPathLine, lineB: IPathLine, filletRadius: number, options?: IPointMatchOptions): IPathArc; /** * Adds a round corner to the inside angle between 2 paths. The paths must meet at one point. * - * @param path1 First path to fillet, which will be modified to fit the fillet. - * @param path2 Second path to fillet, which will be modified to fit the fillet. + * @param pathA First path to fillet, which will be modified to fit the fillet. + * @param pathB Second path to fillet, which will be modified to fit the fillet. * @returns Arc path object of the new fillet. */ - function fillet(path1: IPath, path2: IPath, filletRadius: number, options?: IPointMatchOptions): IPathArc; + function fillet(pathA: IPath, pathB: IPath, filletRadius: number, options?: IPointMatchOptions): IPathArc; } declare namespace MakerJs.kit { /** @@ -1123,22 +1524,15 @@ declare namespace MakerJs.kit { } declare namespace MakerJs.model { /** - * @private + * Find paths that have common endpoints and form chains. + * + * @param modelContext The model to search for chains. + * @param options Optional options object. + * @returns A list of chains. */ - interface IPointMappedItem { - averagePoint: IPoint; - item: T; - } - /** - * @private - */ - class PointMap { - matchingDistance: number; - list: IPointMappedItem[]; - constructor(matchingDistance?: number); - add(pointToAdd: IPoint, item: T): void; - find(pointToFind: IPoint, saveAverage: boolean): T; - } + function findChains(modelContext: IModel, callback: IChainCallback, options?: IFindChainsOptions): void; +} +declare namespace MakerJs.model { /** * Find paths that have common endpoints and form loops. * @@ -1153,7 +1547,14 @@ declare namespace MakerJs.model { * @param loopToDetach The model to search for loops. */ function detachLoop(loopToDetach: IModel): void; - function removeDeadEnds(modelContext: IModel, pointMatchingDistance?: number): void; + /** + * Remove paths from a model which have endpoints that do not connect to other paths. + * + * @param modelContext The model to search for dead ends. + * @param options Optional options object. + * @returns The input model (for chaining). + */ + function removeDeadEnds(modelContext: IModel, pointMatchingDistance?: number): IModel; } declare namespace MakerJs.exporter { /** @@ -1249,6 +1650,37 @@ declare namespace MakerJs.exporter { } } declare namespace MakerJs.exporter { + /** + * Injects drawing into a PDFKit document. + * + * @param modelToExport Model object to export. + * @param options Export options object. + * @returns String of PDF file contents. + */ + function toPDF(doc: PDFKit.PDFDocument, modelToExport: IModel, options?: IPDFRenderOptions): void; + /** + * PDF rendering options. + */ + interface IPDFRenderOptions extends IExportOptions { + /** + * Rendered reference origin. + */ + origin?: IPoint; + /** + * SVG color of the rendered paths. + */ + stroke?: string; + } +} +declare namespace MakerJs.exporter { + /** + * Convert a chain to SVG path data. + */ + function chainToSVGPathData(chain: IChain, offset: IPoint): string; + /** + * Convert a path to SVG path data. + */ + function pathToSVGPathData(pathToExport: IPath, offset: IPoint, offset2: IPoint): string; function toSVG(modelToExport: IModel, options?: ISVGRenderOptions): string; function toSVG(pathsToExport: IPath[], options?: ISVGRenderOptions): string; function toSVG(pathToExport: IPath, options?: ISVGRenderOptions): string; @@ -1273,6 +1705,10 @@ declare namespace MakerJs.exporter { * Optional attributes to add to the root svg tag. */ svgAttrs?: IXmlTagAttrs; + /** + * SVG fill color. + */ + fill?: string; /** * SVG font size and font size units. */ @@ -1314,9 +1750,11 @@ declare namespace MakerJs.models { } } declare namespace MakerJs.models { - class Polygon extends ConnectTheDots { - constructor(numberOfSides: number, radius: number, firstCornerAngleInDegrees?: number); - static getPoints(numberOfSides: number, radius: number, firstCornerAngleInDegrees?: number): IPoint[]; + class Polygon implements IModel { + paths: IPathMap; + constructor(numberOfSides: number, radius: number, firstCornerAngleInDegrees?: number, circumscribed?: boolean); + static circumscribedRadius(radius: number, angleInRadians: number): number; + static getPoints(numberOfSides: number, radius: number, firstCornerAngleInDegrees?: number, circumscribed?: boolean): IPoint[]; } } declare namespace MakerJs.models { @@ -1344,19 +1782,24 @@ declare namespace MakerJs.models { } } declare namespace MakerJs.models { - class Oval extends RoundRectangle { + class Oval implements IModel { + paths: IPathMap; constructor(width: number, height: number); } } declare namespace MakerJs.models { class OvalArc implements IModel { paths: IPathMap; - constructor(startAngle: number, endAngle: number, sweepRadius: number, slotRadius: number, selfIntersect?: boolean); + models: IModelMap; + constructor(startAngle: number, endAngle: number, sweepRadius: number, slotRadius: number, selfIntersect?: boolean, isolateCaps?: boolean); } } declare namespace MakerJs.models { - class Rectangle extends ConnectTheDots { + class Rectangle implements IModel { + paths: IPathMap; + origin: IPoint; constructor(width: number, height: number); + constructor(measurement: IMeasure); } } declare namespace MakerJs.models { @@ -1375,11 +1818,13 @@ declare namespace MakerJs.models { class Slot implements IModel { paths: IPathMap; origin: IPoint; - constructor(origin: IPoint, endPoint: IPoint, radius: number); + models: IModelMap; + constructor(origin: IPoint, endPoint: IPoint, radius: number, isolateCaps?: boolean); } } declare namespace MakerJs.models { - class Square extends Rectangle { + class Square implements IModel { + paths: IPathMap; constructor(side: number); } } From 4eb951c3079978734ce0b1055ee3f21026bf17dd Mon Sep 17 00:00:00 2001 From: William Comartin Date: Tue, 24 May 2016 10:10:12 -0400 Subject: [PATCH 127/402] Adding Definitions for js-quantities (#9411) * Add js-quantities library definitions * Change Module to Namespace * Remove intl-tel-input --- js-quantities/js-quantities-tests.ts | 9 ++++ js-quantities/js-quantities.d.ts | 79 ++++++++++++++++++++++++++++ 2 files changed, 88 insertions(+) create mode 100644 js-quantities/js-quantities-tests.ts create mode 100644 js-quantities/js-quantities.d.ts diff --git a/js-quantities/js-quantities-tests.ts b/js-quantities/js-quantities-tests.ts new file mode 100644 index 0000000000..c8d00eef53 --- /dev/null +++ b/js-quantities/js-quantities-tests.ts @@ -0,0 +1,9 @@ +/// + +var Val1 = Qty('1 m') + +var Val2 = Qty(1); + +var Val3 = Qty(1, 'm'); + +var Val4 = Qty(Val1); \ No newline at end of file diff --git a/js-quantities/js-quantities.d.ts b/js-quantities/js-quantities.d.ts new file mode 100644 index 0000000000..a2e3c2d96c --- /dev/null +++ b/js-quantities/js-quantities.d.ts @@ -0,0 +1,79 @@ +// Type definitions for JS-quantities +// Project: http://gentooboontoo.github.io/js-quantities/ +// Definitions by: William Comartin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare var Qty: QtyModule.QtyStatic; + +declare namespace QtyModule { + interface QtyStatic { + (value: string): Qty; + (value: number): Qty; + (value: number, unit: string): Qty; + (value: Qty): Qty; + } + + interface Qty { + version: string; + + scalar: number; + baseScalar: number; + + parse(value: string): Qty; + + swiftConverter(srcUnits:string, dstUnits:string): (value:number) => number; + + getkinds(): string[]; + + getUnits(kind:string): string[]; + + getAliases(unitName:string): string[]; + + formatter(scalar:number, units:string):string; + + toFloat(): number; + + isUnitless(): boolean; + + isCompatible(other:string|Qty): boolean; + + isInverse(other:string|Qty): boolean + + kind(): string; + + isBase(): boolean; + + toBase(): Qty; + + units(): string; + + eq(other:Qty): boolean; + lt(other:Qty): boolean; + lte(other:Qty): boolean; + gt(other:Qty): boolean; + gte(other:Qty): boolean; + + toPrec(precQuantity: Qty|string|number): Qty; + + toString(targetUnitsOrMaxDecimalsOrPrec?:number|string|Qty, maxDecimals?: number): string; + + format(targetUnits?:string, formatter?:(scalar:number, units:string) => string): string; + + compareTo(other:Qty|string): number; + + same(other: Qty): boolean; + + inverse(): Qty; + + isDegrees(): boolean; + + isTemperature(): boolean; + + to(other:string|Qty): Qty; + + add(other:string|Qty): Qty; + sub(other:string|Qty): Qty; + mul(other:number|string|Qty): Qty; + div(other:number|string|Qty): Qty; + } +} \ No newline at end of file From 587f9d9cb018514c03434ccc0fc53ffcad32e8b7 Mon Sep 17 00:00:00 2001 From: Tamir Duberstein Date: Tue, 24 May 2016 10:20:46 -0400 Subject: [PATCH 128/402] isomorphic-fetch,whatwg-fetch: Add ArrayBuffer to BodyInit (#9387) * isomorphic-fetch: whitespace * isomorphic-fetch: Add ArrayBuffer{,View} to BodyInit Relevant specs: BodyInit: https://fetch.spec.whatwg.org/#bodyinit BufferSource: https://heycam.github.io/webidl/#common-BufferSource * whatwg-fetch: Add ArrayBuffer{,View} to BodyInit Relevant specs: BodyInit: https://fetch.spec.whatwg.org/#bodyinit BufferSource: https://heycam.github.io/webidl/#common-BufferSource --- isomorphic-fetch/isomorphic-fetch.d.ts | 14 +++++++------- whatwg-fetch/whatwg-fetch.d.ts | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/isomorphic-fetch/isomorphic-fetch.d.ts b/isomorphic-fetch/isomorphic-fetch.d.ts index 0edbe24afb..19754db0f1 100644 --- a/isomorphic-fetch/isomorphic-fetch.d.ts +++ b/isomorphic-fetch/isomorphic-fetch.d.ts @@ -4,23 +4,23 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare enum RequestContext { - "audio", "beacon", "cspreport", "download", "embed", "eventsource", - "favicon", "fetch", "font", "form", "frame", "hyperlink", "iframe", - "image", "imageset", "import", "internal", "location", "manifest", - "object", "ping", "plugin", "prefetch", "script", "serviceworker", + "audio", "beacon", "cspreport", "download", "embed", "eventsource", + "favicon", "fetch", "font", "form", "frame", "hyperlink", "iframe", + "image", "imageset", "import", "internal", "location", "manifest", + "object", "ping", "plugin", "prefetch", "script", "serviceworker", "sharedworker", "subresource", "style", "track", "video", "worker", "xmlhttprequest", "xslt" } declare enum RequestMode { "same-origin", "no-cors", "cors" } declare enum RequestCredentials { "omit", "same-origin", "include" } -declare enum RequestCache { - "default", "no-store", "reload", "no-cache", "force-cache", +declare enum RequestCache { + "default", "no-store", "reload", "no-cache", "force-cache", "only-if-cached" } declare enum ResponseType { "basic", "cors", "default", "error", "opaque" } declare type HeaderInit = Headers | Array; -declare type BodyInit = Blob | FormData | string; +declare type BodyInit = ArrayBuffer | ArrayBufferView | Blob | FormData | string; declare type RequestInfo = Request | string; interface RequestInit { diff --git a/whatwg-fetch/whatwg-fetch.d.ts b/whatwg-fetch/whatwg-fetch.d.ts index b1e667650f..8997ab6917 100644 --- a/whatwg-fetch/whatwg-fetch.d.ts +++ b/whatwg-fetch/whatwg-fetch.d.ts @@ -82,7 +82,7 @@ interface ResponseInit { } declare type HeaderInit = Headers|Array; -declare type BodyInit = Blob|FormData|string; +declare type BodyInit = ArrayBuffer|ArrayBufferView|Blob|FormData|string; declare type RequestInfo = Request|string; interface Window { From 9d184d8b22f961c127df21f4a338e9e9d641a615 Mon Sep 17 00:00:00 2001 From: Victor Costan Date: Tue, 24 May 2016 07:21:30 -0700 Subject: [PATCH 129/402] backbone.radio: add module definition (#9413) --- backbone.radio/backbone.radio-tests.ts | 8 +++++++- backbone.radio/backbone.radio.d.ts | 6 ++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/backbone.radio/backbone.radio-tests.ts b/backbone.radio/backbone.radio-tests.ts index 295c552af2..764fb65943 100644 --- a/backbone.radio/backbone.radio-tests.ts +++ b/backbone.radio/backbone.radio-tests.ts @@ -101,4 +101,10 @@ function TestGlobalApiAndChannels() { Backbone.Radio.reply('auth', 'authenticate', onStart); Backbone.Radio.request('auth', 'authenticate', 'pelle', 42); -} \ No newline at end of file +} + +import Radio = require('backbone.radio'); +function TestImport() { + var channel: Backbone.Radio.Channel = Radio.channel('channel-name'); + channel.command('show:view'); +} diff --git a/backbone.radio/backbone.radio.d.ts b/backbone.radio/backbone.radio.d.ts index 50895b0275..dd049ec1fe 100644 --- a/backbone.radio/backbone.radio.d.ts +++ b/backbone.radio/backbone.radio.d.ts @@ -90,3 +90,9 @@ declare namespace Backbone { } } } + +declare module 'backbone.radio' { + import Backbone = require('backbone'); + + export = Backbone.Radio; +} From f2b2aeb303d2d8c9d0114ce754a6a8179c6e99ca Mon Sep 17 00:00:00 2001 From: Tom Wanzek Date: Tue, 24 May 2016 10:23:55 -0400 Subject: [PATCH 130/402] Added missing exports for format and compile functions to support custom named formats (#9364) * Added exports for functions format(name: string, fmt: string | Function): Function and compile(format: string): Function to morgan namespace. These fnctions are exported in the morgan js module and can be used in conjunction with the token function to create named custom formats. Inncluded tests. * Added interface definitions to clarify the signatures of callback function used in defining custom tokens (TokenCallbackFn) with morgan.token(...). Added interface definitions to clarify signatures of custom format functions returned by morgan.compile(...) and used as arguments to morgan.format(...) and morgan(...). Added interface Morgan to clarify return type of morgan.token(...), morgan.compile(...) and morgan.format(...). For a detailed discussion of the rationale of there changes see comments in pull request #9364. Updated tests. Updated version reference to morgan 1.7.0. --- morgan/morgan-tests.ts | 57 ++++++++++++++++++- morgan/morgan.d.ts | 122 +++++++++++++++++++++++++++++++++++++++-- 2 files changed, 173 insertions(+), 6 deletions(-) diff --git a/morgan/morgan-tests.ts b/morgan/morgan-tests.ts index 4a0df99024..f26784c848 100644 --- a/morgan/morgan-tests.ts +++ b/morgan/morgan-tests.ts @@ -4,6 +4,7 @@ */ import morgan = require('morgan'); +import express = require('express'); // a pre-defined name morgan('combined') @@ -15,8 +16,8 @@ morgan('tiny') morgan(':remote-addr :method :url') // a custom function -morgan(function (req, res) { - return req.method + ' ' + req.url +morgan(function (tokens, req, res) { + return req.method + ' ' + req.url + ' ' + tokens['date'](req, res, 'iso'); // use predefined :date[iso] token with format argument }) morgan('combined', { @@ -29,3 +30,55 @@ morgan('combined', { } } }); + + +// test interface definition for morgan +var morgan2 : morgan.Morgan = morgan; + +// a named custom format defined as string (example: extend 'tiny' format with user-agent token) +morgan.format('tiny-extended', ':method :url :status :res[content-length] - :response-time ms :user-agent'); + + +// a named custom format defined using the Function signature (example: extend 'dev' format with user-agent token) + +// extend morgan.FormatFn interface with memoizer property to avoid unnecessary re-compiling +// of status-code range driven colorized format functions +interface IFormatFnIndexer { + [memoizerName: string]: morgan.FormatFn; +} + +interface IExtendedFormatFn extends morgan.FormatFn { + memoizer?: IFormatFnIndexer; +} + + +var developmentExtendedFormatLine : IExtendedFormatFn = function(tokens, req, res):string { + + // get the status code if response written + var status = res.statusCode + ? res.statusCode + : undefined; + + // get status color + var color = status >= 500 ? 31 // red + : status >= 400 ? 33 // yellow + : status >= 300 ? 36 // cyan + : status >= 200 ? 32 // green + : 0; // no color + + // get colored format function, if previously memoized, otherwise undefined + var fn: morgan.FormatFn = developmentExtendedFormatLine.memoizer[color]; + + if (!fn) { + // compile + fn = developmentExtendedFormatLine.memoizer[color] = morgan.compile('\x1b[0m:method :url \x1b[' + + color + 'm:status \x1b[0m:response-time ms - :res[content-length]\x1b[0m :user-agent'); + } + + return fn(tokens, req, res); +}; + +developmentExtendedFormatLine.memoizer = {}; + + +morgan.format('dev-extended', developmentExtendedFormatLine); diff --git a/morgan/morgan.d.ts b/morgan/morgan.d.ts index bf1e840956..8a985b5a1c 100644 --- a/morgan/morgan.d.ts +++ b/morgan/morgan.d.ts @@ -1,4 +1,4 @@ -// Type definitions for morgan 1.2.2 +// Type definitions for morgan 1.7.0 // Project: https://github.com/expressjs/morgan // Definitions by: James Roland Cabresos // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -10,7 +10,114 @@ declare module "morgan" { namespace morgan { - export function token(name: string, callback: (req: express.Request, res: express.Response) => T): express.RequestHandler; + export interface FormatFn extends Function { + (tokens: TokenIndexer, req: express.Request, res: express.Response): string; + } + + export interface TokenCallbackFn extends Function { + (req: express.Request, res: express.Response, arg?: string | number | boolean): string; + } + + export interface TokenIndexer { + [tokenName: string]: TokenCallbackFn; + } + + /** + * Public interface of morgan logger + */ + export interface Morgan { + /*** + * Create a new morgan logger middleware function using the given format and options. The format argument may be a string of a predefined name (see below for the names), + * or a string of a format string containing defined tokens. + * @param format + * @param options + */ + (format: string, options?: Options): express.RequestHandler; + /*** + * Standard Apache combined log output. + * :remote-addr - :remote-user [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent" + * @param format + * @param options + */ + (format: 'combined', options?: Options): express.RequestHandler; + /*** + * Standard Apache common log output. + * :remote-addr - :remote-user [:date] ":method :url HTTP/:http-version" :status :res[content-length] + * @param format + * @param options + */ + (format: 'common', options?: Options): express.RequestHandler; + /** + * Concise output colored by response status for development use. The :status token will be colored red for server error codes, yellow for client error codes, cyan for redirection codes, and uncolored for all other codes. + * :method :url :status :response-time ms - :res[content-length] + * @param format + * @param options + */ + (format: 'dev', options?: Options): express.RequestHandler; + + /*** + * Shorter than default, also including response time. + * :remote-addr :remote-user :method :url HTTP/:http-version :status :res[content-length] - :response-time ms + * @param format + * @param options + */ + (format: 'short', options?: Options): express.RequestHandler; + + /*** + * The minimal output. + * :method :url :status :res[content-length] - :response-time ms + * @param format + * @param options + */ + (format: 'tiny', options?: Options): express.RequestHandler; + + /*** + * Create a new morgan logger middleware function using the given format and options. The format argument may be a + * custom format function which adheres to the signature. + * @param format + * @param options + */ + (format: FormatFn, options?: Options): express.RequestHandler; + + /** + * Define a custom token which can be used in custom morgan logging formats. + */ + token(name: string, callback: TokenCallbackFn): Morgan; + /** + * Define a named custom format by specifying a format string in token notation + */ + format(name: string, fmt: string): Morgan; + + /** + * Define a named custom format by specifying a format function + */ + format(name: string, fmt: FormatFn): Morgan; + + /** + * Compile a format string in token notation into a format function + */ + compile(format: string): FormatFn; + } + + /** + * Define a custom token which can be used in custom morgan logging formats. + */ + export function token(name: string, callback: TokenCallbackFn): Morgan; + + /** + * Define a named custom format by specifying a format string in token notation + */ + export function format(name: string, fmt: string): Morgan; + + /** + * Define a named custom format by specifying a format function + */ + export function format(name: string, fmt: FormatFn): Morgan; + + /** + * Compile a format string in token notation into a format function + */ + export function compile(format: string): FormatFn; export interface StreamOptions { /** @@ -48,7 +155,8 @@ declare module "morgan" { } /*** - * Create a new morgan logger middleware function using the given format and options. The format argument may be a string of a predefined name (see below for the names), a string of a format string, or a function that will produce a log entry. + * Create a new morgan logger middleware function using the given format and options. The format argument may be a string of a predefined name (see below for the names), + * or a string of a format string containing defined tokens. * @param format * @param options */ @@ -94,7 +202,13 @@ declare module "morgan" { */ function morgan(format: 'tiny', options?: morgan.Options): express.RequestHandler; - function morgan(custom: (req: express.Request, res: express.Response) => string): express.RequestHandler + /*** + * Create a new morgan logger middleware function using the given format and options. The format argument may be a + * custom format function which adheres to the signature. + * @param format + * @param options + */ + function morgan(format: morgan.FormatFn, options?: morgan.Options): express.RequestHandler export = morgan; } From 4248c2618591b7e85a9bece7cff5bd6bd518af10 Mon Sep 17 00:00:00 2001 From: Chitoku Date: Tue, 24 May 2016 23:24:03 +0900 Subject: [PATCH 131/402] Add FileCallback and PerRouteMiddleware (#9374) * Add FileCallback and PerRouteMiddleware * Use import syntax in ECMAScript 6 --- browser-sync/browser-sync-tests.ts | 2 +- browser-sync/browser-sync.d.ts | 27 +++++++++++++++++++-------- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/browser-sync/browser-sync-tests.ts b/browser-sync/browser-sync-tests.ts index 822c941d9f..72bcb6465e 100644 --- a/browser-sync/browser-sync-tests.ts +++ b/browser-sync/browser-sync-tests.ts @@ -1,5 +1,5 @@ /// -import browserSync = require("browser-sync"); +import * as browserSync from "browser-sync"; (() => { //make sure that the interfaces are correctly exposed diff --git a/browser-sync/browser-sync.d.ts b/browser-sync/browser-sync.d.ts index 3bc083d1f1..00d234f958 100644 --- a/browser-sync/browser-sync.d.ts +++ b/browser-sync/browser-sync.d.ts @@ -8,10 +8,10 @@ /// declare module "browser-sync" { - import chokidar = require("chokidar"); - import fs = require("fs"); - import http = require("http"); - import mm = require("micromatch"); + import * as chokidar from "chokidar"; + import * as fs from "fs"; + import * as http from "http"; + import * as mm from "micromatch"; namespace browserSync { interface Options { @@ -23,14 +23,14 @@ declare module "browser-sync" { * weinre.port - Default: 8080 * Note: requires at least version 2.0.0 */ - ui?: UIOptions; + ui?: UIOptions | boolean; /** * Browsersync can watch your files as you work. Changes you make will either be injected into the page (CSS * & images) or will cause all browsers to do a full-page refresh. See anymatch for more information on glob * patterns. * Default: false */ - files?: string | string[]; + files?: string | (string | FileCallback)[]; /** * File watching options that get passed along to Chokidar. Check their docs for available options * Default: undefined @@ -245,7 +245,7 @@ declare module "browser-sync" { * Note: requires at least version 1.6.2 */ socket?: SocketOptions; - middleware?: MiddlewareHandler | MiddlewareHandler[]; + middleware?: MiddlewareHandler | PerRouteMiddleware | (MiddlewareHandler | PerRouteMiddleware)[]; } interface Hash { @@ -261,6 +261,12 @@ declare module "browser-sync" { }; } + interface FileCallback { + match?: string | string[]; + fn: (event: string, file: string) => any; + options?: chokidar.WatchOptions; + } + interface ServerOptions { /** set base directory */ baseDir?: string | string[]; @@ -274,7 +280,7 @@ declare module "browser-sync" { */ routes?: Hash; /** configure custom middleware */ - middleware?: MiddlewareHandler[]; + middleware?: (MiddlewareHandler | PerRouteMiddleware)[]; } interface ProxyOptions { @@ -289,6 +295,11 @@ declare module "browser-sync" { (req: http.ServerRequest, res: http.ServerResponse, next: Function): any; } + interface PerRouteMiddleware { + route: string; + handle: MiddlewareHandler; + } + interface GhostOptions { clicks?: boolean; scroll?: boolean; From 8d252184e421915fbc9f56a5debcb098e0d2d68d Mon Sep 17 00:00:00 2001 From: Tanguy Krotoff Date: Tue, 24 May 2016 16:24:29 +0200 Subject: [PATCH 132/402] Allow ES6 import syntax for wolfy87-eventemitter.d.ts (#9415) * Boostrap -> Bootstrap * Allow ES6 import syntax for wolfy87-eventemitter.d.ts See https://github.com/Microsoft/TypeScript/issues/5073 --- redux-bootstrap/redux-bootstrap.d.ts | 4 ++-- wolfy87-eventemitter/wolfy87-eventemitter-tests.ts | 5 ++--- wolfy87-eventemitter/wolfy87-eventemitter.d.ts | 3 ++- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/redux-bootstrap/redux-bootstrap.d.ts b/redux-bootstrap/redux-bootstrap.d.ts index b7873b0793..933fa988a7 100644 --- a/redux-bootstrap/redux-bootstrap.d.ts +++ b/redux-bootstrap/redux-bootstrap.d.ts @@ -9,7 +9,7 @@ declare module "redux-bootstrap" { - interface BoostrapOptions { + interface BootstrapOptions { routes: JSX.Element; reducers: ReducersOption; middlewares?: Redux.Middleware[]; @@ -27,5 +27,5 @@ declare module "redux-bootstrap" { [index: string]: Redux.Reducer; } - export default function bootstrap(options: BoostrapOptions): BootstrapResult; + export default function bootstrap(options: BootstrapOptions): BootstrapResult; } diff --git a/wolfy87-eventemitter/wolfy87-eventemitter-tests.ts b/wolfy87-eventemitter/wolfy87-eventemitter-tests.ts index d2d4e6f0cf..ec26166dc8 100644 --- a/wolfy87-eventemitter/wolfy87-eventemitter-tests.ts +++ b/wolfy87-eventemitter/wolfy87-eventemitter-tests.ts @@ -1,6 +1,6 @@ -/// +/// -import EventEmitter = require("wolfy87-eventemitter"); +import * as EventEmitter from 'wolfy87-eventemitter'; var emitter = new EventEmitter(); @@ -108,4 +108,3 @@ function testNoConflict() { var NoConflictEventEmitter = EventEmitter.noConflict(); var e: Wolfy87EventEmitter.EventEmitter = new NoConflictEventEmitter(); } - diff --git a/wolfy87-eventemitter/wolfy87-eventemitter.d.ts b/wolfy87-eventemitter/wolfy87-eventemitter.d.ts index 45c4e54e5d..8291c50c11 100644 --- a/wolfy87-eventemitter/wolfy87-eventemitter.d.ts +++ b/wolfy87-eventemitter/wolfy87-eventemitter.d.ts @@ -9,7 +9,7 @@ declare namespace Wolfy87EventEmitter { * Hash Object for manipulating multiple events. */ interface MultipleEvents { - [event:string]: any //Function | Function[] + [event: string]: any //Function | Function[] } /** @@ -506,6 +506,7 @@ declare namespace Wolfy87EventEmitter { declare module "wolfy87-eventemitter" { class EventEmitter extends Wolfy87EventEmitter.EventEmitter {} + namespace EventEmitter {} export = EventEmitter; } From b9989e602b3225d48aa4a9dfa0631ae41fea100d Mon Sep 17 00:00:00 2001 From: Marian Palkus Date: Wed, 25 May 2016 10:39:55 +0200 Subject: [PATCH 133/402] Update definitions of enzyme to version 2.3.0. (#9361) * Update definitions of enzyme to version 2.3.0. * Fixed URL of enzyme repository. --- enzyme/enzyme-1.2.0-tests.tsx | 605 ++++++++++++++++++++++++++++++++++ enzyme/enzyme-1.2.0.d.ts | 473 ++++++++++++++++++++++++++ enzyme/enzyme-tests.tsx | 191 ++++++++++- enzyme/enzyme.d.ts | 89 ++++- 4 files changed, 1344 insertions(+), 14 deletions(-) create mode 100644 enzyme/enzyme-1.2.0-tests.tsx create mode 100644 enzyme/enzyme-1.2.0.d.ts diff --git a/enzyme/enzyme-1.2.0-tests.tsx b/enzyme/enzyme-1.2.0-tests.tsx new file mode 100644 index 0000000000..44db5705bc --- /dev/null +++ b/enzyme/enzyme-1.2.0-tests.tsx @@ -0,0 +1,605 @@ +/// +/// + +import { shallow, mount, render, describeWithDOM, spyLifecycle } from "enzyme"; +import * as React from "react"; +import {Component, ReactElement, HTMLAttributes} from "react"; +import {ShallowWrapper, ReactWrapper, CheerioWrapper} from "enzyme"; + + +// Help classes/interfaces +interface MyComponentProps { + propsProperty: any; + numberProp?: number; +} + +interface StatelessProps { + stateless: any; +} + +interface MyComponentState { + stateProperty: any; +} + +class MyComponent extends Component { + setState(...args: any[]) { + } +} + +const MyStatelessComponent = (props: StatelessProps) => ; + +// API +namespace SpyLifecycleTest { + spyLifecycle(MyComponent); +} + +// ShallowWrapper +namespace ShallowWrapperTest { + var shallowWrapper: ShallowWrapper = + shallow(); + + var reactElement: ReactElement, + objectVal: Object, + boolVal: Boolean, + stringVal: String, + elementWrapper: ShallowWrapper + + function test_find() { + elementWrapper = shallowWrapper.find('.selector'); + shallowWrapper = shallowWrapper.find(MyComponent); + shallowWrapper.find(MyStatelessComponent).props().stateless; + shallowWrapper.find(MyStatelessComponent).shallow(); + } + + function test_findWhere() { + shallowWrapper = + shallowWrapper.findWhere((aShallowWrapper: ShallowWrapper) => true); + } + + function test_filter() { + elementWrapper = shallowWrapper.filter('.selector'); + shallowWrapper = shallowWrapper.filter(MyComponent).shallow(); + } + + function test_filterWhere() { + shallowWrapper = + shallowWrapper.filterWhere(wrapper => { + wrapper.props().propsProperty; + return true; + }); + } + + function test_contains() { + boolVal = shallowWrapper.contains(
); + } + + function test_hasClass() { + boolVal = shallowWrapper.find('.my-button').hasClass('disabled'); + } + + function test_is() { + boolVal = shallowWrapper.is('.some-class'); + } + + function test_not() { + elementWrapper = shallowWrapper.find('.foo').not('.bar'); + } + + function test_children() { + shallowWrapper = shallowWrapper.children(); + shallowWrapper.children(MyStatelessComponent).props().stateless; + } + + function test_parents() { + shallowWrapper = shallowWrapper.parents(); + } + + function test_parent() { + shallowWrapper = shallowWrapper.parent(); + } + + function test_closest() { + elementWrapper = shallowWrapper.closest('.selector'); + shallowWrapper = shallowWrapper.closest(MyComponent); + } + + function test_shallow() { + shallowWrapper = shallowWrapper.shallow(); + } + + function test_unmount() { + shallowWrapper = shallowWrapper.unmount(); + } + + function test_render() { + var cheerioWrapper: CheerioWrapper = shallowWrapper.render(); + } + + function test_text() { + stringVal = shallowWrapper.text(); + } + + + function test_html() { + stringVal = shallowWrapper.html(); + } + + function test_get() { + reactElement = shallowWrapper.get(1); + } + + function test_at() { + shallowWrapper = shallowWrapper.at(1); + } + + function test_first() { + shallowWrapper = shallowWrapper.first(); + } + + function test_last() { + shallowWrapper = shallowWrapper.last(); + } + + function test_state() { + shallowWrapper.state(); + shallowWrapper.state('key'); + } + + function test_props() { + objectVal = shallowWrapper.props(); + } + + function test_prop() { + shallowWrapper.prop('key'); + } + + + function test_simulate(...args: any[]) { + shallowWrapper.simulate('click'); + shallowWrapper.simulate('click', args); + } + + function test_setState() { + shallowWrapper = shallowWrapper.setState({stateProperty: 'state'}); + } + + function test_setProps() { + shallowWrapper = shallowWrapper.setProps({propsProperty: 'foo'}); + } + + function test_setContext() { + shallowWrapper = shallowWrapper.setContext({name: 'baz'}); + } + + function test_instance() { + var myComponent: MyComponent = shallowWrapper.instance(); + } + + function test_update() { + shallowWrapper = shallowWrapper.update(); + } + + function test_debug() { + stringVal = shallowWrapper.debug(); + } + + function test_type() { + var stringOrFunction: String|Function = shallowWrapper.type(); + } + + function test_forEach() { + shallowWrapper = + shallowWrapper.forEach(wrapper => wrapper.shallow().props().propsProperty); + } + + function test_map() { + var arrayNumbers: Array = + shallowWrapper.map(wrapper => wrapper.props().numberProp); + } + + function test_reduce() { + const total: number[] = + shallowWrapper.reduce( + (amount: number, n: ShallowWrapper) => amount + n.props().numberProp + ); + } + + function test_reduceRight() { + const total: number[] = + shallowWrapper.reduceRight( + (amount: number, n: ShallowWrapper) => amount + n.prop('amount') + ); + } + + function test_some() { + boolVal = shallowWrapper.some('.selector'); + boolVal = shallowWrapper.some(MyComponent); + } + + function test_someWhere() { + boolVal = shallowWrapper.someWhere((aShallowWrapper: ShallowWrapper) => true); + } + + function test_every() { + boolVal = shallowWrapper.every('.selector'); + boolVal = shallowWrapper.every(MyComponent); + } + + function test_everyWhere() { + boolVal = shallowWrapper.everyWhere((aShallowWrapper: ShallowWrapper) => true); + } +} + + +// ReactWrapper +namespace ReactWrapperTest { + var reactWrapper: ReactWrapper = + mount(); + + var reactElement: ReactElement, + objectVal: Object, + boolVal: Boolean, + stringVal: String, + elementWrapper: ReactWrapper + + function test_unmount() { + reactWrapper = reactWrapper.unmount(); + } + + function test_mount() { + reactWrapper = reactWrapper.mount(); + } + + function test_find() { + elementWrapper = reactWrapper.find('.selector'); + reactWrapper = reactWrapper.find(MyComponent); + reactWrapper.find(MyStatelessComponent).props().stateless; + } + + function test_findWhere() { + reactWrapper = + reactWrapper.findWhere((aReactWrapper: ReactWrapper) => true); + } + + function test_filter() { + elementWrapper = reactWrapper.filter('.selector'); + reactWrapper = reactWrapper.filter(MyComponent); + } + + function test_filterWhere() { + reactWrapper = + reactWrapper.filterWhere(wrapper => { + wrapper.props().propsProperty; + return true; + }); + } + + function test_contains() { + boolVal = reactWrapper.contains(
); + } + + function test_hasClass() { + boolVal = reactWrapper.find('.my-button').hasClass('disabled'); + } + + function test_is() { + boolVal = reactWrapper.is('.some-class'); + } + + function test_not() { + elementWrapper = reactWrapper.find('.foo').not('.bar'); + } + + function test_children() { + reactWrapper = reactWrapper.children(); + } + + function test_parents() { + reactWrapper = reactWrapper.parents(); + } + + function test_parent() { + reactWrapper = reactWrapper.parent(); + } + + function test_closest() { + elementWrapper = reactWrapper.closest('.selector'); + reactWrapper = reactWrapper.closest(MyComponent); + } + + function test_text() { + stringVal = reactWrapper.text(); + } + + function test_html() { + stringVal = reactWrapper.html(); + } + + function test_get() { + reactElement = reactWrapper.get(1); + } + + function test_at() { + reactWrapper = reactWrapper.at(1); + } + + function test_first() { + reactWrapper = reactWrapper.first(); + } + + function test_last() { + reactWrapper = reactWrapper.last(); + } + + function test_state() { + reactWrapper.state(); + reactWrapper.state('key'); + } + + function test_props() { + objectVal = reactWrapper.props(); + } + + function test_prop() { + reactWrapper.prop('key'); + } + + + function test_simulate(...args: any[]) { + reactWrapper.simulate('click'); + reactWrapper.simulate('click', args); + } + + function test_setState() { + reactWrapper = reactWrapper.setState({stateProperty: 'state'}); + } + + function test_setProps() { + reactWrapper = reactWrapper.setProps({propsProperty: 'foo'}); + } + + function test_setContext() { + reactWrapper = reactWrapper.setContext({name: 'baz'}); + } + + function test_instance() { + var myComponent: MyComponent = reactWrapper.instance(); + } + + function test_update() { + reactWrapper = reactWrapper.update(); + } + + function test_debug() { + stringVal = reactWrapper.debug(); + } + + function test_type() { + var stringOrFunction: String|Function = reactWrapper.type(); + } + + function test_forEach() { + reactWrapper = + reactWrapper.forEach(wrapper => wrapper.props().propsProperty); + } + + function test_map() { + var arrayNumbers: Array = + reactWrapper.map(wrapper => wrapper.props().numberProp); + } + + function test_reduce() { + const total: number[] = + reactWrapper.reduce( + (amount: number, n: ReactWrapper) => amount + n.prop('amount') + ); + } + + function test_reduceRight() { + const total: number[] = + reactWrapper.reduceRight( + (amount: number, n: ReactWrapper) => amount + n.prop('amount') + ); + } + + function test_some() { + boolVal = reactWrapper.some('.selector'); + boolVal = reactWrapper.some(MyComponent); + } + + function test_someWhere() { + boolVal = reactWrapper.someWhere((aReactWrapper: ReactWrapper) => true); + } + + function test_every() { + boolVal = reactWrapper.every('.selector'); + boolVal = reactWrapper.every(MyComponent); + } + + function test_everyWhere() { + boolVal = reactWrapper.everyWhere((aReactWrapper: ReactWrapper) => true); + } +} + +// CheerioWrapper +namespace CheerioWrapperTest { + var cheerioWrapper: CheerioWrapper = + render(); + + var reactElement: ReactElement, + objectVal: Object, + boolVal: Boolean, + stringVal: String, + elementWrapper: CheerioWrapper + + function test_find() { + elementWrapper = cheerioWrapper.find('.selector'); + cheerioWrapper = cheerioWrapper.find(MyComponent); + cheerioWrapper.find(MyStatelessComponent).props().stateless; + } + + function test_findWhere() { + cheerioWrapper = + cheerioWrapper.findWhere((aCheerioWrapper: CheerioWrapper) => true); + } + + function test_filter() { + elementWrapper = cheerioWrapper.filter('.selector'); + cheerioWrapper = cheerioWrapper.filter(MyComponent); + } + + function test_filterWhere() { + cheerioWrapper = + cheerioWrapper.filterWhere(wrapper => { + wrapper.props().propsProperty; + return true; + }); + } + + function test_contains() { + boolVal = cheerioWrapper.contains(
); + } + + function test_hasClass() { + boolVal = cheerioWrapper.find('.my-button').hasClass('disabled'); + } + + function test_is() { + boolVal = cheerioWrapper.is('.some-class'); + } + + function test_not() { + elementWrapper = cheerioWrapper.find('.foo').not('.bar'); + } + + function test_children() { + cheerioWrapper = cheerioWrapper.children(); + } + + function test_parents() { + cheerioWrapper = cheerioWrapper.parents(); + } + + function test_parent() { + cheerioWrapper = cheerioWrapper.parent(); + } + + function test_closest() { + elementWrapper = cheerioWrapper.closest('.selector'); + cheerioWrapper = cheerioWrapper.closest(MyComponent); + } + + function test_text() { + stringVal = cheerioWrapper.text(); + } + + function test_html() { + stringVal = cheerioWrapper.html(); + } + + function test_get() { + reactElement = cheerioWrapper.get(1); + } + + function test_at() { + cheerioWrapper = cheerioWrapper.at(1); + } + + function test_first() { + cheerioWrapper = cheerioWrapper.first(); + } + + function test_last() { + cheerioWrapper = cheerioWrapper.last(); + } + + function test_state() { + cheerioWrapper.state(); + cheerioWrapper.state('key'); + } + + function test_props() { + objectVal = cheerioWrapper.props(); + } + + function test_prop() { + cheerioWrapper.prop('key'); + } + + + function test_simulate(...args: any[]) { + cheerioWrapper.simulate('click'); + cheerioWrapper.simulate('click', args); + } + + function test_setState() { + cheerioWrapper = cheerioWrapper.setState({stateProperty: 'state'}); + } + + function test_setProps() { + cheerioWrapper = cheerioWrapper.setProps({propsProperty: 'foo'}); + } + + function test_setContext() { + cheerioWrapper = cheerioWrapper.setContext({name: 'baz'}); + } + + function test_instance() { + var myComponent: MyComponent = cheerioWrapper.instance(); + } + + function test_update() { + cheerioWrapper = cheerioWrapper.update(); + } + + function test_debug() { + stringVal = cheerioWrapper.debug(); + } + + function test_type() { + var stringOrFunction: String|Function = cheerioWrapper.type(); + } + + function test_forEach() { + cheerioWrapper = + cheerioWrapper.forEach((aCheerioWrapper: CheerioWrapper)=> { + }); + } + + function test_map() { + var arrayNumbers: Array = + cheerioWrapper.map(wrapper => wrapper.props().numberProp); + } + + function test_reduce() { + const total: number[] = + cheerioWrapper.reduce( + (amount: number, n: CheerioWrapper) => amount + n.prop('amount') + ); + } + + function test_reduceRight() { + const total: number[] = + cheerioWrapper.reduceRight( + (amount: number, n: CheerioWrapper) => amount + n.prop('amount') + ); + } + + function test_some() { + boolVal = cheerioWrapper.some('.selector'); + boolVal = cheerioWrapper.some(MyComponent); + } + + function test_someWhere() { + boolVal = cheerioWrapper.someWhere((aCheerioWrapper: CheerioWrapper) => true); + } + + function test_every() { + boolVal = cheerioWrapper.every('.selector'); + boolVal = cheerioWrapper.every(MyComponent); + } + + function test_everyWhere() { + boolVal = cheerioWrapper.everyWhere((aCheerioWrapper: CheerioWrapper) => true); + } +} diff --git a/enzyme/enzyme-1.2.0.d.ts b/enzyme/enzyme-1.2.0.d.ts new file mode 100644 index 0000000000..13c00041a5 --- /dev/null +++ b/enzyme/enzyme-1.2.0.d.ts @@ -0,0 +1,473 @@ +// Type definitions for Enzyme v1.2.0 +// Project: https://github.com/airbnb/enzyme +// Definitions by: Marian Palkus , Cap3 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "enzyme" { + + import {ReactElement, Component, StatelessComponent, ComponentClass, HTMLAttributes} from "react"; + + export class ElementClass extends Component { + } + + /** + * Many methods in Enzyme's API accept a selector as an argument. Selectors in Enzyme can fall into one of the + * following three categories: + * + * 1. A Valid CSS Selector + * 2. A React Component Constructor + * 3. A React Component's displayName + */ + export type EnzymeSelector = String | typeof ElementClass; + + interface CommonWrapper { + /** + * Find every node in the render tree that matches the provided selector. + * @param selector The selector to match. + */ + find(component: ComponentClass): CommonWrapper; + find(statelessComponent: StatelessComponent): CommonWrapper; + find(selector: string): CommonWrapper; + + /** + * Finds every node in the render tree that returns true for the provided predicate function. + * @param predicate + */ + findWhere(predicate: (wrapper: CommonWrapper) => Boolean): CommonWrapper; + + /** + * Removes nodes in the current wrapper that do not match the provided selector. + * @param selector The selector to match. + */ + filter(component: ComponentClass): CommonWrapper; + filter(statelessComponent: StatelessComponent): CommonWrapper; + filter(selector: string): CommonWrapper; + + /** + * Returns a new wrapper with only the nodes of the current wrapper that, when passed into the provided predicate function, return true. + * @param predicate + */ + filterWhere(predicate: (wrapper: this) => Boolean): this; + + /** + * Returns whether or not the current wrapper has a node anywhere in it's render tree that looks like the one passed in. + * @param node + */ + contains(node: ReactElement): Boolean; + + /** + * Returns whether or not the current node has a className prop including the passed in class name. + * @param className + */ + hasClass(className: String): Boolean; + + /** + * Returns whether or not the current node matches a provided selector. + * @param selector + */ + is(selector: EnzymeSelector): Boolean; + + /** + * Returns a new wrapper with only the nodes of the current wrapper that don't match the provided selector. + * This method is effectively the negation or inverse of filter. + * @param selector + */ + not(selector: EnzymeSelector): this; + + /** + * Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector + * can be provided and it will filter the children by this selector. + * @param [selector] + */ + children(component: ComponentClass): CommonWrapper; + children(statelessComponent: StatelessComponent): CommonWrapper; + children(selector: string): CommonWrapper; + children(): CommonWrapper; + + /** + * Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the + * current wrapper. Optionally, a selector can be provided and it will filter the parents by this selector. + * + * Note: can only be called on a wrapper of a single node. + * @param [selector] + */ + parents(component: ComponentClass): CommonWrapper; + parents(statelessComponent: StatelessComponent): CommonWrapper; + parents(selector: string): CommonWrapper; + parents(): CommonWrapper; + + /** + * Returns a wrapper with the direct parent of the node in the current wrapper. + */ + parent(): CommonWrapper; + + /** + * Returns a wrapper of the first element that matches the selector by traversing up through the current node's + * ancestors in the tree, starting with itself. + * + * Note: can only be called on a wrapper of a single node. + * @param selector + */ + closest(component: ComponentClass): CommonWrapper; + closest(statelessComponent: StatelessComponent): CommonWrapper; + closest(selector: string): CommonWrapper; + + /** + * Returns a string of the rendered text of the current render tree. This function should be looked at with + * skepticism if being used to test what the actual HTML output of the component will be. If that is what you + * would like to test, use enzyme's render function instead. + * + * Note: can only be called on a wrapper of a single node. + */ + text(): String; + + /** + * Returns a string of the rendered HTML markup of the current render tree. + * + * Note: can only be called on a wrapper of a single node. + */ + html(): String; + + /** + * Returns the node at a given index of the current wrapper. + * @param index + */ + get(index: number): ReactElement; + + /** + * Returns a wrapper around the node at a given index of the current wrapper. + * @param index + */ + at(index: number): this; + + /** + * Reduce the set of matched nodes to the first in the set. + */ + first(): this; + + /** + * Reduce the set of matched nodes to the last in the set. + */ + last(): this; + + /** + * Returns the state hash for the root node of the wrapper. Optionally pass in a prop name and it will return just that value. + * @param [key] + */ + state(key?: String): any; + + /** + * Returns the props hash for the current node of the wrapper. + * + * NOTE: can only be called on a wrapper of a single node. + */ + props(): P; + + /** + * Returns the prop value for the node of the current wrapper with the provided key. + * + * NOTE: can only be called on a wrapper of a single node. + * @param key + */ + prop(key: String): any; + + /** + * Simulate events. + * Returns itself. + * @param event + * @param args? + */ + simulate(event: string, ...args: any[]): this; + + /** + * A method to invoke setState() on the root component instance similar to how you might in the definition of + * the component, and re-renders. This method is useful for testing your component in hard to achieve states, + * however should be used sparingly. If possible, you should utilize your component's external API in order to + * get it into whatever state you want to test, in order to be as accurate of a test as possible. This is not + * always practical, however. + * Returns itself. + * + * NOTE: can only be called on a wrapper instance that is also the root instance. + * @param state + */ + setState(state: S): this; + + /** + * A method that sets the props of the root component, and re-renders. Useful for when you are wanting to test + * how the component behaves over time with changing props. Calling this, for instance, will call the + * componentWillReceiveProps lifecycle method. + * + * Similar to setState, this method accepts a props object and will merge it in with the already existing props. + * Returns itself. + * + * NOTE: can only be called on a wrapper instance that is also the root instance. + * @param state + */ + setProps(props: P): this; + + /** + * A method that sets the context of the root component, and re-renders. Useful for when you are wanting to + * test how the component behaves over time with changing contexts. + * Returns itself. + * + * NOTE: can only be called on a wrapper instance that is also the root instance. + * @param state + */ + setContext(context: Object): this; + + /** + * Gets the instance of the component being rendered as the root node passed into shallow(). + * + * NOTE: can only be called on a wrapper instance that is also the root instance. + */ + instance(): Component; + + /** + * Forces a re-render. Useful to run before checking the render output if something external may be updating + * the state of the component somewhere. + * Returns itself. + * + * NOTE: can only be called on a wrapper instance that is also the root instance. + */ + update(): this; + + /** + * Returns an html-like string of the wrapper for debugging purposes. Useful to print out to the console when + * tests are not passing when you expect them to. + */ + debug(): String; + + /** + * Returns the type of the current node of this wrapper. If it's a composite component, this will be the + * component constructor. If it's native DOM node, it will be a string of the tag name. + * + * Note: can only be called on a wrapper of a single node. + */ + type(): String | Function; + + /** + * Iterates through each node of the current wrapper and executes the provided function with a wrapper around + * the corresponding node passed in as the first argument. + * + * Returns itself. + * @param fn A callback to be run for every node in the collection. Should expect a ShallowWrapper as the first + * argument, and will be run with a context of the original instance. + */ + forEach(fn: (wrapper: this) => any): this; + + /** + * Maps the current array of nodes to another array. Each node is passed in as a ShallowWrapper to the map + * function. + * Returns an array of the returned values from the mapping function.. + * @param fn A mapping function to be run for every node in the collection, the results of which will be mapped + * to the returned array. Should expect a ShallowWrapper as the first argument, and will be run + * with a context of the original instance. + */ + map(fn: (wrapper: this) => V): V[]; + + /** + * Applies the provided reducing function to every node in the wrapper to reduce to a single value. Each node + * is passed in as a ShallowWrapper, and is processed from left to right. + * @param fn + * @param initialValue + */ + reduce(fn: (prevVal: R, wrapper: this, index: number) => R, initialValue?: R): R[]; + + /** + * Applies the provided reducing function to every node in the wrapper to reduce to a single value. + * Each node is passed in as a ShallowWrapper, and is processed from right to left. + * @param fn + * @param initialValue + */ + reduceRight(fn: (prevVal: R, wrapper: this, index: number) => R, initialValue?: R): R[]; + + /** + * Returns whether or not any of the nodes in the wrapper match the provided selector. + * @param selector + */ + some(selector: EnzymeSelector): Boolean; + + /** + * Returns whether or not any of the nodes in the wrapper pass the provided predicate function. + * @param fn + */ + someWhere(fn: (wrapper: this) => Boolean): Boolean; + + /** + * Returns whether or not all of the nodes in the wrapper match the provided selector. + * @param selector + */ + every(selector: EnzymeSelector): Boolean; + + /** + * Returns whether or not any of the nodes in the wrapper pass the provided predicate function. + * @param fn + */ + everyWhere(fn: (wrapper: this) => Boolean): Boolean; + + length: number; + } + + export interface ShallowWrapper extends CommonWrapper { + shallow(): ShallowWrapper; + render(): CheerioWrapper; + unmount(): ShallowWrapper; + + /** + * Find every node in the render tree that matches the provided selector. + * @param selector The selector to match. + */ + find(component: ComponentClass): ShallowWrapper; + find(statelessComponent: (props: P2) => JSX.Element): ShallowWrapper; + find(selector: string): ShallowWrapper; + + /** + * Removes nodes in the current wrapper that do not match the provided selector. + * @param selector The selector to match. + */ + filter(component: ComponentClass): ShallowWrapper; + filter(statelessComponent: StatelessComponent): ShallowWrapper; + filter(selector: string): ShallowWrapper; + + /** + * Finds every node in the render tree that returns true for the provided predicate function. + * @param predicate + */ + findWhere(predicate: (wrapper: CommonWrapper) => Boolean): ShallowWrapper; + + /** + * Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector + * can be provided and it will filter the children by this selector. + * @param [selector] + */ + children(component: ComponentClass): ShallowWrapper; + children(statelessComponent: StatelessComponent): ShallowWrapper; + children(selector: string): ShallowWrapper; + children(): ShallowWrapper; + + /** + * Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the + * current wrapper. Optionally, a selector can be provided and it will filter the parents by this selector. + * + * Note: can only be called on a wrapper of a single node. + * @param [selector] + */ + parents(component: ComponentClass): ShallowWrapper; + parents(statelessComponent: StatelessComponent): ShallowWrapper; + parents(selector: string): ShallowWrapper; + parents(): ShallowWrapper; + + /** + * Returns a wrapper of the first element that matches the selector by traversing up through the current node's + * ancestors in the tree, starting with itself. + * + * Note: can only be called on a wrapper of a single node. + * @param selector + */ + closest(component: ComponentClass): ShallowWrapper; + closest(statelessComponent: StatelessComponent): ShallowWrapper; + closest(selector: string): ShallowWrapper; + + /** + * Returns a wrapper with the direct parent of the node in the current wrapper. + */ + parent(): ShallowWrapper; + } + + export interface ReactWrapper extends CommonWrapper { + unmount(): ReactWrapper; + mount(): ReactWrapper; + + /** + * Find every node in the render tree that matches the provided selector. + * @param selector The selector to match. + */ + find(component: ComponentClass): ReactWrapper; + find(statelessComponent: (props: P2) => JSX.Element): ReactWrapper; + find(selector: string): ReactWrapper; + + /** + * Finds every node in the render tree that returns true for the provided predicate function. + * @param predicate + */ + findWhere(predicate: (wrapper: CommonWrapper) => Boolean): ReactWrapper; + + /** + * Removes nodes in the current wrapper that do not match the provided selector. + * @param selector The selector to match. + */ + filter(component: ComponentClass): ReactWrapper; + filter(statelessComponent: StatelessComponent): ReactWrapper; + filter(selector: string): ReactWrapper; + + /** + * Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector + * can be provided and it will filter the children by this selector. + * @param [selector] + */ + children(component: ComponentClass): ReactWrapper; + children(statelessComponent: StatelessComponent): ReactWrapper; + children(selector: string): ReactWrapper; + children(): ReactWrapper; + + /** + * Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the + * current wrapper. Optionally, a selector can be provided and it will filter the parents by this selector. + * + * Note: can only be called on a wrapper of a single node. + * @param [selector] + */ + parents(component: ComponentClass): ReactWrapper; + parents(statelessComponent: StatelessComponent): ReactWrapper; + parents(selector: string): ReactWrapper; + parents(): ReactWrapper; + + /** + * Returns a wrapper of the first element that matches the selector by traversing up through the current node's + * ancestors in the tree, starting with itself. + * + * Note: can only be called on a wrapper of a single node. + * @param selector + */ + closest(component: ComponentClass): ReactWrapper; + closest(statelessComponent: StatelessComponent): ReactWrapper; + closest(selector: string): ReactWrapper; + + /** + * Returns a wrapper with the direct parent of the node in the current wrapper. + */ + parent(): ReactWrapper; + } + + export interface CheerioWrapper extends CommonWrapper { + + } + + /** + * Shallow rendering is useful to constrain yourself to testing a component as a unit, and to ensure that + * your tests aren't indirectly asserting on behavior of child components. + * @param node + * @param [options] + */ + export function shallow(node: ReactElement

, options?: any): ShallowWrapper; + + /** + * Mounts and renders a react component into the document and provides a testing wrapper around it. + * @param node + * @param [options] + */ + export function mount(node: ReactElement

, options?: any): ReactWrapper; + + /** + * Render react components to static HTML and analyze the resulting HTML structure. + * @param node + * @param [options] + */ + export function render(node: ReactElement

, options?: any): CheerioWrapper; + + export function describeWithDOM(description: String, fn: Function): void; + + export function spyLifecycle(component: typeof Component): void; +} \ No newline at end of file diff --git a/enzyme/enzyme-tests.tsx b/enzyme/enzyme-tests.tsx index 4cc45e9fd4..805201e53a 100644 --- a/enzyme/enzyme-tests.tsx +++ b/enzyme/enzyme-tests.tsx @@ -73,6 +73,26 @@ namespace ShallowWrapperTest { boolVal = shallowWrapper.contains(

); } + function test_containsMatchingElement() { + boolVal = shallowWrapper.contains(
); + } + + function test_containsAllMatchingElements() { + boolVal = shallowWrapper.containsAllMatchingElements([
]); + } + + function test_containsAnyMatchingElement() { + boolVal = shallowWrapper.containsAnyMatchingElements([
]); + } + + function test_equals() { + boolVal = shallowWrapper.equals(
); + } + + function test_matchesElement() { + boolVal = shallowWrapper.matchesElement(
); + } + function test_hasClass() { boolVal = shallowWrapper.find('.my-button').hasClass('disabled'); } @@ -90,6 +110,20 @@ namespace ShallowWrapperTest { shallowWrapper.children(MyStatelessComponent).props().stateless; } + function test_childAt() { + const childWrapper: ShallowWrapper = shallowWrapper.childAt(0); + + interface TmpType1 { + foo: any + } + + interface TmpType2 { + bar: any + } + + const childWrapper2: ShallowWrapper = shallowWrapper.childAt(0); + } + function test_parents() { shallowWrapper = shallowWrapper.parents(); } @@ -143,6 +177,13 @@ namespace ShallowWrapperTest { function test_state() { shallowWrapper.state(); shallowWrapper.state('key'); + const tmp: String = shallowWrapper.state('key'); + } + + function test_context() { + shallowWrapper.context(); + shallowWrapper.context('key'); + const tmp: String = shallowWrapper.context('key'); } function test_props() { @@ -151,8 +192,12 @@ namespace ShallowWrapperTest { function test_prop() { shallowWrapper.prop('key'); + const tmp: String = shallowWrapper.prop('key'); } + function test_key() { + stringVal = shallowWrapper.key(); + } function test_simulate(...args: any[]) { shallowWrapper.simulate('click'); @@ -160,15 +205,15 @@ namespace ShallowWrapperTest { } function test_setState() { - shallowWrapper = shallowWrapper.setState({stateProperty: 'state'}); + shallowWrapper = shallowWrapper.setState({ stateProperty: 'state' }); } function test_setProps() { - shallowWrapper = shallowWrapper.setProps({propsProperty: 'foo'}); + shallowWrapper = shallowWrapper.setProps({ propsProperty: 'foo' }); } function test_setContext() { - shallowWrapper = shallowWrapper.setContext({name: 'baz'}); + shallowWrapper = shallowWrapper.setContext({ name: 'baz' }); } function test_instance() { @@ -184,7 +229,11 @@ namespace ShallowWrapperTest { } function test_type() { - var stringOrFunction: String|Function = shallowWrapper.type(); + var stringOrFunction: String | Function = shallowWrapper.type(); + } + + function test_name() { + var str: String = shallowWrapper.name(); } function test_forEach() { @@ -250,6 +299,24 @@ namespace ReactWrapperTest { reactWrapper = reactWrapper.mount(); } + function test_ref() { + reactWrapper = reactWrapper.ref('refName'); + + interface TmpType1 { + foo: string + } + + interface TmpType2 { + bar: string + } + + const tmp: ReactWrapper = reactWrapper.ref('refName'); + } + + function test_detach() { + reactWrapper.detach(); + } + function test_find() { elementWrapper = reactWrapper.find('.selector'); reactWrapper = reactWrapper.find(MyComponent); @@ -278,6 +345,26 @@ namespace ReactWrapperTest { boolVal = reactWrapper.contains(
); } + function test_containsMatchingElement() { + boolVal = reactWrapper.contains(
); + } + + function test_containsAllMatchingElements() { + boolVal = reactWrapper.containsAllMatchingElements([
]); + } + + function test_containsAnyMatchingElement() { + boolVal = reactWrapper.containsAnyMatchingElements([
]); + } + + function test_equals() { + boolVal = reactWrapper.equals(
); + } + + function test_matchesElement() { + boolVal = reactWrapper.matchesElement(
); + } + function test_hasClass() { boolVal = reactWrapper.find('.my-button').hasClass('disabled'); } @@ -294,6 +381,20 @@ namespace ReactWrapperTest { reactWrapper = reactWrapper.children(); } + function test_childAt() { + const childWrapper: ReactWrapper = reactWrapper.childAt(0); + + interface TmpType1 { + foo: any + } + + interface TmpType2 { + bar: any + } + + const childWrapper2: ReactWrapper = reactWrapper.childAt(0); + } + function test_parents() { reactWrapper = reactWrapper.parents(); } @@ -334,6 +435,13 @@ namespace ReactWrapperTest { function test_state() { reactWrapper.state(); reactWrapper.state('key'); + const tmp: String = reactWrapper.state('key'); + } + + function test_context() { + reactWrapper.context(); + reactWrapper.context('key'); + const tmp: String = reactWrapper.context('key'); } function test_props() { @@ -342,8 +450,12 @@ namespace ReactWrapperTest { function test_prop() { reactWrapper.prop('key'); + const tmp: String = reactWrapper.prop('key'); } + function test_key() { + stringVal = reactWrapper.key(); + } function test_simulate(...args: any[]) { reactWrapper.simulate('click'); @@ -351,15 +463,15 @@ namespace ReactWrapperTest { } function test_setState() { - reactWrapper = reactWrapper.setState({stateProperty: 'state'}); + reactWrapper = reactWrapper.setState({ stateProperty: 'state' }); } function test_setProps() { - reactWrapper = reactWrapper.setProps({propsProperty: 'foo'}); + reactWrapper = reactWrapper.setProps({ propsProperty: 'foo' }); } function test_setContext() { - reactWrapper = reactWrapper.setContext({name: 'baz'}); + reactWrapper = reactWrapper.setContext({ name: 'baz' }); } function test_instance() { @@ -375,7 +487,11 @@ namespace ReactWrapperTest { } function test_type() { - var stringOrFunction: String|Function = reactWrapper.type(); + var stringOrFunction: String | Function = reactWrapper.type(); + } + + function test_name() { + var str: String = reactWrapper.name(); } function test_forEach() { @@ -460,6 +576,26 @@ namespace CheerioWrapperTest { boolVal = cheerioWrapper.contains(
); } + function test_containsMatchingElement() { + boolVal = cheerioWrapper.contains(
); + } + + function test_containsAllMatchingElements() { + boolVal = cheerioWrapper.containsAllMatchingElements([
]); + } + + function test_containsAnyMatchingElement() { + boolVal = cheerioWrapper.containsAnyMatchingElements([
]); + } + + function test_equals() { + boolVal = cheerioWrapper.equals(
); + } + + function test_matchesElement() { + boolVal = cheerioWrapper.matchesElement(
); + } + function test_hasClass() { boolVal = cheerioWrapper.find('.my-button').hasClass('disabled'); } @@ -476,6 +612,20 @@ namespace CheerioWrapperTest { cheerioWrapper = cheerioWrapper.children(); } + function test_childAt() { + const childWrapper: CheerioWrapper = cheerioWrapper.childAt(0); + + interface TmpType1 { + foo: any + } + + interface TmpType2 { + bar: any + } + + const childWrapper2: CheerioWrapper = cheerioWrapper.childAt(0); + } + function test_parents() { cheerioWrapper = cheerioWrapper.parents(); } @@ -516,6 +666,13 @@ namespace CheerioWrapperTest { function test_state() { cheerioWrapper.state(); cheerioWrapper.state('key'); + const tmp: String = cheerioWrapper.state('key'); + } + + function test_context() { + cheerioWrapper.context(); + cheerioWrapper.context('key'); + const tmp: String = cheerioWrapper.context('key'); } function test_props() { @@ -524,8 +681,12 @@ namespace CheerioWrapperTest { function test_prop() { cheerioWrapper.prop('key'); + const tmp: String = cheerioWrapper.prop('key'); } + function test_key() { + stringVal = cheerioWrapper.key(); + } function test_simulate(...args: any[]) { cheerioWrapper.simulate('click'); @@ -533,15 +694,15 @@ namespace CheerioWrapperTest { } function test_setState() { - cheerioWrapper = cheerioWrapper.setState({stateProperty: 'state'}); + cheerioWrapper = cheerioWrapper.setState({ stateProperty: 'state' }); } function test_setProps() { - cheerioWrapper = cheerioWrapper.setProps({propsProperty: 'foo'}); + cheerioWrapper = cheerioWrapper.setProps({ propsProperty: 'foo' }); } function test_setContext() { - cheerioWrapper = cheerioWrapper.setContext({name: 'baz'}); + cheerioWrapper = cheerioWrapper.setContext({ name: 'baz' }); } function test_instance() { @@ -557,12 +718,16 @@ namespace CheerioWrapperTest { } function test_type() { - var stringOrFunction: String|Function = cheerioWrapper.type(); + var stringOrFunction: String | Function = cheerioWrapper.type(); + } + + function test_name() { + var str: String = cheerioWrapper.name(); } function test_forEach() { cheerioWrapper = - cheerioWrapper.forEach((aCheerioWrapper: CheerioWrapper)=> { + cheerioWrapper.forEach((aCheerioWrapper: CheerioWrapper) => { }); } diff --git a/enzyme/enzyme.d.ts b/enzyme/enzyme.d.ts index 13c00041a5..2698fd366b 100644 --- a/enzyme/enzyme.d.ts +++ b/enzyme/enzyme.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Enzyme v1.2.0 +// Type definitions for Enzyme v2.3.0 // Project: https://github.com/airbnb/enzyme // Definitions by: Marian Palkus , Cap3 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -57,6 +57,34 @@ declare module "enzyme" { */ contains(node: ReactElement): Boolean; + /** + * Returns whether or not a given react element exists in the shallow render tree. + * @param node + */ + containsMatchingElement(node: ReactElement): Boolean; + + /** + * Returns whether or not all the given react elements exists in the shallow render tree + * @param nodes + */ + containsAllMatchingElements(nodes: ReactElement[]): Boolean; + + /** + * Returns whether or not one of the given react elements exists in the shallow render tree. + * @param nodes + */ + containsAnyMatchingElements(nodes: ReactElement[]): Boolean; + + /** + * Returns whether or not the current render tree is equal to the given node, based on the expected value. + */ + equals(node: ReactElement): Boolean; + + /** + * Returns whether or not a given react element matches the shallow render tree. + */ + matchesElement(node: ReactElement): Boolean; + /** * Returns whether or not the current node has a className prop including the passed in class name. * @param className @@ -86,6 +114,13 @@ declare module "enzyme" { children(selector: string): CommonWrapper; children(): CommonWrapper; + /** + * Returns a new wrapper with child at the specified index. + * @param index + */ + childAt(index: Number): CommonWrapper; + childAt(index: Number): CommonWrapper; + /** * Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the * current wrapper. Optionally, a selector can be provided and it will filter the parents by this selector. @@ -157,6 +192,13 @@ declare module "enzyme" { * @param [key] */ state(key?: String): any; + state(key?: String): T; + + /** + * Returns the context hash for the root node of the wrapper. Optionally pass in a prop name and it will return just that value. + */ + context(key?: String): any; + context(key?: String): T; /** * Returns the props hash for the current node of the wrapper. @@ -172,6 +214,13 @@ declare module "enzyme" { * @param key */ prop(key: String): any; + prop(key: String): T; + + /** + * Returns the key value for the node of the current wrapper. + * NOTE: can only be called on a wrapper of a single node. + */ + key(): String; /** * Simulate events. @@ -247,6 +296,11 @@ declare module "enzyme" { */ type(): String | Function; + /** + * Returns the name of the current node of the wrapper. + */ + name(): String; + /** * Iterates through each node of the current wrapper and executes the provided function with a wrapper around * the corresponding node passed in as the first argument. @@ -347,6 +401,13 @@ declare module "enzyme" { children(selector: string): ShallowWrapper; children(): ShallowWrapper; + /** + * Returns a new wrapper with child at the specified index. + * @param index + */ + childAt(index: Number): ShallowWrapper; + childAt(index: Number): ShallowWrapper; + /** * Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the * current wrapper. Optionally, a selector can be provided and it will filter the parents by this selector. @@ -380,6 +441,25 @@ declare module "enzyme" { unmount(): ReactWrapper; mount(): ReactWrapper; + /** + * Returns a wrapper of the node that matches the provided reference name. + * + * NOTE: can only be called on a wrapper instance that is also the root instance. + */ + ref(refName: String): ReactWrapper; + ref(refName: String): ReactWrapper; + + /** + * Detaches the react tree from the DOM. Runs ReactDOM.unmountComponentAtNode() under the hood. + * + * This method will most commonly be used as a "cleanup" method if you decide to use the attachTo option in mount(node, options). + * + * The method is intentionally not "fluent" (in that it doesn't return this) because you should not be doing anything with this wrapper after this method is called. + * + * Using the attachTo is not generally recommended unless it is absolutely necessary to test something. It is your responsibility to clean up after yourself at the end of the test if you do decide to use it, though. + */ + detach() : void; + /** * Find every node in the render tree that matches the provided selector. * @param selector The selector to match. @@ -412,6 +492,13 @@ declare module "enzyme" { children(selector: string): ReactWrapper; children(): ReactWrapper; + /** + * Returns a new wrapper with child at the specified index. + * @param index + */ + childAt(index: Number): ReactWrapper; + childAt(index: Number): ReactWrapper; + /** * Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the * current wrapper. Optionally, a selector can be provided and it will filter the parents by this selector. From ae98aa7dd3b0bac69144340c7771be4aca2c4522 Mon Sep 17 00:00:00 2001 From: Matthias Date: Thu, 26 May 2016 23:11:56 +1000 Subject: [PATCH 134/402] Added Missing third ExecCallback param (stderr) for shelljs (#9417) * Added Missing third ExecCallback param (stderr) for shelljs * Made third ExecCallback parameter optional --- shelljs/shelljs.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/shelljs/shelljs.d.ts b/shelljs/shelljs.d.ts index 949f723ff9..ac501e078c 100644 --- a/shelljs/shelljs.d.ts +++ b/shelljs/shelljs.d.ts @@ -465,7 +465,7 @@ declare module "shelljs" export function exec(command: string, callback: ExecCallback): child.ChildProcess; export interface ExecCallback { - (code: number, output: string): any; + (code: number, output: string, error?: string): any; } export interface ExecOptions { From 3e77642fd96ddef451d39d28533d78d9f87865f5 Mon Sep 17 00:00:00 2001 From: delphinus Date: Thu, 26 May 2016 22:21:52 +0900 Subject: [PATCH 135/402] Add origin() & joinPaths() to urijs (#9419) --- urijs/URIjs.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/urijs/URIjs.d.ts b/urijs/URIjs.d.ts index c7a2630370..8d784ad1ac 100644 --- a/urijs/URIjs.d.ts +++ b/urijs/URIjs.d.ts @@ -52,6 +52,8 @@ declare namespace uri { is(qry: string): boolean; iso8859(): URI; + joinPaths(...paths: (string | URI)[]): URI; + normalize(): URI; normalizeFragment(): URI; normalizeHash(): URI; @@ -63,6 +65,9 @@ declare namespace uri { normalizeQuery(): URI; normalizeSearch(): URI; + origin(): string; + origin(uri: string | URI): URI; + password(): string; password(pw: string): URI; path(): string; From 1a1580dd781db4a0c8b8ab20b44c97be562ce80a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juan=20Luis=20Boya=20Garc=C3=ADa?= Date: Thu, 26 May 2016 15:36:10 +0200 Subject: [PATCH 136/402] Rx: retryWhen (#9422) --- rx/rx-lite.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/rx/rx-lite.d.ts b/rx/rx-lite.d.ts index 3a4ee18450..d44a4d4d9e 100644 --- a/rx/rx-lite.d.ts +++ b/rx/rx-lite.d.ts @@ -325,6 +325,7 @@ declare namespace Rx { materialize(): Observable>; repeat(repeatCount?: number): Observable; retry(retryCount?: number): Observable; + retryWhen(notifier: (errors: Observable) => Observable): Observable; /** * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. From 512ffae8cc7bf150364fecb5db3a6803d961e58f Mon Sep 17 00:00:00 2001 From: thynson Date: Thu, 26 May 2016 21:38:10 +0800 Subject: [PATCH 137/402] Support Array as Value type (#9382) --- knex/knex.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/knex/knex.d.ts b/knex/knex.d.ts index b9c4a9ca12..6fadd1b450 100644 --- a/knex/knex.d.ts +++ b/knex/knex.d.ts @@ -12,7 +12,7 @@ declare module "knex" { type Callback = Function; type Client = Function; - type Value = string|number|boolean|Date; + type Value = string|number|boolean|Date|Array|Array|Array|Array; type ColumnName = string|Knex.Raw|Knex.QueryBuilder; interface Knex extends Knex.QueryInterface { From 37fa4e22fdac9da5babbdc828c178244891e160c Mon Sep 17 00:00:00 2001 From: Dominik Date: Thu, 26 May 2016 15:39:26 +0200 Subject: [PATCH 138/402] Added onFocus prop (#9426) --- react-input-calendar/react-input-calendar.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/react-input-calendar/react-input-calendar.d.ts b/react-input-calendar/react-input-calendar.d.ts index 5dac6aff5d..c511a557d9 100644 --- a/react-input-calendar/react-input-calendar.d.ts +++ b/react-input-calendar/react-input-calendar.d.ts @@ -50,6 +50,10 @@ declare namespace reactInputCalendar { */ onBlur?: (event: __React.SyntheticEvent, computableDate: string) => void; /** + * Set a function that will be triggered when the input field is focused. + */ + onFocus?: (event: __React.SyntheticEvent) => void; + /** * Define state when date picker would close once the user has clicked on a date. */ closeOnSelect?: boolean; From 3a5e413626448a6261a090596f45c40c696f065e Mon Sep 17 00:00:00 2001 From: PascalSenn Date: Thu, 26 May 2016 15:45:27 +0200 Subject: [PATCH 139/402] update(Gridstack): update to version 0.2.5 (#9430) * Update existing function to version 0.2.5 May there are new functions * Update existing tests to version 0.2.5 --- gridstack/gridstack-tests.ts | 12 ++++----- gridstack/gridstack.d.ts | 52 ++++++++++++++++++------------------ 2 files changed, 32 insertions(+), 32 deletions(-) diff --git a/gridstack/gridstack-tests.ts b/gridstack/gridstack-tests.ts index f084e4f46c..3414230a4a 100644 --- a/gridstack/gridstack-tests.ts +++ b/gridstack/gridstack-tests.ts @@ -12,9 +12,9 @@ var options = { }; var gridstack:GridStack = $(document).gridstack(options); -gridstack.add_widget("test", 1, 2, 3, 4, true); -gridstack.batch_update(); -gridstack.cell_height();; -gridstack.cell_height(2); -gridstack.cell_width(); -gridstack.get_cell_from_pixel({ left:20, top: 20 }); +gridstack.addWidget("test", 1, 2, 3, 4, true); +gridstack.batchUpdate(); +gridstack.cellHeight();; +gridstack.cellHeight(2); +gridstack.cellWidth(); +gridstack.getCellFromPixel({ left:20, top: 20 }); diff --git a/gridstack/gridstack.d.ts b/gridstack/gridstack.d.ts index c69770a1b6..399f25e04b 100644 --- a/gridstack/gridstack.d.ts +++ b/gridstack/gridstack.d.ts @@ -11,35 +11,35 @@ interface GridStack { /** * Creates new widget and returns it. * - * Widget will be always placed even if result height is more than actual grid height. You need to use will_it_fit method before calling add_widget for additional check. + * Widget will be always placed even if result height is more than actual grid height. You need to use willItFit method before calling addWidget for additional check. * * @param {string} el widget to add * @param {number} x widget position x * @param {number} y widget position y * @param {number} width widget dimension width * @param {number} height widget dimension height - * @param {boolean} auto_position if true then x, y parameters will be ignored and widget will be places on the first available position + * @param {boolean} autoPosition if true then x, y parameters will be ignored and widget will be places on the first available position */ - add_widget(el: string, x: number, y: number, width: number, height: number, auto_position: boolean): JQuery + addWidget(el: string, x: number, y: number, width: number, height: number, autoPosition: boolean): JQuery /** * Initializes batch updates. You will see no changes until commit method is called. */ - batch_update():void + batchUpdate():void /** * Gets current cell height. */ - cell_height():number + cellHeight():number /** * Update current cell height. This method rebuilds an internal CSS style sheet. Note: You can expect performance issues if call this method too often. * @param {number} val the cell height */ - cell_height(val:number):void + cellHeight(val:number):void /** * Gets current cell width. */ - cell_width():number + cellWidth():number /** - * Finishes batch updates. Updates DOM nodes. You must call it after batch_update. + * Finishes batch updates. Updates DOM nodes. You must call it after batchUpdate. */ commit():void /** @@ -58,7 +58,7 @@ interface GridStack { * Get the position of the cell under a pixel on screen. * @param {MousePosition} position the position of the pixel to resolve in absolute coordinates, as an object with top and leftproperties */ - get_cell_from_pixel(position: MousePosition): CellPosition, + getCellFromPixel(position: MousePosition): CellPosition, /* * Checks if specified area is empty. * @param {number} x the position x. @@ -66,7 +66,7 @@ interface GridStack { * @param {number} width the width of to check * @param {number} height the height of to check */ - is_area_empty(x: number, y: number, width: number, height: number): void + isAreaEmpty(x: number, y: number, width: number, height: number): void /* * Locks/unlocks widget. * @param {HTMLElement} el widget to modify. @@ -78,13 +78,13 @@ interface GridStack { * @param {HTMLElement} el widget to modify. * @param {number} val A numeric value of the number of columns */ - min_width(el: HTMLElement, val: number): void + minWidth(el: HTMLElement, val: number): void /* * Set the minHeight for a widget. * @param {HTMLElement} el widget to modify. * @param {number} val A numeric value of the number of rows */ - min_height(el: HTMLElement, val: number): void + minHeight(el: HTMLElement, val: number): void /* * Enables/Disables moving. * @param {HTMLElement} el widget to modify. @@ -102,13 +102,13 @@ interface GridStack { /** * Removes widget from the grid. * @param {HTMLElement} el widget to modify - * @param {boolean} detach_node if false DOM node won't be removed from the tree (Optional. Default true). + * @param {boolean} detachNode if false DOM node won't be removed from the tree (Optional. Default true). */ - remove_widget(el: HTMLElement, detach_node?: boolean): void + removeWidget(el: HTMLElement, detachNode?: boolean): void /** * Removes all widgets from the grid. */ - remove_all(): void + removeAll(): void /** * Changes widget size * @param {HTMLElement} el widget to modify @@ -124,9 +124,9 @@ interface GridStack { resizable(el: HTMLElement, val: boolean): void /** * Toggle the grid static state. Also toggle the grid-stack-static class. - * @param {boolean} static_value if true the grid become static. + * @param {boolean} staticValue if true the grid become static. */ - set_static(static_value: boolean): void + setStatic(staticValue: boolean): void /** * Updates widget position/size. * @param {HTMLElement} el widget to modify @@ -142,9 +142,9 @@ interface GridStack { * @param {number} y new position y. If value is null or undefined it will be ignored. * @param {number} width new dimensions width. If value is null or undefined it will be ignored. * @param {number} height new dimensions height. If value is null or undefined it will be ignored. - * @param {boolean} auto_position if true then x, y parameters will be ignored and widget will be places on the first available position + * @param {boolean} autoPosition if true then x, y parameters will be ignored and widget will be places on the first available position */ - will_it_fit(x: number, y: number, width: number, height: number, auto_position:boolean):boolean + willItFit(x: number, y: number, width: number, height: number, autoPosition:boolean):boolean } @@ -181,7 +181,7 @@ interface IGridstackOptions { /** * if true the resizing handles are shown even if the user is not hovering over the widget (default: false) */ - always_show_resize_handle: boolean; + alwaysShowResizeHandle: boolean; /** * turns animation on (default: true) */ @@ -193,7 +193,7 @@ interface IGridstackOptions { /** * one cell height (default: 60) */ - cell_height: number; + cellHeight: number; /** * allows to override jQuery UI draggable options. (default: { handle: '.grid-stack-item-content', scroll: true, appendTo: 'body' }) */ @@ -213,15 +213,15 @@ interface IGridstackOptions { /** * widget class (default: 'grid-stack-item') */ - item_class: string; + itemClass: string; /** * minimal width.If window width is less, grid will be shown in one - column mode (default: 768) */ - min_width: number; + minWidth: number; /** * class for placeholder (default: 'grid-stack-placeholder') */ - placeholder_class: string; + placeholderClass: string; /** * allows to override jQuery UI resizable options. (default: { autoHide: true, handles: 'se' }) */ @@ -229,11 +229,11 @@ interface IGridstackOptions { /** * makes grid static (default false).If true widgets are not movable/ resizable.You don't even need jQueryUI draggable/resizable. A CSS class grid-stack-static is also added to the container. */ - static_grid: boolean; + staticGrid: boolean; /** * vertical gap size (default: 20) */ - vertical_margin: number; + verticalMargin: number; /** * amount of columns (default: 12) */ From e8377d3d50a4d814a8d5193473a526226d0caf12 Mon Sep 17 00:00:00 2001 From: Dhananjay Balan Date: Thu, 26 May 2016 19:15:38 +0530 Subject: [PATCH 140/402] Improve z-schema.d.ts (#9427) - add `validateSchema` function to the definitions. --- z-schema/z-schema-tests.ts | 1 + z-schema/z-schema.d.ts | 6 ++++++ 2 files changed, 7 insertions(+) diff --git a/z-schema/z-schema-tests.ts b/z-schema/z-schema-tests.ts index 90fdc4cd32..4dc96a0428 100644 --- a/z-schema/z-schema-tests.ts +++ b/z-schema/z-schema-tests.ts @@ -21,6 +21,7 @@ var schema: any = { }, }; +validator.validateSchema(schema); validator.validate(json, schema); validator.validate(json, schema, function (err: any, valid: boolean) { if (err) { diff --git a/z-schema/z-schema.d.ts b/z-schema/z-schema.d.ts index 83f43bc064..750abd2870 100644 --- a/z-schema/z-schema.d.ts +++ b/z-schema/z-schema.d.ts @@ -39,6 +39,12 @@ declare namespace ZSchema { export class Validator { constructor(options: Options); + /** + * @param schema - JSON object representing schema + * @returns {boolean} true if schema is valid. + */ + validateSchema(schema: any): boolean; + /** * @param json - either a JSON string or a parsed JSON object * @param schema - the JSON object representing the schema From dc619d01b2d39a7064c14852a8262aa1a1f4dcdd Mon Sep 17 00:00:00 2001 From: Jan-Pieter Zoutewelle Date: Thu, 26 May 2016 15:46:01 +0200 Subject: [PATCH 141/402] Added the version of React to the typing. (#9429) * Added version to React typings * Update react.d.ts --- react/react.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/react/react.d.ts b/react/react.d.ts index efe8d8c2e8..4dd185d89c 100644 --- a/react/react.d.ts +++ b/react/react.d.ts @@ -150,7 +150,8 @@ declare namespace __React { var DOM: ReactDOM; var PropTypes: ReactPropTypes; var Children: ReactChildren; - + var version: string; + // // Component API // ---------------------------------------------------------------------- From e8357a2f9dee02d39138923cb6d5db544e996927 Mon Sep 17 00:00:00 2001 From: Danilo Jr Date: Thu, 26 May 2016 11:12:39 -0300 Subject: [PATCH 142/402] Adding some form components in react-bootstrap (#9070) * adding some form components * fix some components type * fix some components type. this fixes issue #9062 --- react-bootstrap/react-bootstrap-tests.tsx | 33 +++++++- react-bootstrap/react-bootstrap.d.ts | 94 ++++++++++++++++++++--- 2 files changed, 117 insertions(+), 10 deletions(-) diff --git a/react-bootstrap/react-bootstrap-tests.tsx b/react-bootstrap/react-bootstrap-tests.tsx index cad2242a38..36d5c1ab23 100644 --- a/react-bootstrap/react-bootstrap-tests.tsx +++ b/react-bootstrap/react-bootstrap-tests.tsx @@ -7,7 +7,7 @@ // -------------------------------------------------------------------------------- import * as React from 'react'; import { Component, CSSProperties } from 'react'; -import { Button, ButtonToolbar, Modal, Well, ButtonGroup, DropdownButton, MenuItem, Panel, ListGroup, ListGroupItem, Accordion, Tooltip, OverlayTrigger, Popover, ProgressBar, Nav, NavItem, Navbar, NavDropdown, Tabs, Tab, Pager, PageItem, Pagination, Alert, Carousel, CarouselItem, Grid, Row, Col, Thumbnail, Label, Badge, Jumbotron, PageHeader, Glyphicon, Table, Input, ButtonInput, FormControls } from 'react-bootstrap'; +import { Button, ButtonToolbar, Modal, Well, ButtonGroup, DropdownButton, MenuItem, Panel, ListGroup, ListGroupItem, Accordion, Tooltip, OverlayTrigger, Popover, ProgressBar, Nav, NavItem, Navbar, NavDropdown, Tabs, Tab, Pager, PageItem, Pagination, Alert, Carousel, CarouselItem, Grid, Row, Col, Thumbnail, Label, Badge, Jumbotron, PageHeader, Glyphicon, Table, Input, ButtonInput, FormControls, Form, FormGroup, ControlLabel, FormControl, HelpBlock, Radio, Checkbox } from 'react-bootstrap'; export class ReactBootstrapTest extends Component { @@ -911,6 +911,37 @@ export class ReactBootstrapTest extends Component {
+ +
+
+ + Control Label + + + Help block message. + + + + 1 + {' '} + 2 + {' '} + 3 + + + 1 + {' '} + 2 + {' '} + 3 + +
+
); } diff --git a/react-bootstrap/react-bootstrap.d.ts b/react-bootstrap/react-bootstrap.d.ts index 9dd6b9bbf1..366eeef7b5 100644 --- a/react-bootstrap/react-bootstrap.d.ts +++ b/react-bootstrap/react-bootstrap.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 +// Definitions by: Walker Burgin , Vincent Siao , Danilo Barros // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -21,7 +21,7 @@ declare module "react-bootstrap" { bsSize?: string; navItem?: boolean; navDropdown?: boolean; - componentClass?: string; + componentClass?: React.ReactType; } type Button = React.ClassicComponent; var Button: React.ClassicComponentClass; @@ -335,7 +335,7 @@ declare module "react-bootstrap" { brand?: any; // TODO: Add more specific type bsSize?: string; bsStyle?: string; - componentClass?: any; // TODO: Add more specific type + componentClass?: React.ReactType; defaultNavExpanded?: boolean; eventKey?: any; fixedBottom?: boolean; @@ -386,7 +386,7 @@ declare module "react-bootstrap" { brand?: any; // TODO: Add more specific type bsSize?: string; bsStyle?: string; - componentClass?: any; // TODO: Add more specific type + componentClass?: React.ReactType; defaultNavExpanded?: boolean; fixedBottom?: boolean; fixedTop?: boolean; @@ -461,7 +461,7 @@ declare module "react-bootstrap" { activePage?: number; bsSize?: string; bsStyle?: string; - buttonComponentClass?: any; // TODO: Add more specific type + buttonComponentClass?: React.ReactType; ellipsis?: boolean; first?: boolean; items?: number; @@ -522,7 +522,7 @@ declare module "react-bootstrap" { // // ---------------------------------------- interface GridProps extends React.HTMLAttributes { - componentClass?: any; // TODO: Add more specific type + componentClass?: React.ReactType; fluid?: boolean; } type Grid = React.ClassicComponent; @@ -531,7 +531,7 @@ declare module "react-bootstrap" { // // ---------------------------------------- interface RowProps extends React.HTMLAttributes { - componentClass?: any; // TODO: Add more specific type + componentClass?: React.ReactType; } type Row = React.ClassicComponent; var Row: React.ClassicComponentClass; @@ -539,7 +539,7 @@ declare module "react-bootstrap" { // // ---------------------------------------- interface ColProps extends React.HTMLAttributes { - componentClass?: any; // TODO: Add more specific type + componentClass?: React.ReactType; lg?: number; lgHidden?: boolean; lgOffset?: number; @@ -615,7 +615,7 @@ declare module "react-bootstrap" { // // ---------------------------------------- interface JumbotronProps extends React.HTMLAttributes { - componentClass?: any; // TODO: Add more specific type + componentClass?: React.ReactType; } type Jumbotron = React.ClassicComponent; var Jumbotron: React.ClassicComponentClass; @@ -710,6 +710,82 @@ declare module "react-bootstrap" { } var FormControls: FormControlsClass; + //
+ // ---------------------------------------- + interface FormProps extends React.HTMLAttributes { + bsClass?: string; + componentClass?: React.ReactType; + horizontal?: boolean; + inline?: boolean; + } + class Form extends React.Component {} + + // + // ---------------------------------------- + interface FormGroupProps extends React.HTMLAttributes { + bsClass?: string; + bsSize?: "sm" | "small" | "lg" | "large"; + controlId?: string; + validationState?: "success" | "warning" | "error"; + } + class FormGroup extends React.Component {} + + // + // ---------------------------------------- + interface ControlLabelProps extends React.HTMLAttributes { + bsClass?: string; + htmlFor?: string; + srOnly?: boolean; + } + class ControlLabel extends React.Component {} + + // + // ---------------------------------------- + interface FormControlFeedbackProps extends React.HTMLAttributes { + } + class FormControlFeedback extends React.Component { + } + + // + // ---------------------------------------- + interface FormControlProps extends React.HTMLAttributes { + bsClass?: string; + componentClass?: React.ReactType; + id?: string; + type?: string; + } + interface FormControlClass extends React.ClassicComponentClass { + Feedback: typeof FormControlFeedback; + } + type FormControl = React.Component; + var FormControl: FormControlClass; + + // + // ---------------------------------------- + interface HelpBlockProps extends React.HTMLAttributes { + bsClass?: string; + } + class HelpBlock extends React.Component {} + + // + // ---------------------------------------- + interface CheckboxProps extends React.HTMLAttributes { + bsClass?: string; + disabled?: boolean; + inline?: boolean; + validationState?: "success" | "warning" | "error"; + } + class Checkbox extends React.Component {} + + // + // ---------------------------------------- + interface RadioProps extends React.HTMLAttributes { + bsClass?: string; + disabled?: boolean; + inline?: boolean; + validationState?: "success" | "warning" | "error"; + } + class Radio extends React.Component {} // // ---------------------------------------- From c851b46f119b93ecfc3010d71a4c8b3761ad356a Mon Sep 17 00:00:00 2001 From: Alex Staroselsky Date: Thu, 26 May 2016 09:13:45 -0500 Subject: [PATCH 143/402] Added interface for Angular Material Prompt Dialog added in 1.1.0-rc1 (2016-03-09) extending IPresetDialog and included cancel() and placeholder() methods. (#9420) --- angular-material/angular-material-tests.ts | 12 ++++++++++++ angular-material/angular-material.d.ts | 6 ++++++ 2 files changed, 18 insertions(+) diff --git a/angular-material/angular-material-tests.ts b/angular-material/angular-material-tests.ts index 3c70dd27e8..cecaf07e67 100644 --- a/angular-material/angular-material-tests.ts +++ b/angular-material/angular-material-tests.ts @@ -55,6 +55,18 @@ myApp.controller('DialogController', ($scope: ng.IScope, $mdDialog: ng.material. $scope['confirmDialog'] = () => { $mdDialog.show($mdDialog.confirm().htmlContent('Confirm!')); }; + $scope['promptDialog'] = () => { + $mdDialog.show($mdDialog.prompt().textContent('Prompt!')); + }; + $scope['promptDialog'] = () => { + $mdDialog.show($mdDialog.prompt().htmlContent('Prompt!')); + }; + $scope['promptDialog'] = () => { + $mdDialog.show($mdDialog.prompt().cancel('Prompt "Cancel" button text')); + }; + $scope['promptDialog'] = () => { + $mdDialog.show($mdDialog.prompt().placeholder('Prompt input placeholder text')); + }; $scope['hideDialog'] = $mdDialog.hide.bind($mdDialog, 'hide'); $scope['cancelDialog'] = $mdDialog.cancel.bind($mdDialog, 'cancel'); }); diff --git a/angular-material/angular-material.d.ts b/angular-material/angular-material.d.ts index 12fe28a9b8..bb144d15d4 100644 --- a/angular-material/angular-material.d.ts +++ b/angular-material/angular-material.d.ts @@ -59,6 +59,11 @@ declare namespace angular.material { interface IConfirmDialog extends IPresetDialog { cancel(cancel: string): IConfirmDialog; } + + interface IPromptDialog extends IPresetDialog { + cancel(cancel: string): IPromptDialog; + placeholder(placeholder: string): IPromptDialog; + } interface IDialogOptions { templateUrl?: string; @@ -90,6 +95,7 @@ declare namespace angular.material { show(dialog: IDialogOptions|IAlertDialog|IConfirmDialog): angular.IPromise; confirm(): IConfirmDialog; alert(): IAlertDialog; + prompt(): IPromptDialog; hide(response?: any): angular.IPromise; cancel(response?: any): void; } From f3fb377beb65b45a619de72f638dd6b487db6116 Mon Sep 17 00:00:00 2001 From: Matthew Wilton Date: Fri, 27 May 2016 00:14:14 +1000 Subject: [PATCH 144/402] Handle mutating promise return types in PDF.js. (#9431) --- pdf/pdf-tests.ts | 7 +++++++ pdf/pdf.d.ts | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/pdf/pdf-tests.ts b/pdf/pdf-tests.ts index 6157307808..07b49644cf 100644 --- a/pdf/pdf-tests.ts +++ b/pdf/pdf-tests.ts @@ -43,3 +43,10 @@ function goNext() { renderPage(pageNum); } } + +// +// Test PDFPromise allows return value mutation +// +var promise: PDFPromise = PDFJS.getDocument('helloworld.pdf').then(pdf => { + return "arbitrary string"; +}); \ No newline at end of file diff --git a/pdf/pdf.d.ts b/pdf/pdf.d.ts index cf74bb658c..9fca2d1af5 100644 --- a/pdf/pdf.d.ts +++ b/pdf/pdf.d.ts @@ -32,7 +32,7 @@ interface PDFPromise { isRejected(): boolean; resolve(value: T): void; reject(reason: string): void; - then(onResolve: (promise: T) => void, onReject?: (reason: string) => void): PDFPromise; + then(onResolve: (promise: T) => U, onReject?: (reason: string) => void): PDFPromise; } interface PDFTreeNode { From be20672826346fb3fdb080b7a040b08fb1f152e4 Mon Sep 17 00:00:00 2001 From: hookclaw Date: Thu, 26 May 2016 23:21:26 +0900 Subject: [PATCH 145/402] Add "express-domain-middleware.d.ts" (#9396) * Add "express-domain-middleware.d.ts" * Add reference comment --- .../express-domain-middleware-tests.ts | 2 ++ .../express-domain-middleware.d.ts | 12 ++++++++++++ 2 files changed, 14 insertions(+) create mode 100644 express-domain-middleware/express-domain-middleware-tests.ts create mode 100644 express-domain-middleware/express-domain-middleware.d.ts diff --git a/express-domain-middleware/express-domain-middleware-tests.ts b/express-domain-middleware/express-domain-middleware-tests.ts new file mode 100644 index 0000000000..446b732353 --- /dev/null +++ b/express-domain-middleware/express-domain-middleware-tests.ts @@ -0,0 +1,2 @@ +/// +import fn = require('express-domain-middleware'); diff --git a/express-domain-middleware/express-domain-middleware.d.ts b/express-domain-middleware/express-domain-middleware.d.ts new file mode 100644 index 0000000000..1710d548e0 --- /dev/null +++ b/express-domain-middleware/express-domain-middleware.d.ts @@ -0,0 +1,12 @@ +// Type definitions for express-domain-middleware +// Project: https://www.npmjs.com/package/express-domain-middleware +// Definitions by: Hookclaw +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "express-domain-middleware" { + import express = require('express'); + function e(req: express.Request, res: express.Response, next: express.NextFunction): any; + export = e; +} From 70a3d231e115630b1e91fad2081dc389cfead090 Mon Sep 17 00:00:00 2001 From: hookclaw Date: Thu, 26 May 2016 23:21:53 +0900 Subject: [PATCH 146/402] Add "istanbul-middleware.d.ts" (#9393) * Add "istanbul-middleware.d.ts" * Add reference comment --- .../istanbul-middleware-tests.ts | 2 ++ istanbul-middleware/istanbul-middleware.d.ts | 33 +++++++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 istanbul-middleware/istanbul-middleware-tests.ts create mode 100644 istanbul-middleware/istanbul-middleware.d.ts diff --git a/istanbul-middleware/istanbul-middleware-tests.ts b/istanbul-middleware/istanbul-middleware-tests.ts new file mode 100644 index 0000000000..01afa92082 --- /dev/null +++ b/istanbul-middleware/istanbul-middleware-tests.ts @@ -0,0 +1,2 @@ +/// +import i = require('istanbul-middleware'); diff --git a/istanbul-middleware/istanbul-middleware.d.ts b/istanbul-middleware/istanbul-middleware.d.ts new file mode 100644 index 0000000000..054e32931e --- /dev/null +++ b/istanbul-middleware/istanbul-middleware.d.ts @@ -0,0 +1,33 @@ +// Type definitions for istanbul-middleware +// Project: https://www.npmjs.com/package/istanbul-middleware +// Definitions by: Hookclaw +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "istanbul-middleware" { + import * as express from "express"; + + type Matcher = (file:string)=> boolean; + type PostLoadHookFn = (file:any)=> {}; + type PostLoadHook = (matcherfn:Matcher,transformer:any,verbose:boolean)=>PostLoadHookFn; + + export function hookLoader(matcherOrRoot:Matcher|string, opts?:{ + postLoadHook?:PostLoadHook, + verbose?:boolean + //and istanbul.Instrumenter(...opts) + }): void; + + export function createHandler(opts?:{ + resetOnGet?:boolean + }): any; + + type ClientMatcher = (req:express.Request)=> boolean; + type PathTransformer = (req:express.Request)=> string; + + export function createClientHandler(root:string,opts?:{ + matcher?:ClientMatcher, + pathTransformer?:PathTransformer, + verbose?:boolean + }): any; +} From 651987be27fe418e8560697b4eafa7f4f500b418 Mon Sep 17 00:00:00 2001 From: hookclaw Date: Thu, 26 May 2016 23:22:13 +0900 Subject: [PATCH 147/402] Add "jsonnet.d.ts" (#9394) * Add "jsonnet.d.ts" * fix comment --- jsonnet/jsonnet-tests.ts | 6 ++++++ jsonnet/jsonnet.d.ts | 13 +++++++++++++ 2 files changed, 19 insertions(+) create mode 100644 jsonnet/jsonnet-tests.ts create mode 100644 jsonnet/jsonnet.d.ts diff --git a/jsonnet/jsonnet-tests.ts b/jsonnet/jsonnet-tests.ts new file mode 100644 index 0000000000..88b3c82bed --- /dev/null +++ b/jsonnet/jsonnet-tests.ts @@ -0,0 +1,6 @@ +/// +import Jsonnet = require('jsonnet'); +var jsonnet = new Jsonnet(); +var code = '{a:1}'; +var result = jsonnet.eval(code); +console.log(result); diff --git a/jsonnet/jsonnet.d.ts b/jsonnet/jsonnet.d.ts new file mode 100644 index 0000000000..5a5aa5b619 --- /dev/null +++ b/jsonnet/jsonnet.d.ts @@ -0,0 +1,13 @@ +// Type definitions for jsonnet +// Project: https://github.com/yosuke-furukawa/node-jsonnet +// Definitions by: Hookclaw +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare module "jsonnet" { + class Jsonnet { + constructor(); + eval(code: string): any; + evalFile(): any; + destroy(): void; + } + export = Jsonnet; +} From edb64e4a35896510ce02b93c0bca5ec3878db738 Mon Sep 17 00:00:00 2001 From: hookclaw Date: Thu, 26 May 2016 23:23:49 +0900 Subject: [PATCH 148/402] Add "locutus.d.ts" (#9395) * Add "locutus.d.ts" * Fix reference comment --- locutus/locutus-tests.ts | 353 ++++++++ locutus/locutus.d.ts | 1734 ++++++++++++++++++++++++++++++++++++++ locutus/locutus_print.ts | 188 +++++ 3 files changed, 2275 insertions(+) create mode 100644 locutus/locutus-tests.ts create mode 100644 locutus/locutus.d.ts create mode 100644 locutus/locutus_print.ts diff --git a/locutus/locutus-tests.ts b/locutus/locutus-tests.ts new file mode 100644 index 0000000000..a465bbd4fa --- /dev/null +++ b/locutus/locutus-tests.ts @@ -0,0 +1,353 @@ +/// +import locutus_c_math_abs = require('locutus/c/math/abs'); +import locutus_golang_strings_Contains = require('locutus/golang/strings/Contains'); +import locutus_golang_strings_Count = require('locutus/golang/strings/Count'); +import locutus_golang_strings_Index = require('locutus/golang/strings/Index'); +import locutus_golang_strings_LastIndex = require('locutus/golang/strings/LastIndex'); +import locutus_php_array_array_change_key_case = require('locutus/php/array/array_change_key_case'); +import locutus_php_array_array_chunk = require('locutus/php/array/array_chunk'); +import locutus_php_array_array_combine = require('locutus/php/array/array_combine'); +import locutus_php_array_array_count_values = require('locutus/php/array/array_count_values'); +import locutus_php_array_array_diff = require('locutus/php/array/array_diff'); +import locutus_php_array_array_diff_assoc = require('locutus/php/array/array_diff_assoc'); +import locutus_php_array_array_diff_key = require('locutus/php/array/array_diff_key'); +import locutus_php_array_array_diff_uassoc = require('locutus/php/array/array_diff_uassoc'); +import locutus_php_array_array_diff_ukey = require('locutus/php/array/array_diff_ukey'); +import locutus_php_array_array_fill = require('locutus/php/array/array_fill'); +import locutus_php_array_array_fill_keys = require('locutus/php/array/array_fill_keys'); +import locutus_php_array_array_filter = require('locutus/php/array/array_filter'); +import locutus_php_array_array_flip = require('locutus/php/array/array_flip'); +import locutus_php_array_array_intersect = require('locutus/php/array/array_intersect'); +import locutus_php_array_array_intersect_assoc = require('locutus/php/array/array_intersect_assoc'); +import locutus_php_array_array_intersect_key = require('locutus/php/array/array_intersect_key'); +import locutus_php_array_array_intersect_uassoc = require('locutus/php/array/array_intersect_uassoc'); +import locutus_php_array_array_intersect_ukey = require('locutus/php/array/array_intersect_ukey'); +import locutus_php_array_array_key_exists = require('locutus/php/array/array_key_exists'); +import locutus_php_array_array_keys = require('locutus/php/array/array_keys'); +import locutus_php_array_array_map = require('locutus/php/array/array_map'); +import locutus_php_array_array_merge = require('locutus/php/array/array_merge'); +import locutus_php_array_array_merge_recursive = require('locutus/php/array/array_merge_recursive'); +import locutus_php_array_array_multisort = require('locutus/php/array/array_multisort'); +import locutus_php_array_array_pad = require('locutus/php/array/array_pad'); +import locutus_php_array_array_pop = require('locutus/php/array/array_pop'); +import locutus_php_array_array_product = require('locutus/php/array/array_product'); +import locutus_php_array_array_push = require('locutus/php/array/array_push'); +import locutus_php_array_array_rand = require('locutus/php/array/array_rand'); +import locutus_php_array_array_reduce = require('locutus/php/array/array_reduce'); +import locutus_php_array_array_replace = require('locutus/php/array/array_replace'); +import locutus_php_array_array_replace_recursive = require('locutus/php/array/array_replace_recursive'); +import locutus_php_array_array_reverse = require('locutus/php/array/array_reverse'); +import locutus_php_array_array_search = require('locutus/php/array/array_search'); +import locutus_php_array_array_shift = require('locutus/php/array/array_shift'); +import locutus_php_array_array_slice = require('locutus/php/array/array_slice'); +import locutus_php_array_array_splice = require('locutus/php/array/array_splice'); +import locutus_php_array_array_sum = require('locutus/php/array/array_sum'); +import locutus_php_array_array_udiff = require('locutus/php/array/array_udiff'); +import locutus_php_array_array_udiff_assoc = require('locutus/php/array/array_udiff_assoc'); +import locutus_php_array_array_udiff_uassoc = require('locutus/php/array/array_udiff_uassoc'); +import locutus_php_array_array_uintersect = require('locutus/php/array/array_uintersect'); +import locutus_php_array_array_uintersect_uassoc = require('locutus/php/array/array_uintersect_uassoc'); +import locutus_php_array_array_unique = require('locutus/php/array/array_unique'); +import locutus_php_array_array_unshift = require('locutus/php/array/array_unshift'); +import locutus_php_array_array_values = require('locutus/php/array/array_values'); +import locutus_php_array_array_walk = require('locutus/php/array/array_walk'); +import locutus_php_array_arsort = require('locutus/php/array/arsort'); +import locutus_php_array_asort = require('locutus/php/array/asort'); +import locutus_php_array_count = require('locutus/php/array/count'); +import locutus_php_array_current = require('locutus/php/array/current'); +import locutus_php_array_each = require('locutus/php/array/each'); +import locutus_php_array_end = require('locutus/php/array/end'); +import locutus_php_array_in_array = require('locutus/php/array/in_array'); +import locutus_php_array_key = require('locutus/php/array/key'); +import locutus_php_array_krsort = require('locutus/php/array/krsort'); +import locutus_php_array_ksort = require('locutus/php/array/ksort'); +import locutus_php_array_natcasesort = require('locutus/php/array/natcasesort'); +import locutus_php_array_natsort = require('locutus/php/array/natsort'); +import locutus_php_array_next = require('locutus/php/array/next'); +import locutus_php_array_pos = require('locutus/php/array/pos'); +import locutus_php_array_prev = require('locutus/php/array/prev'); +import locutus_php_array_range = require('locutus/php/array/range'); +import locutus_php_array_reset = require('locutus/php/array/reset'); +import locutus_php_array_rsort = require('locutus/php/array/rsort'); +import locutus_php_array_shuffle = require('locutus/php/array/shuffle'); +import locutus_php_array_sizeof = require('locutus/php/array/sizeof'); +import locutus_php_array_sort = require('locutus/php/array/sort'); +import locutus_php_array_uasort = require('locutus/php/array/uasort'); +import locutus_php_array_uksort = require('locutus/php/array/uksort'); +import locutus_php_array_usort = require('locutus/php/array/usort'); +import locutus_php_bc_bcadd = require('locutus/php/bc/bcadd'); +import locutus_php_bc_bccomp = require('locutus/php/bc/bccomp'); +import locutus_php_bc_bcdiv = require('locutus/php/bc/bcdiv'); +import locutus_php_bc_bcmul = require('locutus/php/bc/bcmul'); +import locutus_php_bc_bcround = require('locutus/php/bc/bcround'); +import locutus_php_bc_bcscale = require('locutus/php/bc/bcscale'); +import locutus_php_bc_bcsub = require('locutus/php/bc/bcsub'); +import locutus_php_ctype_ctype_alnum = require('locutus/php/ctype/ctype_alnum'); +import locutus_php_ctype_ctype_alpha = require('locutus/php/ctype/ctype_alpha'); +import locutus_php_ctype_ctype_cntrl = require('locutus/php/ctype/ctype_cntrl'); +import locutus_php_ctype_ctype_digit = require('locutus/php/ctype/ctype_digit'); +import locutus_php_ctype_ctype_graph = require('locutus/php/ctype/ctype_graph'); +import locutus_php_ctype_ctype_lower = require('locutus/php/ctype/ctype_lower'); +import locutus_php_ctype_ctype_print = require('locutus/php/ctype/ctype_print'); +import locutus_php_ctype_ctype_punct = require('locutus/php/ctype/ctype_punct'); +import locutus_php_ctype_ctype_space = require('locutus/php/ctype/ctype_space'); +import locutus_php_ctype_ctype_upper = require('locutus/php/ctype/ctype_upper'); +import locutus_php_ctype_ctype_xdigit = require('locutus/php/ctype/ctype_xdigit'); +import locutus_php_datetime_checkdate = require('locutus/php/datetime/checkdate'); +import locutus_php_datetime_date = require('locutus/php/datetime/date'); +import locutus_php_datetime_date_parse = require('locutus/php/datetime/date_parse'); +import locutus_php_datetime_getdate = require('locutus/php/datetime/getdate'); +import locutus_php_datetime_gettimeofday = require('locutus/php/datetime/gettimeofday'); +import locutus_php_datetime_gmdate = require('locutus/php/datetime/gmdate'); +import locutus_php_datetime_gmmktime = require('locutus/php/datetime/gmmktime'); +import locutus_php_datetime_gmstrftime = require('locutus/php/datetime/gmstrftime'); +import locutus_php_datetime_idate = require('locutus/php/datetime/idate'); +import locutus_php_datetime_microtime = require('locutus/php/datetime/microtime'); +import locutus_php_datetime_mktime = require('locutus/php/datetime/mktime'); +import locutus_php_datetime_strftime = require('locutus/php/datetime/strftime'); +import locutus_php_datetime_strptime = require('locutus/php/datetime/strptime'); +import locutus_php_datetime_strtotime = require('locutus/php/datetime/strtotime'); +import locutus_php_datetime_time = require('locutus/php/datetime/time'); +import locutus_php_exec_escapeshellarg = require('locutus/php/exec/escapeshellarg'); +import locutus_php_filesystem_basename = require('locutus/php/filesystem/basename'); +import locutus_php_filesystem_dirname = require('locutus/php/filesystem/dirname'); +import locutus_php_filesystem_file_get_contents = require('locutus/php/filesystem/file_get_contents'); +import locutus_php_filesystem_pathinfo = require('locutus/php/filesystem/pathinfo'); +import locutus_php_filesystem_realpath = require('locutus/php/filesystem/realpath'); +import locutus_php_funchand_call_user_func = require('locutus/php/funchand/call_user_func'); +import locutus_php_funchand_call_user_func_array = require('locutus/php/funchand/call_user_func_array'); +import locutus_php_funchand_create_function = require('locutus/php/funchand/create_function'); +import locutus_php_funchand_function_exists = require('locutus/php/funchand/function_exists'); +import locutus_php_funchand_get_defined_functions = require('locutus/php/funchand/get_defined_functions'); +import locutus_php_i18n_i18n_loc_get_default = require('locutus/php/i18n/i18n_loc_get_default'); +import locutus_php_i18n_i18n_loc_set_default = require('locutus/php/i18n/i18n_loc_set_default'); +import locutus_php_info_assert_options = require('locutus/php/info/assert_options'); +import locutus_php_info_getenv = require('locutus/php/info/getenv'); +import locutus_php_info_ini_get = require('locutus/php/info/ini_get'); +import locutus_php_info_ini_set = require('locutus/php/info/ini_set'); +import locutus_php_info_set_time_limit = require('locutus/php/info/set_time_limit'); +import locutus_php_info_version_compare = require('locutus/php/info/version_compare'); +import locutus_php_json_json_decode = require('locutus/php/json/json_decode'); +import locutus_php_json_json_encode = require('locutus/php/json/json_encode'); +import locutus_php_json_json_last_error = require('locutus/php/json/json_last_error'); +import locutus_php_math_abs = require('locutus/php/math/abs'); +import locutus_php_math_acos = require('locutus/php/math/acos'); +import locutus_php_math_acosh = require('locutus/php/math/acosh'); +import locutus_php_math_asin = require('locutus/php/math/asin'); +import locutus_php_math_asinh = require('locutus/php/math/asinh'); +import locutus_php_math_atan = require('locutus/php/math/atan'); +import locutus_php_math_atan2 = require('locutus/php/math/atan2'); +import locutus_php_math_atanh = require('locutus/php/math/atanh'); +import locutus_php_math_base_convert = require('locutus/php/math/base_convert'); +import locutus_php_math_bindec = require('locutus/php/math/bindec'); +import locutus_php_math_ceil = require('locutus/php/math/ceil'); +import locutus_php_math_cos = require('locutus/php/math/cos'); +import locutus_php_math_cosh = require('locutus/php/math/cosh'); +import locutus_php_math_decbin = require('locutus/php/math/decbin'); +import locutus_php_math_dechex = require('locutus/php/math/dechex'); +import locutus_php_math_decoct = require('locutus/php/math/decoct'); +import locutus_php_math_deg2rad = require('locutus/php/math/deg2rad'); +import locutus_php_math_exp = require('locutus/php/math/exp'); +import locutus_php_math_expm1 = require('locutus/php/math/expm1'); +import locutus_php_math_floor = require('locutus/php/math/floor'); +import locutus_php_math_fmod = require('locutus/php/math/fmod'); +import locutus_php_math_getrandmax = require('locutus/php/math/getrandmax'); +import locutus_php_math_hexdec = require('locutus/php/math/hexdec'); +import locutus_php_math_hypot = require('locutus/php/math/hypot'); +import locutus_php_math_is_finite = require('locutus/php/math/is_finite'); +import locutus_php_math_is_infinite = require('locutus/php/math/is_infinite'); +import locutus_php_math_is_nan = require('locutus/php/math/is_nan'); +import locutus_php_math_lcg_value = require('locutus/php/math/lcg_value'); +import locutus_php_math_log = require('locutus/php/math/log'); +import locutus_php_math_log10 = require('locutus/php/math/log10'); +import locutus_php_math_log1p = require('locutus/php/math/log1p'); +import locutus_php_math_max = require('locutus/php/math/max'); +import locutus_php_math_min = require('locutus/php/math/min'); +import locutus_php_math_mt_getrandmax = require('locutus/php/math/mt_getrandmax'); +import locutus_php_math_mt_rand = require('locutus/php/math/mt_rand'); +import locutus_php_math_octdec = require('locutus/php/math/octdec'); +import locutus_php_math_pi = require('locutus/php/math/pi'); +import locutus_php_math_pow = require('locutus/php/math/pow'); +import locutus_php_math_rad2deg = require('locutus/php/math/rad2deg'); +import locutus_php_math_rand = require('locutus/php/math/rand'); +import locutus_php_math_round = require('locutus/php/math/round'); +import locutus_php_math_sin = require('locutus/php/math/sin'); +import locutus_php_math_sinh = require('locutus/php/math/sinh'); +import locutus_php_math_sqrt = require('locutus/php/math/sqrt'); +import locutus_php_math_tan = require('locutus/php/math/tan'); +import locutus_php_math_tanh = require('locutus/php/math/tanh'); +import locutus_php_misc_pack = require('locutus/php/misc/pack'); +import locutus_php_misc_uniqid = require('locutus/php/misc/uniqid'); +import locutus_php_net_gopher_gopher_parsedir = require('locutus/php/net-gopher/gopher_parsedir'); +import locutus_php_network_inet_ntop = require('locutus/php/network/inet_ntop'); +import locutus_php_network_inet_pton = require('locutus/php/network/inet_pton'); +import locutus_php_network_ip2long = require('locutus/php/network/ip2long'); +import locutus_php_network_long2ip = require('locutus/php/network/long2ip'); +import locutus_php_network_setcookie = require('locutus/php/network/setcookie'); +import locutus_php_network_setrawcookie = require('locutus/php/network/setrawcookie'); +import locutus_php_pcre_preg_quote = require('locutus/php/pcre/preg_quote'); +import locutus_php_pcre_sql_regcase = require('locutus/php/pcre/sql_regcase'); +import locutus_php_strings_addcslashes = require('locutus/php/strings/addcslashes'); +import locutus_php_strings_addslashes = require('locutus/php/strings/addslashes'); +import locutus_php_strings_bin2hex = require('locutus/php/strings/bin2hex'); +import locutus_php_strings_chop = require('locutus/php/strings/chop'); +import locutus_php_strings_chr = require('locutus/php/strings/chr'); +import locutus_php_strings_chunk_split = require('locutus/php/strings/chunk_split'); +import locutus_php_strings_convert_cyr_string = require('locutus/php/strings/convert_cyr_string'); +import locutus_php_strings_convert_uuencode = require('locutus/php/strings/convert_uuencode'); +import locutus_php_strings_count_chars = require('locutus/php/strings/count_chars'); +import locutus_php_strings_crc32 = require('locutus/php/strings/crc32'); +import locutus_php_strings_echo = require('locutus/php/strings/echo'); +import locutus_php_strings_explode = require('locutus/php/strings/explode'); +import locutus_php_strings_get_html_translation_table = require('locutus/php/strings/get_html_translation_table'); +import locutus_php_strings_hex2bin = require('locutus/php/strings/hex2bin'); +import locutus_php_strings_html_entity_decode = require('locutus/php/strings/html_entity_decode'); +import locutus_php_strings_htmlentities = require('locutus/php/strings/htmlentities'); +import locutus_php_strings_htmlspecialchars = require('locutus/php/strings/htmlspecialchars'); +import locutus_php_strings_htmlspecialchars_decode = require('locutus/php/strings/htmlspecialchars_decode'); +import locutus_php_strings_implode = require('locutus/php/strings/implode'); +import locutus_php_strings_join = require('locutus/php/strings/join'); +import locutus_php_strings_lcfirst = require('locutus/php/strings/lcfirst'); +import locutus_php_strings_levenshtein = require('locutus/php/strings/levenshtein'); +import locutus_php_strings_localeconv = require('locutus/php/strings/localeconv'); +import locutus_php_strings_ltrim = require('locutus/php/strings/ltrim'); +import locutus_php_strings_md5 = require('locutus/php/strings/md5'); +import locutus_php_strings_md5_file = require('locutus/php/strings/md5_file'); +import locutus_php_strings_metaphone = require('locutus/php/strings/metaphone'); +import locutus_php_strings_money_format = require('locutus/php/strings/money_format'); +import locutus_php_strings_nl2br = require('locutus/php/strings/nl2br'); +import locutus_php_strings_nl_langinfo = require('locutus/php/strings/nl_langinfo'); +import locutus_php_strings_number_format = require('locutus/php/strings/number_format'); +import locutus_php_strings_ord = require('locutus/php/strings/ord'); +import locutus_php_strings_parse_str = require('locutus/php/strings/parse_str'); +import locutus_php_strings_printf = require('locutus/php/strings/printf'); +import locutus_php_strings_quoted_printable_decode = require('locutus/php/strings/quoted_printable_decode'); +import locutus_php_strings_quoted_printable_encode = require('locutus/php/strings/quoted_printable_encode'); +import locutus_php_strings_quotemeta = require('locutus/php/strings/quotemeta'); +import locutus_php_strings_rtrim = require('locutus/php/strings/rtrim'); +import locutus_php_strings_setlocale = require('locutus/php/strings/setlocale'); +import locutus_php_strings_sha1 = require('locutus/php/strings/sha1'); +import locutus_php_strings_sha1_file = require('locutus/php/strings/sha1_file'); +import locutus_php_strings_similar_text = require('locutus/php/strings/similar_text'); +import locutus_php_strings_soundex = require('locutus/php/strings/soundex'); +import locutus_php_strings_split = require('locutus/php/strings/split'); +import locutus_php_strings_sprintf = require('locutus/php/strings/sprintf'); +import locutus_php_strings_sscanf = require('locutus/php/strings/sscanf'); +import locutus_php_strings_str_getcsv = require('locutus/php/strings/str_getcsv'); +import locutus_php_strings_str_ireplace = require('locutus/php/strings/str_ireplace'); +import locutus_php_strings_str_pad = require('locutus/php/strings/str_pad'); +import locutus_php_strings_str_repeat = require('locutus/php/strings/str_repeat'); +import locutus_php_strings_str_replace = require('locutus/php/strings/str_replace'); +import locutus_php_strings_str_rot13 = require('locutus/php/strings/str_rot13'); +import locutus_php_strings_str_shuffle = require('locutus/php/strings/str_shuffle'); +import locutus_php_strings_str_split = require('locutus/php/strings/str_split'); +import locutus_php_strings_str_word_count = require('locutus/php/strings/str_word_count'); +import locutus_php_strings_strcasecmp = require('locutus/php/strings/strcasecmp'); +import locutus_php_strings_strchr = require('locutus/php/strings/strchr'); +import locutus_php_strings_strcmp = require('locutus/php/strings/strcmp'); +import locutus_php_strings_strcoll = require('locutus/php/strings/strcoll'); +import locutus_php_strings_strcspn = require('locutus/php/strings/strcspn'); +import locutus_php_strings_strip_tags = require('locutus/php/strings/strip_tags'); +import locutus_php_strings_stripos = require('locutus/php/strings/stripos'); +import locutus_php_strings_stripslashes = require('locutus/php/strings/stripslashes'); +import locutus_php_strings_stristr = require('locutus/php/strings/stristr'); +import locutus_php_strings_strlen = require('locutus/php/strings/strlen'); +import locutus_php_strings_strnatcasecmp = require('locutus/php/strings/strnatcasecmp'); +import locutus_php_strings_strnatcmp = require('locutus/php/strings/strnatcmp'); +import locutus_php_strings_strncasecmp = require('locutus/php/strings/strncasecmp'); +import locutus_php_strings_strncmp = require('locutus/php/strings/strncmp'); +import locutus_php_strings_strpbrk = require('locutus/php/strings/strpbrk'); +import locutus_php_strings_strpos = require('locutus/php/strings/strpos'); +import locutus_php_strings_strrchr = require('locutus/php/strings/strrchr'); +import locutus_php_strings_strrev = require('locutus/php/strings/strrev'); +import locutus_php_strings_strripos = require('locutus/php/strings/strripos'); +import locutus_php_strings_strrpos = require('locutus/php/strings/strrpos'); +import locutus_php_strings_strspn = require('locutus/php/strings/strspn'); +import locutus_php_strings_strstr = require('locutus/php/strings/strstr'); +import locutus_php_strings_strtok = require('locutus/php/strings/strtok'); +import locutus_php_strings_strtolower = require('locutus/php/strings/strtolower'); +import locutus_php_strings_strtoupper = require('locutus/php/strings/strtoupper'); +import locutus_php_strings_strtr = require('locutus/php/strings/strtr'); +import locutus_php_strings_substr = require('locutus/php/strings/substr'); +import locutus_php_strings_substr_compare = require('locutus/php/strings/substr_compare'); +import locutus_php_strings_substr_count = require('locutus/php/strings/substr_count'); +import locutus_php_strings_substr_replace = require('locutus/php/strings/substr_replace'); +import locutus_php_strings_trim = require('locutus/php/strings/trim'); +import locutus_php_strings_ucfirst = require('locutus/php/strings/ucfirst'); +import locutus_php_strings_ucwords = require('locutus/php/strings/ucwords'); +import locutus_php_strings_vprintf = require('locutus/php/strings/vprintf'); +import locutus_php_strings_vsprintf = require('locutus/php/strings/vsprintf'); +import locutus_php_strings_wordwrap = require('locutus/php/strings/wordwrap'); +import locutus_php_url_base64_decode = require('locutus/php/url/base64_decode'); +import locutus_php_url_base64_encode = require('locutus/php/url/base64_encode'); +import locutus_php_url_http_build_query = require('locutus/php/url/http_build_query'); +import locutus_php_url_parse_url = require('locutus/php/url/parse_url'); +import locutus_php_url_rawurldecode = require('locutus/php/url/rawurldecode'); +import locutus_php_url_rawurlencode = require('locutus/php/url/rawurlencode'); +import locutus_php_url_urldecode = require('locutus/php/url/urldecode'); +import locutus_php_url_urlencode = require('locutus/php/url/urlencode'); +import locutus_php_var_doubleval = require('locutus/php/var/doubleval'); +import locutus_php_var_empty = require('locutus/php/var/empty'); +import locutus_php_var_floatval = require('locutus/php/var/floatval'); +import locutus_php_var_gettype = require('locutus/php/var/gettype'); +import locutus_php_var_intval = require('locutus/php/var/intval'); +import locutus_php_var_is_array = require('locutus/php/var/is_array'); +import locutus_php_var_is_binary = require('locutus/php/var/is_binary'); +import locutus_php_var_is_bool = require('locutus/php/var/is_bool'); +import locutus_php_var_is_buffer = require('locutus/php/var/is_buffer'); +import locutus_php_var_is_callable = require('locutus/php/var/is_callable'); +import locutus_php_var_is_double = require('locutus/php/var/is_double'); +import locutus_php_var_is_float = require('locutus/php/var/is_float'); +import locutus_php_var_is_int = require('locutus/php/var/is_int'); +import locutus_php_var_is_integer = require('locutus/php/var/is_integer'); +import locutus_php_var_is_long = require('locutus/php/var/is_long'); +import locutus_php_var_is_null = require('locutus/php/var/is_null'); +import locutus_php_var_is_numeric = require('locutus/php/var/is_numeric'); +import locutus_php_var_is_object = require('locutus/php/var/is_object'); +import locutus_php_var_is_real = require('locutus/php/var/is_real'); +import locutus_php_var_is_scalar = require('locutus/php/var/is_scalar'); +import locutus_php_var_is_string = require('locutus/php/var/is_string'); +import locutus_php_var_is_unicode = require('locutus/php/var/is_unicode'); +import locutus_php_var_isset = require('locutus/php/var/isset'); +import locutus_php_var_print_r = require('locutus/php/var/print_r'); +import locutus_php_var_serialize = require('locutus/php/var/serialize'); +import locutus_php_var_strval = require('locutus/php/var/strval'); +import locutus_php_var_unserialize = require('locutus/php/var/unserialize'); +import locutus_php_var_var_dump = require('locutus/php/var/var_dump'); +import locutus_php_var_var_export = require('locutus/php/var/var_export'); +import locutus_php_xdiff_xdiff_string_diff = require('locutus/php/xdiff/xdiff_string_diff'); +import locutus_php_xdiff_xdiff_string_patch = require('locutus/php/xdiff/xdiff_string_patch'); +import locutus_php_xml_utf8_decode = require('locutus/php/xml/utf8_decode'); +import locutus_php_xml_utf8_encode = require('locutus/php/xml/utf8_encode'); +import locutus_python_string_capwords = require('locutus/python/string/capwords'); +import locutus_ruby_Math_acos = require('locutus/ruby/Math/acos'); +import locutus_c_math = require('locutus/c/math'); +import locutus_golang_strings = require('locutus/golang/strings'); +import locutus_php_array = require('locutus/php/array'); +import locutus_php_bc = require('locutus/php/bc'); +import locutus_php_ctype = require('locutus/php/ctype'); +import locutus_php_datetime = require('locutus/php/datetime'); +import locutus_php_exec = require('locutus/php/exec'); +import locutus_php_filesystem = require('locutus/php/filesystem'); +import locutus_php_funchand = require('locutus/php/funchand'); +import locutus_php_i18n = require('locutus/php/i18n'); +import locutus_php_info = require('locutus/php/info'); +import locutus_php_json = require('locutus/php/json'); +import locutus_php_math = require('locutus/php/math'); +import locutus_php_misc = require('locutus/php/misc'); +import locutus_php_net_gopher = require('locutus/php/net-gopher'); +import locutus_php_network = require('locutus/php/network'); +import locutus_php_pcre = require('locutus/php/pcre'); +import locutus_php_strings = require('locutus/php/strings'); +import locutus_php_url = require('locutus/php/url'); +import locutus_php_var = require('locutus/php/var'); +import locutus_php_xdiff = require('locutus/php/xdiff'); +import locutus_php_xml = require('locutus/php/xml'); +import locutus_python_string = require('locutus/python/string'); +import locutus_ruby_Math = require('locutus/ruby/Math'); +import locutus_c = require('locutus/c'); +import locutus_golang = require('locutus/golang'); +import locutus_php = require('locutus/php'); +import locutus_python = require('locutus/python'); +import locutus_ruby = require('locutus/ruby'); +import locutus = require('locutus'); diff --git a/locutus/locutus.d.ts b/locutus/locutus.d.ts new file mode 100644 index 0000000000..4e1077a937 --- /dev/null +++ b/locutus/locutus.d.ts @@ -0,0 +1,1734 @@ +// Type definitions for locutus +// Project: http://locutusjs.io +// Definitions by: Hookclaw +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "locutus/c/math/abs" { + function abs(mixedNumber?:any):any; + export = abs; +} +declare module "locutus/golang/strings/Contains" { + function Contains(s?:any, substr?:any):any; + export = Contains; +} +declare module "locutus/golang/strings/Count" { + function Count(s?:any, sep?:any):any; + export = Count; +} +declare module "locutus/golang/strings/Index" { + function Index(s?:any, sep?:any):any; + export = Index; +} +declare module "locutus/golang/strings/LastIndex" { + function LastIndex(s?:any, sep?:any):any; + export = LastIndex; +} +declare module "locutus/php/array/array_change_key_case" { + function array_change_key_case(array?:any, cs?:any):any; + export = array_change_key_case; +} +declare module "locutus/php/array/array_chunk" { + function array_chunk(input?:any, size?:any, preserveKeys?:any):any; + export = array_chunk; +} +declare module "locutus/php/array/array_combine" { + function array_combine(keys?:any, values?:any):any; + export = array_combine; +} +declare module "locutus/php/array/array_count_values" { + function array_count_values(array?:any):any; + export = array_count_values; +} +declare module "locutus/php/array/array_diff" { + function array_diff(...args:any[]):any; + export = array_diff; +} +declare module "locutus/php/array/array_diff_assoc" { + function array_diff_assoc(...args:any[]):any; + export = array_diff_assoc; +} +declare module "locutus/php/array/array_diff_key" { + function array_diff_key(...args:any[]):any; + export = array_diff_key; +} +declare module "locutus/php/array/array_diff_uassoc" { + function array_diff_uassoc(...args:any[]):any; + export = array_diff_uassoc; +} +declare module "locutus/php/array/array_diff_ukey" { + function array_diff_ukey(...args:any[]):any; + export = array_diff_ukey; +} +declare module "locutus/php/array/array_fill" { + function array_fill(startIndex?:any, num?:any, mixedVal?:any):any; + export = array_fill; +} +declare module "locutus/php/array/array_fill_keys" { + function array_fill_keys(keys?:any, value?:any):any; + export = array_fill_keys; +} +declare module "locutus/php/array/array_filter" { + function array_filter(arr?:any, func?:any):any; + export = array_filter; +} +declare module "locutus/php/array/array_flip" { + function array_flip(trans?:any):any; + export = array_flip; +} +declare module "locutus/php/array/array_intersect" { + function array_intersect(...args:any[]):any; + export = array_intersect; +} +declare module "locutus/php/array/array_intersect_assoc" { + function array_intersect_assoc(...args:any[]):any; + export = array_intersect_assoc; +} +declare module "locutus/php/array/array_intersect_key" { + function array_intersect_key(...args:any[]):any; + export = array_intersect_key; +} +declare module "locutus/php/array/array_intersect_uassoc" { + function array_intersect_uassoc(...args:any[]):any; + export = array_intersect_uassoc; +} +declare module "locutus/php/array/array_intersect_ukey" { + function array_intersect_ukey(...args:any[]):any; + export = array_intersect_ukey; +} +declare module "locutus/php/array/array_key_exists" { + function array_key_exists(key?:any, search?:any):any; + export = array_key_exists; +} +declare module "locutus/php/array/array_keys" { + function array_keys(input?:any, searchValue?:any, argStrict?:any):any; + export = array_keys; +} +declare module "locutus/php/array/array_map" { + function array_map(...args:any[]):any; + export = array_map; +} +declare module "locutus/php/array/array_merge" { + function array_merge(...args:any[]):any; + export = array_merge; +} +declare module "locutus/php/array/array_merge_recursive" { + function array_merge_recursive(arr1?:any, arr2?:any):any; + export = array_merge_recursive; +} +declare module "locutus/php/array/array_multisort" { + function array_multisort(...args:any[]):any; + export = array_multisort; +} +declare module "locutus/php/array/array_pad" { + function array_pad(input?:any, padSize?:any, padValue?:any):any; + export = array_pad; +} +declare module "locutus/php/array/array_pop" { + function array_pop(inputArr?:any):any; + export = array_pop; +} +declare module "locutus/php/array/array_product" { + function array_product(input?:any):any; + export = array_product; +} +declare module "locutus/php/array/array_push" { + function array_push(...args:any[]):any; + export = array_push; +} +declare module "locutus/php/array/array_rand" { + function array_rand(input?:any, numReq?:any):any; + export = array_rand; +} +declare module "locutus/php/array/array_reduce" { + function array_reduce(aInput?:any, callback?:any):any; + export = array_reduce; +} +declare module "locutus/php/array/array_replace" { + function array_replace(...args:any[]):any; + export = array_replace; +} +declare module "locutus/php/array/array_replace_recursive" { + function array_replace_recursive(...args:any[]):any; + export = array_replace_recursive; +} +declare module "locutus/php/array/array_reverse" { + function array_reverse(array?:any, preserveKeys?:any):any; + export = array_reverse; +} +declare module "locutus/php/array/array_search" { + function array_search(needle?:any, haystack?:any, argStrict?:any):any; + export = array_search; +} +declare module "locutus/php/array/array_shift" { + function array_shift(inputArr?:any):any; + export = array_shift; +} +declare module "locutus/php/array/array_slice" { + function array_slice(arr?:any, offst?:any, lgth?:any, preserveKeys?:any):any; + export = array_slice; +} +declare module "locutus/php/array/array_splice" { + function array_splice(arr?:any, offst?:any, lgth?:any, replacement?:any):any; + export = array_splice; +} +declare module "locutus/php/array/array_sum" { + function array_sum(array?:any):any; + export = array_sum; +} +declare module "locutus/php/array/array_udiff" { + function array_udiff(...args:any[]):any; + export = array_udiff; +} +declare module "locutus/php/array/array_udiff_assoc" { + function array_udiff_assoc(...args:any[]):any; + export = array_udiff_assoc; +} +declare module "locutus/php/array/array_udiff_uassoc" { + function array_udiff_uassoc(...args:any[]):any; + export = array_udiff_uassoc; +} +declare module "locutus/php/array/array_uintersect" { + function array_uintersect(...args:any[]):any; + export = array_uintersect; +} +declare module "locutus/php/array/array_uintersect_uassoc" { + function array_uintersect_uassoc(...args:any[]):any; + export = array_uintersect_uassoc; +} +declare module "locutus/php/array/array_unique" { + function array_unique(inputArr?:any):any; + export = array_unique; +} +declare module "locutus/php/array/array_unshift" { + function array_unshift(...args:any[]):any; + export = array_unshift; +} +declare module "locutus/php/array/array_values" { + function array_values(input?:any):any; + export = array_values; +} +declare module "locutus/php/array/array_walk" { + function array_walk(...args:any[]):any; + export = array_walk; +} +declare module "locutus/php/array/arsort" { + function arsort(inputArr?:any, sortFlags?:any):any; + export = arsort; +} +declare module "locutus/php/array/asort" { + function asort(inputArr?:any, sortFlags?:any):any; + export = asort; +} +declare module "locutus/php/array/count" { + function count(mixedVar?:any, mode?:any):any; + export = count; +} +declare module "locutus/php/array/current" { + function current(arr?:any):any; + export = current; +} +declare module "locutus/php/array/each" { + function each(arr?:any):any; + export = each; +} +declare module "locutus/php/array/end" { + function end(arr?:any):any; + export = end; +} +declare module "locutus/php/array/in_array" { + function in_array(needle?:any, haystack?:any, argStrict?:any):any; + export = in_array; +} +declare module "locutus/php/array/key" { + function key(arr?:any):any; + export = key; +} +declare module "locutus/php/array/krsort" { + function krsort(inputArr?:any, sortFlags?:any):any; + export = krsort; +} +declare module "locutus/php/array/ksort" { + function ksort(inputArr?:any, sortFlags?:any):any; + export = ksort; +} +declare module "locutus/php/array/natcasesort" { + function natcasesort(inputArr?:any):any; + export = natcasesort; +} +declare module "locutus/php/array/natsort" { + function natsort(inputArr?:any):any; + export = natsort; +} +declare module "locutus/php/array/next" { + function next(arr?:any):any; + export = next; +} +declare module "locutus/php/array/pos" { + function pos(arr?:any):any; + export = pos; +} +declare module "locutus/php/array/prev" { + function prev(arr?:any):any; + export = prev; +} +declare module "locutus/php/array/range" { + function range(low?:any, high?:any, step?:any):any; + export = range; +} +declare module "locutus/php/array/reset" { + function reset(arr?:any):any; + export = reset; +} +declare module "locutus/php/array/rsort" { + function rsort(inputArr?:any, sortFlags?:any):any; + export = rsort; +} +declare module "locutus/php/array/shuffle" { + function shuffle(inputArr?:any):any; + export = shuffle; +} +declare module "locutus/php/array/sizeof" { + function sizeof(mixedVar?:any, mode?:any):any; + export = sizeof; +} +declare module "locutus/php/array/sort" { + function sort(inputArr?:any, sortFlags?:any):any; + export = sort; +} +declare module "locutus/php/array/uasort" { + function uasort(inputArr?:any, sorter?:any):any; + export = uasort; +} +declare module "locutus/php/array/uksort" { + function uksort(inputArr?:any, sorter?:any):any; + export = uksort; +} +declare module "locutus/php/array/usort" { + function usort(inputArr?:any, sorter?:any):any; + export = usort; +} +declare module "locutus/php/bc/bcadd" { + function bcadd(leftOperand?:any, rightOperand?:any, scale?:any):any; + export = bcadd; +} +declare module "locutus/php/bc/bccomp" { + function bccomp(leftOperand?:any, rightOperand?:any, scale?:any):any; + export = bccomp; +} +declare module "locutus/php/bc/bcdiv" { + function bcdiv(leftOperand?:any, rightOperand?:any, scale?:any):any; + export = bcdiv; +} +declare module "locutus/php/bc/bcmul" { + function bcmul(leftOperand?:any, rightOperand?:any, scale?:any):any; + export = bcmul; +} +declare module "locutus/php/bc/bcround" { + function bcround(val?:any, precision?:any):any; + export = bcround; +} +declare module "locutus/php/bc/bcscale" { + function bcscale(scale?:any):any; + export = bcscale; +} +declare module "locutus/php/bc/bcsub" { + function bcsub(leftOperand?:any, rightOperand?:any, scale?:any):any; + export = bcsub; +} +declare module "locutus/php/ctype/ctype_alnum" { + function ctype_alnum(text?:any):any; + export = ctype_alnum; +} +declare module "locutus/php/ctype/ctype_alpha" { + function ctype_alpha(text?:any):any; + export = ctype_alpha; +} +declare module "locutus/php/ctype/ctype_cntrl" { + function ctype_cntrl(text?:any):any; + export = ctype_cntrl; +} +declare module "locutus/php/ctype/ctype_digit" { + function ctype_digit(text?:any):any; + export = ctype_digit; +} +declare module "locutus/php/ctype/ctype_graph" { + function ctype_graph(text?:any):any; + export = ctype_graph; +} +declare module "locutus/php/ctype/ctype_lower" { + function ctype_lower(text?:any):any; + export = ctype_lower; +} +declare module "locutus/php/ctype/ctype_print" { + function ctype_print(text?:any):any; + export = ctype_print; +} +declare module "locutus/php/ctype/ctype_punct" { + function ctype_punct(text?:any):any; + export = ctype_punct; +} +declare module "locutus/php/ctype/ctype_space" { + function ctype_space(text?:any):any; + export = ctype_space; +} +declare module "locutus/php/ctype/ctype_upper" { + function ctype_upper(text?:any):any; + export = ctype_upper; +} +declare module "locutus/php/ctype/ctype_xdigit" { + function ctype_xdigit(text?:any):any; + export = ctype_xdigit; +} +declare module "locutus/php/datetime/checkdate" { + function checkdate(m?:any, d?:any, y?:any):any; + export = checkdate; +} +declare module "locutus/php/datetime/date" { + function date(format?:any, timestamp?:any):any; + export = date; +} +declare module "locutus/php/datetime/date_parse" { + function date_parse(date?:any):any; + export = date_parse; +} +declare module "locutus/php/datetime/getdate" { + function getdate(timestamp?:any):any; + export = getdate; +} +declare module "locutus/php/datetime/gettimeofday" { + function gettimeofday(returnFloat?:any):any; + export = gettimeofday; +} +declare module "locutus/php/datetime/gmdate" { + function gmdate(format?:any, timestamp?:any):any; + export = gmdate; +} +declare module "locutus/php/datetime/gmmktime" { + function gmmktime(...args:any[]):any; + export = gmmktime; +} +declare module "locutus/php/datetime/gmstrftime" { + function gmstrftime(format?:any, timestamp?:any):any; + export = gmstrftime; +} +declare module "locutus/php/datetime/idate" { + function idate(format?:any, timestamp?:any):any; + export = idate; +} +declare module "locutus/php/datetime/microtime" { + function microtime(getAsFloat?:any):any; + export = microtime; +} +declare module "locutus/php/datetime/mktime" { + function mktime(...args:any[]):any; + export = mktime; +} +declare module "locutus/php/datetime/strftime" { + function strftime(fmt?:any, timestamp?:any):any; + export = strftime; +} +declare module "locutus/php/datetime/strptime" { + function strptime(dateStr?:any, format?:any):any; + export = strptime; +} +declare module "locutus/php/datetime/strtotime" { + function strtotime(text?:any, now?:any):any; + export = strtotime; +} +declare module "locutus/php/datetime/time" { + function time():any; + export = time; +} +declare module "locutus/php/exec/escapeshellarg" { + function escapeshellarg(arg?:any):any; + export = escapeshellarg; +} +declare module "locutus/php/filesystem/basename" { + function basename(path?:any, suffix?:any):any; + export = basename; +} +declare module "locutus/php/filesystem/dirname" { + function dirname(path?:any):any; + export = dirname; +} +declare module "locutus/php/filesystem/file_get_contents" { + function file_get_contents(url?:any, flags?:any, context?:any, offset?:any, maxLen?:any):any; + export = file_get_contents; +} +declare module "locutus/php/filesystem/pathinfo" { + function pathinfo(...args:any[]):any; + export = pathinfo; +} +declare module "locutus/php/filesystem/realpath" { + function realpath(path?:any):any; + export = realpath; +} +declare module "locutus/php/funchand/call_user_func" { + function call_user_func(...args:any[]):any; + export = call_user_func; +} +declare module "locutus/php/funchand/call_user_func_array" { + function call_user_func_array(cb?:any, parameters?:any):any; + export = call_user_func_array; +} +declare module "locutus/php/funchand/create_function" { + function create_function(args?:any, code?:any):any; + export = create_function; +} +declare module "locutus/php/funchand/function_exists" { + function function_exists(funcName?:any):any; + export = function_exists; +} +declare module "locutus/php/funchand/get_defined_functions" { + function get_defined_functions():any; + export = get_defined_functions; +} +declare module "locutus/php/i18n/i18n_loc_get_default" { + function i18n_loc_get_default():any; + export = i18n_loc_get_default; +} +declare module "locutus/php/i18n/i18n_loc_set_default" { + function i18n_loc_set_default(name?:any):any; + export = i18n_loc_set_default; +} +declare module "locutus/php/info/assert_options" { + function assert_options(what?:any, value?:any):any; + export = assert_options; +} +declare module "locutus/php/info/getenv" { + function getenv(varname?:any):any; + export = getenv; +} +declare module "locutus/php/info/ini_get" { + function ini_get(varname?:any):any; + export = ini_get; +} +declare module "locutus/php/info/ini_set" { + function ini_set(varname?:any, newvalue?:any):any; + export = ini_set; +} +declare module "locutus/php/info/set_time_limit" { + function set_time_limit(seconds?:any):any; + export = set_time_limit; +} +declare module "locutus/php/info/version_compare" { + function version_compare(v1?:any, v2?:any, operator?:any):any; + export = version_compare; +} +declare module "locutus/php/json/json_decode" { + function json_decode(strJson?:any):any; + export = json_decode; +} +declare module "locutus/php/json/json_encode" { + function json_encode(mixedVal?:any):any; + export = json_encode; +} +declare module "locutus/php/json/json_last_error" { + function json_last_error():any; + export = json_last_error; +} +declare module "locutus/php/math/abs" { + function abs(mixedNumber?:any):any; + export = abs; +} +declare module "locutus/php/math/acos" { + function acos(arg?:any):any; + export = acos; +} +declare module "locutus/php/math/acosh" { + function acosh(arg?:any):any; + export = acosh; +} +declare module "locutus/php/math/asin" { + function asin(arg?:any):any; + export = asin; +} +declare module "locutus/php/math/asinh" { + function asinh(arg?:any):any; + export = asinh; +} +declare module "locutus/php/math/atan" { + function atan(arg?:any):any; + export = atan; +} +declare module "locutus/php/math/atan2" { + function atan2(y?:any, x?:any):any; + export = atan2; +} +declare module "locutus/php/math/atanh" { + function atanh(arg?:any):any; + export = atanh; +} +declare module "locutus/php/math/base_convert" { + function base_convert(number?:any, frombase?:any, tobase?:any):any; + export = base_convert; +} +declare module "locutus/php/math/bindec" { + function bindec(binaryString?:any):any; + export = bindec; +} +declare module "locutus/php/math/ceil" { + function ceil(value?:any):any; + export = ceil; +} +declare module "locutus/php/math/cos" { + function cos(arg?:any):any; + export = cos; +} +declare module "locutus/php/math/cosh" { + function cosh(arg?:any):any; + export = cosh; +} +declare module "locutus/php/math/decbin" { + function decbin(number?:any):any; + export = decbin; +} +declare module "locutus/php/math/dechex" { + function dechex(number?:any):any; + export = dechex; +} +declare module "locutus/php/math/decoct" { + function decoct(number?:any):any; + export = decoct; +} +declare module "locutus/php/math/deg2rad" { + function deg2rad(angle?:any):any; + export = deg2rad; +} +declare module "locutus/php/math/exp" { + function exp(arg?:any):any; + export = exp; +} +declare module "locutus/php/math/expm1" { + function expm1(x?:any):any; + export = expm1; +} +declare module "locutus/php/math/floor" { + function floor(value?:any):any; + export = floor; +} +declare module "locutus/php/math/fmod" { + function fmod(x?:any, y?:any):any; + export = fmod; +} +declare module "locutus/php/math/getrandmax" { + function getrandmax():any; + export = getrandmax; +} +declare module "locutus/php/math/hexdec" { + function hexdec(hexString?:any):any; + export = hexdec; +} +declare module "locutus/php/math/hypot" { + function hypot(x?:any, y?:any):any; + export = hypot; +} +declare module "locutus/php/math/is_finite" { + function is_finite(val?:any):any; + export = is_finite; +} +declare module "locutus/php/math/is_infinite" { + function is_infinite(val?:any):any; + export = is_infinite; +} +declare module "locutus/php/math/is_nan" { + function is_nan(val?:any):any; + export = is_nan; +} +declare module "locutus/php/math/lcg_value" { + function lcg_value():any; + export = lcg_value; +} +declare module "locutus/php/math/log" { + function log(arg?:any, base?:any):any; + export = log; +} +declare module "locutus/php/math/log10" { + function log10(arg?:any):any; + export = log10; +} +declare module "locutus/php/math/log1p" { + function log1p(x?:any):any; + export = log1p; +} +declare module "locutus/php/math/max" { + function max(...args:any[]):any; + export = max; +} +declare module "locutus/php/math/min" { + function min(...args:any[]):any; + export = min; +} +declare module "locutus/php/math/mt_getrandmax" { + function mt_getrandmax():any; + export = mt_getrandmax; +} +declare module "locutus/php/math/mt_rand" { + function mt_rand(...args:any[]):any; + export = mt_rand; +} +declare module "locutus/php/math/octdec" { + function octdec(octString?:any):any; + export = octdec; +} +declare module "locutus/php/math/pi" { + function pi():any; + export = pi; +} +declare module "locutus/php/math/pow" { + function pow(base?:any, exp?:any):any; + export = pow; +} +declare module "locutus/php/math/rad2deg" { + function rad2deg(angle?:any):any; + export = rad2deg; +} +declare module "locutus/php/math/rand" { + function rand(...args:any[]):any; + export = rand; +} +declare module "locutus/php/math/round" { + function round(...args:any[]):any; + export = round; +} +declare module "locutus/php/math/sin" { + function sin(arg?:any):any; + export = sin; +} +declare module "locutus/php/math/sinh" { + function sinh(arg?:any):any; + export = sinh; +} +declare module "locutus/php/math/sqrt" { + function sqrt(arg?:any):any; + export = sqrt; +} +declare module "locutus/php/math/tan" { + function tan(arg?:any):any; + export = tan; +} +declare module "locutus/php/math/tanh" { + function tanh(arg?:any):any; + export = tanh; +} +declare module "locutus/php/misc/pack" { + function pack(...args:any[]):any; + export = pack; +} +declare module "locutus/php/misc/uniqid" { + function uniqid(prefix?:any, moreEntropy?:any):any; + export = uniqid; +} +declare module "locutus/php/net-gopher/gopher_parsedir" { + function gopher_parsedir(dirent?:any):any; + export = gopher_parsedir; +} +declare module "locutus/php/network/inet_ntop" { + function inet_ntop(a?:any):any; + export = inet_ntop; +} +declare module "locutus/php/network/inet_pton" { + function inet_pton(a?:any):any; + export = inet_pton; +} +declare module "locutus/php/network/ip2long" { + function ip2long(argIP?:any):any; + export = ip2long; +} +declare module "locutus/php/network/long2ip" { + function long2ip(ip?:any):any; + export = long2ip; +} +declare module "locutus/php/network/setcookie" { + function setcookie(name?:any, value?:any, expires?:any, path?:any, domain?:any, secure?:any):any; + export = setcookie; +} +declare module "locutus/php/network/setrawcookie" { + function setrawcookie(name?:any, value?:any, expires?:any, path?:any, domain?:any, secure?:any):any; + export = setrawcookie; +} +declare module "locutus/php/pcre/preg_quote" { + function preg_quote(str?:any, delimiter?:any):any; + export = preg_quote; +} +declare module "locutus/php/pcre/sql_regcase" { + function sql_regcase(str?:any):any; + export = sql_regcase; +} +declare module "locutus/php/strings/addcslashes" { + function addcslashes(str?:any, charlist?:any):any; + export = addcslashes; +} +declare module "locutus/php/strings/addslashes" { + function addslashes(str?:any):any; + export = addslashes; +} +declare module "locutus/php/strings/bin2hex" { + function bin2hex(s?:any):any; + export = bin2hex; +} +declare module "locutus/php/strings/chop" { + function chop(str?:any, charlist?:any):any; + export = chop; +} +declare module "locutus/php/strings/chr" { + function chr(codePt?:any):any; + export = chr; +} +declare module "locutus/php/strings/chunk_split" { + function chunk_split(body?:any, chunklen?:any, end?:any):any; + export = chunk_split; +} +declare module "locutus/php/strings/convert_cyr_string" { + function convert_cyr_string(str?:any, from?:any, to?:any):any; + export = convert_cyr_string; +} +declare module "locutus/php/strings/convert_uuencode" { + function convert_uuencode(str?:any):any; + export = convert_uuencode; +} +declare module "locutus/php/strings/count_chars" { + function count_chars(str?:any, mode?:any):any; + export = count_chars; +} +declare module "locutus/php/strings/crc32" { + function crc32(str?:any):any; + export = crc32; +} +declare module "locutus/php/strings/echo" { + function echo(...args:any[]):any; + export = echo; +} +declare module "locutus/php/strings/explode" { + function explode(...args:any[]):any; + export = explode; +} +declare module "locutus/php/strings/get_html_translation_table" { + function get_html_translation_table(...args:any[]):any; + export = get_html_translation_table; +} +declare module "locutus/php/strings/hex2bin" { + function hex2bin(s?:any):any; + export = hex2bin; +} +declare module "locutus/php/strings/html_entity_decode" { + function html_entity_decode(string?:any, quoteStyle?:any):any; + export = html_entity_decode; +} +declare module "locutus/php/strings/htmlentities" { + function htmlentities(string?:any, quoteStyle?:any, charset?:any, doubleEncode?:any):any; + export = htmlentities; +} +declare module "locutus/php/strings/htmlspecialchars" { + function htmlspecialchars(string?:any, quoteStyle?:any, charset?:any, doubleEncode?:any):any; + export = htmlspecialchars; +} +declare module "locutus/php/strings/htmlspecialchars_decode" { + function htmlspecialchars_decode(string?:any, quoteStyle?:any):any; + export = htmlspecialchars_decode; +} +declare module "locutus/php/strings/implode" { + function implode(...args:any[]):any; + export = implode; +} +declare module "locutus/php/strings/join" { + function join(glue?:any, pieces?:any):any; + export = join; +} +declare module "locutus/php/strings/lcfirst" { + function lcfirst(str?:any):any; + export = lcfirst; +} +declare module "locutus/php/strings/levenshtein" { + function levenshtein(s1?:any, s2?:any, costIns?:any, costRep?:any, costDel?:any):any; + export = levenshtein; +} +declare module "locutus/php/strings/localeconv" { + function localeconv():any; + export = localeconv; +} +declare module "locutus/php/strings/ltrim" { + function ltrim(str?:any, charlist?:any):any; + export = ltrim; +} +declare module "locutus/php/strings/md5" { + function md5(str?:any):any; + export = md5; +} +declare module "locutus/php/strings/md5_file" { + function md5_file(str_filename?:any):any; + export = md5_file; +} +declare module "locutus/php/strings/metaphone" { + function metaphone(word?:any, maxPhonemes?:any):any; + export = metaphone; +} +declare module "locutus/php/strings/money_format" { + function money_format(format?:any, number?:any):any; + export = money_format; +} +declare module "locutus/php/strings/nl2br" { + function nl2br(str?:any, isXhtml?:any):any; + export = nl2br; +} +declare module "locutus/php/strings/nl_langinfo" { + function nl_langinfo(item?:any):any; + export = nl_langinfo; +} +declare module "locutus/php/strings/number_format" { + function number_format(number?:any, decimals?:any, decPoint?:any, thousandsSep?:any):any; + export = number_format; +} +declare module "locutus/php/strings/ord" { + function ord(string?:any):any; + export = ord; +} +declare module "locutus/php/strings/parse_str" { + function parse_str(str?:any, array?:any):any; + export = parse_str; +} +declare module "locutus/php/strings/printf" { + function printf(...args:any[]):any; + export = printf; +} +declare module "locutus/php/strings/quoted_printable_decode" { + function quoted_printable_decode(str?:any):any; + export = quoted_printable_decode; +} +declare module "locutus/php/strings/quoted_printable_encode" { + function quoted_printable_encode(str?:any):any; + export = quoted_printable_encode; +} +declare module "locutus/php/strings/quotemeta" { + function quotemeta(str?:any):any; + export = quotemeta; +} +declare module "locutus/php/strings/rtrim" { + function rtrim(str?:any, charlist?:any):any; + export = rtrim; +} +declare module "locutus/php/strings/setlocale" { + function setlocale(category?:any, locale?:any):any; + export = setlocale; +} +declare module "locutus/php/strings/sha1" { + function sha1(str?:any):any; + export = sha1; +} +declare module "locutus/php/strings/sha1_file" { + function sha1_file(str_filename?:any):any; + export = sha1_file; +} +declare module "locutus/php/strings/similar_text" { + function similar_text(first?:any, second?:any, percent?:any):any; + export = similar_text; +} +declare module "locutus/php/strings/soundex" { + function soundex(str?:any):any; + export = soundex; +} +declare module "locutus/php/strings/split" { + function split(delimiter?:any, string?:any):any; + export = split; +} +declare module "locutus/php/strings/sprintf" { + function sprintf(...args:any[]):any; + export = sprintf; +} +declare module "locutus/php/strings/sscanf" { + function sscanf(...args:any[]):any; + export = sscanf; +} +declare module "locutus/php/strings/str_getcsv" { + function str_getcsv(input?:any, delimiter?:any, enclosure?:any, escape?:any):any; + export = str_getcsv; +} +declare module "locutus/php/strings/str_ireplace" { + function str_ireplace(search?:any, replace?:any, subject?:any, countObj?:any):any; + export = str_ireplace; +} +declare module "locutus/php/strings/str_pad" { + function str_pad(input?:any, padLength?:any, padString?:any, padType?:any):any; + export = str_pad; +} +declare module "locutus/php/strings/str_repeat" { + function str_repeat(input?:any, multiplier?:any):any; + export = str_repeat; +} +declare module "locutus/php/strings/str_replace" { + function str_replace(search?:any, replace?:any, subject?:any, countObj?:any):any; + export = str_replace; +} +declare module "locutus/php/strings/str_rot13" { + function str_rot13(str?:any):any; + export = str_rot13; +} +declare module "locutus/php/strings/str_shuffle" { + function str_shuffle(...args:any[]):any; + export = str_shuffle; +} +declare module "locutus/php/strings/str_split" { + function str_split(string?:any, splitLength?:any):any; + export = str_split; +} +declare module "locutus/php/strings/str_word_count" { + function str_word_count(str?:any, format?:any, charlist?:any):any; + export = str_word_count; +} +declare module "locutus/php/strings/strcasecmp" { + function strcasecmp(fString1?:any, fString2?:any):any; + export = strcasecmp; +} +declare module "locutus/php/strings/strchr" { + function strchr(haystack?:any, needle?:any, bool?:any):any; + export = strchr; +} +declare module "locutus/php/strings/strcmp" { + function strcmp(str1?:any, str2?:any):any; + export = strcmp; +} +declare module "locutus/php/strings/strcoll" { + function strcoll(str1?:any, str2?:any):any; + export = strcoll; +} +declare module "locutus/php/strings/strcspn" { + function strcspn(str?:any, mask?:any, start?:any, length?:any):any; + export = strcspn; +} +declare module "locutus/php/strings/strip_tags" { + function strip_tags(input?:any, allowed?:any):any; + export = strip_tags; +} +declare module "locutus/php/strings/stripos" { + function stripos(fHaystack?:any, fNeedle?:any, fOffset?:any):any; + export = stripos; +} +declare module "locutus/php/strings/stripslashes" { + function stripslashes(str?:any):any; + export = stripslashes; +} +declare module "locutus/php/strings/stristr" { + function stristr(haystack?:any, needle?:any, bool?:any):any; + export = stristr; +} +declare module "locutus/php/strings/strlen" { + function strlen(string?:any):any; + export = strlen; +} +declare module "locutus/php/strings/strnatcasecmp" { + function strnatcasecmp(str1?:any, str2?:any):any; + export = strnatcasecmp; +} +declare module "locutus/php/strings/strnatcmp" { + function strnatcmp(fString1?:any, fString2?:any, fVersion?:any):any; + export = strnatcmp; +} +declare module "locutus/php/strings/strncasecmp" { + function strncasecmp(argStr1?:any, argStr2?:any, len?:any):any; + export = strncasecmp; +} +declare module "locutus/php/strings/strncmp" { + function strncmp(str1?:any, str2?:any, lgth?:any):any; + export = strncmp; +} +declare module "locutus/php/strings/strpbrk" { + function strpbrk(haystack?:any, charList?:any):any; + export = strpbrk; +} +declare module "locutus/php/strings/strpos" { + function strpos(haystack?:any, needle?:any, offset?:any):any; + export = strpos; +} +declare module "locutus/php/strings/strrchr" { + function strrchr(haystack?:any, needle?:any):any; + export = strrchr; +} +declare module "locutus/php/strings/strrev" { + function strrev(string?:any):any; + export = strrev; +} +declare module "locutus/php/strings/strripos" { + function strripos(haystack?:any, needle?:any, offset?:any):any; + export = strripos; +} +declare module "locutus/php/strings/strrpos" { + function strrpos(haystack?:any, needle?:any, offset?:any):any; + export = strrpos; +} +declare module "locutus/php/strings/strspn" { + function strspn(str1?:any, str2?:any, start?:any, lgth?:any):any; + export = strspn; +} +declare module "locutus/php/strings/strstr" { + function strstr(haystack?:any, needle?:any, bool?:any):any; + export = strstr; +} +declare module "locutus/php/strings/strtok" { + function strtok(str?:any, tokens?:any):any; + export = strtok; +} +declare module "locutus/php/strings/strtolower" { + function strtolower(str?:any):any; + export = strtolower; +} +declare module "locutus/php/strings/strtoupper" { + function strtoupper(str?:any):any; + export = strtoupper; +} +declare module "locutus/php/strings/strtr" { + function strtr(str?:any, trFrom?:any, trTo?:any):any; + export = strtr; +} +declare module "locutus/php/strings/substr" { + function substr(str?:any, start?:any, len?:any):any; + export = substr; +} +declare module "locutus/php/strings/substr_compare" { + function substr_compare(mainStr?:any, str?:any, offset?:any, length?:any, caseInsensitivity?:any):any; + export = substr_compare; +} +declare module "locutus/php/strings/substr_count" { + function substr_count(haystack?:any, needle?:any, offset?:any, length?:any):any; + export = substr_count; +} +declare module "locutus/php/strings/substr_replace" { + function substr_replace(str?:any, replace?:any, start?:any, length?:any):any; + export = substr_replace; +} +declare module "locutus/php/strings/trim" { + function trim(str?:any, charlist?:any):any; + export = trim; +} +declare module "locutus/php/strings/ucfirst" { + function ucfirst(str?:any):any; + export = ucfirst; +} +declare module "locutus/php/strings/ucwords" { + function ucwords(str?:any):any; + export = ucwords; +} +declare module "locutus/php/strings/vprintf" { + function vprintf(format?:any, args?:any):any; + export = vprintf; +} +declare module "locutus/php/strings/vsprintf" { + function vsprintf(format?:any, args?:any):any; + export = vsprintf; +} +declare module "locutus/php/strings/wordwrap" { + function wordwrap(...args:any[]):any; + export = wordwrap; +} +declare module "locutus/php/url/base64_decode" { + function base64_decode(encodedData?:any):any; + export = base64_decode; +} +declare module "locutus/php/url/base64_encode" { + function base64_encode(stringToEncode?:any):any; + export = base64_encode; +} +declare module "locutus/php/url/http_build_query" { + function http_build_query(formdata?:any, numericPrefix?:any, argSeparator?:any):any; + export = http_build_query; +} +declare module "locutus/php/url/parse_url" { + function parse_url(str?:any, component?:any):any; + export = parse_url; +} +declare module "locutus/php/url/rawurldecode" { + function rawurldecode(str?:any):any; + export = rawurldecode; +} +declare module "locutus/php/url/rawurlencode" { + function rawurlencode(str?:any):any; + export = rawurlencode; +} +declare module "locutus/php/url/urldecode" { + function urldecode(str?:any):any; + export = urldecode; +} +declare module "locutus/php/url/urlencode" { + function urlencode(str?:any):any; + export = urlencode; +} +declare module "locutus/php/var/doubleval" { + function doubleval(mixedVar?:any):any; + export = doubleval; +} +declare module "locutus/php/var/empty" { + function empty(mixedVar?:any):any; + export = empty; +} +declare module "locutus/php/var/floatval" { + function floatval(mixedVar?:any):any; + export = floatval; +} +declare module "locutus/php/var/gettype" { + function gettype(mixedVar?:any):any; + export = gettype; +} +declare module "locutus/php/var/intval" { + function intval(mixedVar?:any, base?:any):any; + export = intval; +} +declare module "locutus/php/var/is_array" { + function is_array(mixedVar?:any):any; + export = is_array; +} +declare module "locutus/php/var/is_binary" { + function is_binary(vr?:any):any; + export = is_binary; +} +declare module "locutus/php/var/is_bool" { + function is_bool(mixedVar?:any):any; + export = is_bool; +} +declare module "locutus/php/var/is_buffer" { + function is_buffer(vr?:any):any; + export = is_buffer; +} +declare module "locutus/php/var/is_callable" { + function is_callable(mixedVar?:any, syntaxOnly?:any, callableName?:any):any; + export = is_callable; +} +declare module "locutus/php/var/is_double" { + function is_double(mixedVar?:any):any; + export = is_double; +} +declare module "locutus/php/var/is_float" { + function is_float(mixedVar?:any):any; + export = is_float; +} +declare module "locutus/php/var/is_int" { + function is_int(mixedVar?:any):any; + export = is_int; +} +declare module "locutus/php/var/is_integer" { + function is_integer(mixedVar?:any):any; + export = is_integer; +} +declare module "locutus/php/var/is_long" { + function is_long(mixedVar?:any):any; + export = is_long; +} +declare module "locutus/php/var/is_null" { + function is_null(mixedVar?:any):any; + export = is_null; +} +declare module "locutus/php/var/is_numeric" { + function is_numeric(mixedVar?:any):any; + export = is_numeric; +} +declare module "locutus/php/var/is_object" { + function is_object(mixedVar?:any):any; + export = is_object; +} +declare module "locutus/php/var/is_real" { + function is_real(mixedVar?:any):any; + export = is_real; +} +declare module "locutus/php/var/is_scalar" { + function is_scalar(mixedVar?:any):any; + export = is_scalar; +} +declare module "locutus/php/var/is_string" { + function is_string(mixedVar?:any):any; + export = is_string; +} +declare module "locutus/php/var/is_unicode" { + function is_unicode(vr?:any):any; + export = is_unicode; +} +declare module "locutus/php/var/isset" { + function isset(...args:any[]):any; + export = isset; +} +declare module "locutus/php/var/print_r" { + function print_r(array?:any, returnVal?:any):any; + export = print_r; +} +declare module "locutus/php/var/serialize" { + function serialize(mixedValue?:any):any; + export = serialize; +} +declare module "locutus/php/var/strval" { + function strval(str?:any):any; + export = strval; +} +declare module "locutus/php/var/unserialize" { + function unserialize(data?:any):any; + export = unserialize; +} +declare module "locutus/php/var/var_dump" { + function var_dump(...args:any[]):any; + export = var_dump; +} +declare module "locutus/php/var/var_export" { + function var_export(...args:any[]):any; + export = var_export; +} +declare module "locutus/php/xdiff/xdiff_string_diff" { + function xdiff_string_diff(...args:any[]):any; + export = xdiff_string_diff; +} +declare module "locutus/php/xdiff/xdiff_string_patch" { + function xdiff_string_patch(...args:any[]):any; + export = xdiff_string_patch; +} +declare module "locutus/php/xml/utf8_decode" { + function utf8_decode(strData?:any):any; + export = utf8_decode; +} +declare module "locutus/php/xml/utf8_encode" { + function utf8_encode(argString?:any):any; + export = utf8_encode; +} +declare module "locutus/python/string/capwords" { + function capwords(str?:any):any; + export = capwords; +} +declare module "locutus/ruby/Math/acos" { + function acos(arg?:any):any; + export = acos; +} +declare module "locutus/c/math" { + import abs = require("locutus/c/math/abs"); + export {abs}; +} +declare module "locutus/golang/strings" { + import Contains = require("locutus/golang/strings/Contains"); + import Count = require("locutus/golang/strings/Count"); + import Index = require("locutus/golang/strings/Index"); + import LastIndex = require("locutus/golang/strings/LastIndex"); + export {Contains,Count,Index,LastIndex}; +} +declare module "locutus/php/array" { + import array_change_key_case = require("locutus/php/array/array_change_key_case"); + import array_chunk = require("locutus/php/array/array_chunk"); + import array_combine = require("locutus/php/array/array_combine"); + import array_count_values = require("locutus/php/array/array_count_values"); + import array_diff = require("locutus/php/array/array_diff"); + import array_diff_assoc = require("locutus/php/array/array_diff_assoc"); + import array_diff_key = require("locutus/php/array/array_diff_key"); + import array_diff_uassoc = require("locutus/php/array/array_diff_uassoc"); + import array_diff_ukey = require("locutus/php/array/array_diff_ukey"); + import array_fill = require("locutus/php/array/array_fill"); + import array_fill_keys = require("locutus/php/array/array_fill_keys"); + import array_filter = require("locutus/php/array/array_filter"); + import array_flip = require("locutus/php/array/array_flip"); + import array_intersect = require("locutus/php/array/array_intersect"); + import array_intersect_assoc = require("locutus/php/array/array_intersect_assoc"); + import array_intersect_key = require("locutus/php/array/array_intersect_key"); + import array_intersect_uassoc = require("locutus/php/array/array_intersect_uassoc"); + import array_intersect_ukey = require("locutus/php/array/array_intersect_ukey"); + import array_key_exists = require("locutus/php/array/array_key_exists"); + import array_keys = require("locutus/php/array/array_keys"); + import array_map = require("locutus/php/array/array_map"); + import array_merge = require("locutus/php/array/array_merge"); + import array_merge_recursive = require("locutus/php/array/array_merge_recursive"); + import array_multisort = require("locutus/php/array/array_multisort"); + import array_pad = require("locutus/php/array/array_pad"); + import array_pop = require("locutus/php/array/array_pop"); + import array_product = require("locutus/php/array/array_product"); + import array_push = require("locutus/php/array/array_push"); + import array_rand = require("locutus/php/array/array_rand"); + import array_reduce = require("locutus/php/array/array_reduce"); + import array_replace = require("locutus/php/array/array_replace"); + import array_replace_recursive = require("locutus/php/array/array_replace_recursive"); + import array_reverse = require("locutus/php/array/array_reverse"); + import array_search = require("locutus/php/array/array_search"); + import array_shift = require("locutus/php/array/array_shift"); + import array_slice = require("locutus/php/array/array_slice"); + import array_splice = require("locutus/php/array/array_splice"); + import array_sum = require("locutus/php/array/array_sum"); + import array_udiff = require("locutus/php/array/array_udiff"); + import array_udiff_assoc = require("locutus/php/array/array_udiff_assoc"); + import array_udiff_uassoc = require("locutus/php/array/array_udiff_uassoc"); + import array_uintersect = require("locutus/php/array/array_uintersect"); + import array_uintersect_uassoc = require("locutus/php/array/array_uintersect_uassoc"); + import array_unique = require("locutus/php/array/array_unique"); + import array_unshift = require("locutus/php/array/array_unshift"); + import array_values = require("locutus/php/array/array_values"); + import array_walk = require("locutus/php/array/array_walk"); + import arsort = require("locutus/php/array/arsort"); + import asort = require("locutus/php/array/asort"); + import count = require("locutus/php/array/count"); + import current = require("locutus/php/array/current"); + import each = require("locutus/php/array/each"); + import end = require("locutus/php/array/end"); + import in_array = require("locutus/php/array/in_array"); + import key = require("locutus/php/array/key"); + import krsort = require("locutus/php/array/krsort"); + import ksort = require("locutus/php/array/ksort"); + import natcasesort = require("locutus/php/array/natcasesort"); + import natsort = require("locutus/php/array/natsort"); + import next = require("locutus/php/array/next"); + import pos = require("locutus/php/array/pos"); + import prev = require("locutus/php/array/prev"); + import range = require("locutus/php/array/range"); + import reset = require("locutus/php/array/reset"); + import rsort = require("locutus/php/array/rsort"); + import shuffle = require("locutus/php/array/shuffle"); + import sizeof = require("locutus/php/array/sizeof"); + import sort = require("locutus/php/array/sort"); + import uasort = require("locutus/php/array/uasort"); + import uksort = require("locutus/php/array/uksort"); + import usort = require("locutus/php/array/usort"); + export {array_change_key_case,array_chunk,array_combine,array_count_values,array_diff,array_diff_assoc,array_diff_key,array_diff_uassoc,array_diff_ukey,array_fill,array_fill_keys,array_filter,array_flip,array_intersect,array_intersect_assoc,array_intersect_key,array_intersect_uassoc,array_intersect_ukey,array_key_exists,array_keys,array_map,array_merge,array_merge_recursive,array_multisort,array_pad,array_pop,array_product,array_push,array_rand,array_reduce,array_replace,array_replace_recursive,array_reverse,array_search,array_shift,array_slice,array_splice,array_sum,array_udiff,array_udiff_assoc,array_udiff_uassoc,array_uintersect,array_uintersect_uassoc,array_unique,array_unshift,array_values,array_walk,arsort,asort,count,current,each,end,in_array,key,krsort,ksort,natcasesort,natsort,next,pos,prev,range,reset,rsort,shuffle,sizeof,sort,uasort,uksort,usort}; +} +declare module "locutus/php/bc" { + import bcadd = require("locutus/php/bc/bcadd"); + import bccomp = require("locutus/php/bc/bccomp"); + import bcdiv = require("locutus/php/bc/bcdiv"); + import bcmul = require("locutus/php/bc/bcmul"); + import bcround = require("locutus/php/bc/bcround"); + import bcscale = require("locutus/php/bc/bcscale"); + import bcsub = require("locutus/php/bc/bcsub"); + export {bcadd,bccomp,bcdiv,bcmul,bcround,bcscale,bcsub}; +} +declare module "locutus/php/ctype" { + import ctype_alnum = require("locutus/php/ctype/ctype_alnum"); + import ctype_alpha = require("locutus/php/ctype/ctype_alpha"); + import ctype_cntrl = require("locutus/php/ctype/ctype_cntrl"); + import ctype_digit = require("locutus/php/ctype/ctype_digit"); + import ctype_graph = require("locutus/php/ctype/ctype_graph"); + import ctype_lower = require("locutus/php/ctype/ctype_lower"); + import ctype_print = require("locutus/php/ctype/ctype_print"); + import ctype_punct = require("locutus/php/ctype/ctype_punct"); + import ctype_space = require("locutus/php/ctype/ctype_space"); + import ctype_upper = require("locutus/php/ctype/ctype_upper"); + import ctype_xdigit = require("locutus/php/ctype/ctype_xdigit"); + export {ctype_alnum,ctype_alpha,ctype_cntrl,ctype_digit,ctype_graph,ctype_lower,ctype_print,ctype_punct,ctype_space,ctype_upper,ctype_xdigit}; +} +declare module "locutus/php/datetime" { + import checkdate = require("locutus/php/datetime/checkdate"); + import date = require("locutus/php/datetime/date"); + import date_parse = require("locutus/php/datetime/date_parse"); + import getdate = require("locutus/php/datetime/getdate"); + import gettimeofday = require("locutus/php/datetime/gettimeofday"); + import gmdate = require("locutus/php/datetime/gmdate"); + import gmmktime = require("locutus/php/datetime/gmmktime"); + import gmstrftime = require("locutus/php/datetime/gmstrftime"); + import idate = require("locutus/php/datetime/idate"); + import microtime = require("locutus/php/datetime/microtime"); + import mktime = require("locutus/php/datetime/mktime"); + import strftime = require("locutus/php/datetime/strftime"); + import strptime = require("locutus/php/datetime/strptime"); + import strtotime = require("locutus/php/datetime/strtotime"); + import time = require("locutus/php/datetime/time"); + export {checkdate,date,date_parse,getdate,gettimeofday,gmdate,gmmktime,gmstrftime,idate,microtime,mktime,strftime,strptime,strtotime,time}; +} +declare module "locutus/php/exec" { + import escapeshellarg = require("locutus/php/exec/escapeshellarg"); + export {escapeshellarg}; +} +declare module "locutus/php/filesystem" { + import basename = require("locutus/php/filesystem/basename"); + import dirname = require("locutus/php/filesystem/dirname"); + import file_get_contents = require("locutus/php/filesystem/file_get_contents"); + import pathinfo = require("locutus/php/filesystem/pathinfo"); + import realpath = require("locutus/php/filesystem/realpath"); + export {basename,dirname,file_get_contents,pathinfo,realpath}; +} +declare module "locutus/php/funchand" { + import call_user_func = require("locutus/php/funchand/call_user_func"); + import call_user_func_array = require("locutus/php/funchand/call_user_func_array"); + import create_function = require("locutus/php/funchand/create_function"); + import function_exists = require("locutus/php/funchand/function_exists"); + import get_defined_functions = require("locutus/php/funchand/get_defined_functions"); + export {call_user_func,call_user_func_array,create_function,function_exists,get_defined_functions}; +} +declare module "locutus/php/i18n" { + import i18n_loc_get_default = require("locutus/php/i18n/i18n_loc_get_default"); + import i18n_loc_set_default = require("locutus/php/i18n/i18n_loc_set_default"); + export {i18n_loc_get_default,i18n_loc_set_default}; +} +declare module "locutus/php/info" { + import assert_options = require("locutus/php/info/assert_options"); + import getenv = require("locutus/php/info/getenv"); + import ini_get = require("locutus/php/info/ini_get"); + import ini_set = require("locutus/php/info/ini_set"); + import set_time_limit = require("locutus/php/info/set_time_limit"); + import version_compare = require("locutus/php/info/version_compare"); + export {assert_options,getenv,ini_get,ini_set,set_time_limit,version_compare}; +} +declare module "locutus/php/json" { + import json_decode = require("locutus/php/json/json_decode"); + import json_encode = require("locutus/php/json/json_encode"); + import json_last_error = require("locutus/php/json/json_last_error"); + export {json_decode,json_encode,json_last_error}; +} +declare module "locutus/php/math" { + import abs = require("locutus/php/math/abs"); + import acos = require("locutus/php/math/acos"); + import acosh = require("locutus/php/math/acosh"); + import asin = require("locutus/php/math/asin"); + import asinh = require("locutus/php/math/asinh"); + import atan = require("locutus/php/math/atan"); + import atan2 = require("locutus/php/math/atan2"); + import atanh = require("locutus/php/math/atanh"); + import base_convert = require("locutus/php/math/base_convert"); + import bindec = require("locutus/php/math/bindec"); + import ceil = require("locutus/php/math/ceil"); + import cos = require("locutus/php/math/cos"); + import cosh = require("locutus/php/math/cosh"); + import decbin = require("locutus/php/math/decbin"); + import dechex = require("locutus/php/math/dechex"); + import decoct = require("locutus/php/math/decoct"); + import deg2rad = require("locutus/php/math/deg2rad"); + import exp = require("locutus/php/math/exp"); + import expm1 = require("locutus/php/math/expm1"); + import floor = require("locutus/php/math/floor"); + import fmod = require("locutus/php/math/fmod"); + import getrandmax = require("locutus/php/math/getrandmax"); + import hexdec = require("locutus/php/math/hexdec"); + import hypot = require("locutus/php/math/hypot"); + import is_finite = require("locutus/php/math/is_finite"); + import is_infinite = require("locutus/php/math/is_infinite"); + import is_nan = require("locutus/php/math/is_nan"); + import lcg_value = require("locutus/php/math/lcg_value"); + import log = require("locutus/php/math/log"); + import log10 = require("locutus/php/math/log10"); + import log1p = require("locutus/php/math/log1p"); + import max = require("locutus/php/math/max"); + import min = require("locutus/php/math/min"); + import mt_getrandmax = require("locutus/php/math/mt_getrandmax"); + import mt_rand = require("locutus/php/math/mt_rand"); + import octdec = require("locutus/php/math/octdec"); + import pi = require("locutus/php/math/pi"); + import pow = require("locutus/php/math/pow"); + import rad2deg = require("locutus/php/math/rad2deg"); + import rand = require("locutus/php/math/rand"); + import round = require("locutus/php/math/round"); + import sin = require("locutus/php/math/sin"); + import sinh = require("locutus/php/math/sinh"); + import sqrt = require("locutus/php/math/sqrt"); + import tan = require("locutus/php/math/tan"); + import tanh = require("locutus/php/math/tanh"); + export {abs,acos,acosh,asin,asinh,atan,atan2,atanh,base_convert,bindec,ceil,cos,cosh,decbin,dechex,decoct,deg2rad,exp,expm1,floor,fmod,getrandmax,hexdec,hypot,is_finite,is_infinite,is_nan,lcg_value,log,log10,log1p,max,min,mt_getrandmax,mt_rand,octdec,pi,pow,rad2deg,rand,round,sin,sinh,sqrt,tan,tanh}; +} +declare module "locutus/php/misc" { + import pack = require("locutus/php/misc/pack"); + import uniqid = require("locutus/php/misc/uniqid"); + export {pack,uniqid}; +} +declare module "locutus/php/net-gopher" { + import gopher_parsedir = require("locutus/php/net-gopher/gopher_parsedir"); + export {gopher_parsedir}; +} +declare module "locutus/php/network" { + import inet_ntop = require("locutus/php/network/inet_ntop"); + import inet_pton = require("locutus/php/network/inet_pton"); + import ip2long = require("locutus/php/network/ip2long"); + import long2ip = require("locutus/php/network/long2ip"); + import setcookie = require("locutus/php/network/setcookie"); + import setrawcookie = require("locutus/php/network/setrawcookie"); + export {inet_ntop,inet_pton,ip2long,long2ip,setcookie,setrawcookie}; +} +declare module "locutus/php/pcre" { + import preg_quote = require("locutus/php/pcre/preg_quote"); + import sql_regcase = require("locutus/php/pcre/sql_regcase"); + export {preg_quote,sql_regcase}; +} +declare module "locutus/php/strings" { + import addcslashes = require("locutus/php/strings/addcslashes"); + import addslashes = require("locutus/php/strings/addslashes"); + import bin2hex = require("locutus/php/strings/bin2hex"); + import chop = require("locutus/php/strings/chop"); + import chr = require("locutus/php/strings/chr"); + import chunk_split = require("locutus/php/strings/chunk_split"); + import convert_cyr_string = require("locutus/php/strings/convert_cyr_string"); + import convert_uuencode = require("locutus/php/strings/convert_uuencode"); + import count_chars = require("locutus/php/strings/count_chars"); + import crc32 = require("locutus/php/strings/crc32"); + import echo = require("locutus/php/strings/echo"); + import explode = require("locutus/php/strings/explode"); + import get_html_translation_table = require("locutus/php/strings/get_html_translation_table"); + import hex2bin = require("locutus/php/strings/hex2bin"); + import html_entity_decode = require("locutus/php/strings/html_entity_decode"); + import htmlentities = require("locutus/php/strings/htmlentities"); + import htmlspecialchars = require("locutus/php/strings/htmlspecialchars"); + import htmlspecialchars_decode = require("locutus/php/strings/htmlspecialchars_decode"); + import implode = require("locutus/php/strings/implode"); + import join = require("locutus/php/strings/join"); + import lcfirst = require("locutus/php/strings/lcfirst"); + import levenshtein = require("locutus/php/strings/levenshtein"); + import localeconv = require("locutus/php/strings/localeconv"); + import ltrim = require("locutus/php/strings/ltrim"); + import md5 = require("locutus/php/strings/md5"); + import md5_file = require("locutus/php/strings/md5_file"); + import metaphone = require("locutus/php/strings/metaphone"); + import money_format = require("locutus/php/strings/money_format"); + import nl2br = require("locutus/php/strings/nl2br"); + import nl_langinfo = require("locutus/php/strings/nl_langinfo"); + import number_format = require("locutus/php/strings/number_format"); + import ord = require("locutus/php/strings/ord"); + import parse_str = require("locutus/php/strings/parse_str"); + import printf = require("locutus/php/strings/printf"); + import quoted_printable_decode = require("locutus/php/strings/quoted_printable_decode"); + import quoted_printable_encode = require("locutus/php/strings/quoted_printable_encode"); + import quotemeta = require("locutus/php/strings/quotemeta"); + import rtrim = require("locutus/php/strings/rtrim"); + import setlocale = require("locutus/php/strings/setlocale"); + import sha1 = require("locutus/php/strings/sha1"); + import sha1_file = require("locutus/php/strings/sha1_file"); + import similar_text = require("locutus/php/strings/similar_text"); + import soundex = require("locutus/php/strings/soundex"); + import split = require("locutus/php/strings/split"); + import sprintf = require("locutus/php/strings/sprintf"); + import sscanf = require("locutus/php/strings/sscanf"); + import str_getcsv = require("locutus/php/strings/str_getcsv"); + import str_ireplace = require("locutus/php/strings/str_ireplace"); + import str_pad = require("locutus/php/strings/str_pad"); + import str_repeat = require("locutus/php/strings/str_repeat"); + import str_replace = require("locutus/php/strings/str_replace"); + import str_rot13 = require("locutus/php/strings/str_rot13"); + import str_shuffle = require("locutus/php/strings/str_shuffle"); + import str_split = require("locutus/php/strings/str_split"); + import str_word_count = require("locutus/php/strings/str_word_count"); + import strcasecmp = require("locutus/php/strings/strcasecmp"); + import strchr = require("locutus/php/strings/strchr"); + import strcmp = require("locutus/php/strings/strcmp"); + import strcoll = require("locutus/php/strings/strcoll"); + import strcspn = require("locutus/php/strings/strcspn"); + import strip_tags = require("locutus/php/strings/strip_tags"); + import stripos = require("locutus/php/strings/stripos"); + import stripslashes = require("locutus/php/strings/stripslashes"); + import stristr = require("locutus/php/strings/stristr"); + import strlen = require("locutus/php/strings/strlen"); + import strnatcasecmp = require("locutus/php/strings/strnatcasecmp"); + import strnatcmp = require("locutus/php/strings/strnatcmp"); + import strncasecmp = require("locutus/php/strings/strncasecmp"); + import strncmp = require("locutus/php/strings/strncmp"); + import strpbrk = require("locutus/php/strings/strpbrk"); + import strpos = require("locutus/php/strings/strpos"); + import strrchr = require("locutus/php/strings/strrchr"); + import strrev = require("locutus/php/strings/strrev"); + import strripos = require("locutus/php/strings/strripos"); + import strrpos = require("locutus/php/strings/strrpos"); + import strspn = require("locutus/php/strings/strspn"); + import strstr = require("locutus/php/strings/strstr"); + import strtok = require("locutus/php/strings/strtok"); + import strtolower = require("locutus/php/strings/strtolower"); + import strtoupper = require("locutus/php/strings/strtoupper"); + import strtr = require("locutus/php/strings/strtr"); + import substr = require("locutus/php/strings/substr"); + import substr_compare = require("locutus/php/strings/substr_compare"); + import substr_count = require("locutus/php/strings/substr_count"); + import substr_replace = require("locutus/php/strings/substr_replace"); + import trim = require("locutus/php/strings/trim"); + import ucfirst = require("locutus/php/strings/ucfirst"); + import ucwords = require("locutus/php/strings/ucwords"); + import vprintf = require("locutus/php/strings/vprintf"); + import vsprintf = require("locutus/php/strings/vsprintf"); + import wordwrap = require("locutus/php/strings/wordwrap"); + export {addcslashes,addslashes,bin2hex,chop,chr,chunk_split,convert_cyr_string,convert_uuencode,count_chars,crc32,echo,explode,get_html_translation_table,hex2bin,html_entity_decode,htmlentities,htmlspecialchars,htmlspecialchars_decode,implode,join,lcfirst,levenshtein,localeconv,ltrim,md5,md5_file,metaphone,money_format,nl2br,nl_langinfo,number_format,ord,parse_str,printf,quoted_printable_decode,quoted_printable_encode,quotemeta,rtrim,setlocale,sha1,sha1_file,similar_text,soundex,split,sprintf,sscanf,str_getcsv,str_ireplace,str_pad,str_repeat,str_replace,str_rot13,str_shuffle,str_split,str_word_count,strcasecmp,strchr,strcmp,strcoll,strcspn,strip_tags,stripos,stripslashes,stristr,strlen,strnatcasecmp,strnatcmp,strncasecmp,strncmp,strpbrk,strpos,strrchr,strrev,strripos,strrpos,strspn,strstr,strtok,strtolower,strtoupper,strtr,substr,substr_compare,substr_count,substr_replace,trim,ucfirst,ucwords,vprintf,vsprintf,wordwrap}; +} +declare module "locutus/php/url" { + import base64_decode = require("locutus/php/url/base64_decode"); + import base64_encode = require("locutus/php/url/base64_encode"); + import http_build_query = require("locutus/php/url/http_build_query"); + import parse_url = require("locutus/php/url/parse_url"); + import rawurldecode = require("locutus/php/url/rawurldecode"); + import rawurlencode = require("locutus/php/url/rawurlencode"); + import urldecode = require("locutus/php/url/urldecode"); + import urlencode = require("locutus/php/url/urlencode"); + export {base64_decode,base64_encode,http_build_query,parse_url,rawurldecode,rawurlencode,urldecode,urlencode}; +} +declare module "locutus/php/var" { + import doubleval = require("locutus/php/var/doubleval"); + import empty = require("locutus/php/var/empty"); + import floatval = require("locutus/php/var/floatval"); + import gettype = require("locutus/php/var/gettype"); + import intval = require("locutus/php/var/intval"); + import is_array = require("locutus/php/var/is_array"); + import is_binary = require("locutus/php/var/is_binary"); + import is_bool = require("locutus/php/var/is_bool"); + import is_buffer = require("locutus/php/var/is_buffer"); + import is_callable = require("locutus/php/var/is_callable"); + import is_double = require("locutus/php/var/is_double"); + import is_float = require("locutus/php/var/is_float"); + import is_int = require("locutus/php/var/is_int"); + import is_integer = require("locutus/php/var/is_integer"); + import is_long = require("locutus/php/var/is_long"); + import is_null = require("locutus/php/var/is_null"); + import is_numeric = require("locutus/php/var/is_numeric"); + import is_object = require("locutus/php/var/is_object"); + import is_real = require("locutus/php/var/is_real"); + import is_scalar = require("locutus/php/var/is_scalar"); + import is_string = require("locutus/php/var/is_string"); + import is_unicode = require("locutus/php/var/is_unicode"); + import isset = require("locutus/php/var/isset"); + import print_r = require("locutus/php/var/print_r"); + import serialize = require("locutus/php/var/serialize"); + import strval = require("locutus/php/var/strval"); + import unserialize = require("locutus/php/var/unserialize"); + import var_dump = require("locutus/php/var/var_dump"); + import var_export = require("locutus/php/var/var_export"); + export {doubleval,empty,floatval,gettype,intval,is_array,is_binary,is_bool,is_buffer,is_callable,is_double,is_float,is_int,is_integer,is_long,is_null,is_numeric,is_object,is_real,is_scalar,is_string,is_unicode,isset,print_r,serialize,strval,unserialize,var_dump,var_export}; +} +declare module "locutus/php/xdiff" { + import xdiff_string_diff = require("locutus/php/xdiff/xdiff_string_diff"); + import xdiff_string_patch = require("locutus/php/xdiff/xdiff_string_patch"); + export {xdiff_string_diff,xdiff_string_patch}; +} +declare module "locutus/php/xml" { + import utf8_decode = require("locutus/php/xml/utf8_decode"); + import utf8_encode = require("locutus/php/xml/utf8_encode"); + export {utf8_decode,utf8_encode}; +} +declare module "locutus/python/string" { + import capwords = require("locutus/python/string/capwords"); + export {capwords}; +} +declare module "locutus/ruby/Math" { + import acos = require("locutus/ruby/Math/acos"); + export {acos}; +} +declare module "locutus/c" { + import math = require("locutus/c/math"); + export {math}; +} +declare module "locutus/golang" { + import strings = require("locutus/golang/strings"); + export {strings}; +} +declare module "locutus/php" { + import array = require("locutus/php/array"); + import bc = require("locutus/php/bc"); + import ctype = require("locutus/php/ctype"); + import datetime = require("locutus/php/datetime"); + import exec = require("locutus/php/exec"); + import filesystem = require("locutus/php/filesystem"); + import funchand = require("locutus/php/funchand"); + import i18n = require("locutus/php/i18n"); + import info = require("locutus/php/info"); + import json = require("locutus/php/json"); + import math = require("locutus/php/math"); + import misc = require("locutus/php/misc"); + // import net_gopher = require("locutus/php/net-gopher"); + import network = require("locutus/php/network"); + import pcre = require("locutus/php/pcre"); + import strings = require("locutus/php/strings"); + import url = require("locutus/php/url"); + // import Var = require("locutus/php/var"); + import xdiff = require("locutus/php/xdiff"); + import xml = require("locutus/php/xml"); + export {array,bc,ctype,datetime,exec,filesystem,funchand,i18n,info,json,math,misc,network,pcre,strings,url,xdiff,xml /* ,"net-gopher":net_gopher */ /* ,"var":Var */}; +} +declare module "locutus/python" { + import string = require("locutus/python/string"); + export {string}; +} +declare module "locutus/ruby" { + import Math = require("locutus/ruby/Math"); + export {Math}; +} +declare module "locutus" { + import c = require("locutus/c"); + import golang = require("locutus/golang"); + import php = require("locutus/php"); + import python = require("locutus/python"); + import ruby = require("locutus/ruby"); + export {c,golang,php,python,ruby}; +} diff --git a/locutus/locutus_print.ts b/locutus/locutus_print.ts new file mode 100644 index 0000000000..fc21294639 --- /dev/null +++ b/locutus/locutus_print.ts @@ -0,0 +1,188 @@ +// Automatically generate script for locutus +// Written by: Hookclaw + +/* Usage + tsc locutus_print.ts + node locutus_print.js define + */ + +/// +/// + +var locutus = require('locutus'); + +type f = (...args:any[]) => any; +type e = {[key:string]:f}; +type d = {[key:string]:e}; +type c = {[key:string]:d}; + +let loc:c = locutus; + +let run = ():void => { + if(process.argv.length > 1) { + switch(process.argv[2]) { + case 'define': + define(); + return; + case 'test': + test(); + return; + case 'settings': + settings(); + return; + } + } + console.log('settings,list,define'); +}; + +let define = ():void => { + console.log('// Type definitions for locutus'); + console.log('// Project: http://locutusjs.io'); + console.log('// Definitions by: Hookclaw '); + console.log('// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped'); + console.log(''); + + for(let key1 in loc) { + for(let key2 in loc[key1]) { + for(let key3 in loc[key1][key2]) { + printSingle(loc,key1,key2,key3); + } + } + } + for(let key1 in loc) { + for(let key2 in loc[key1]) { + let modulename = 'locutus/' + key1 + '/' + key2; + printGroup(modulename, loc[key1][key2]); + } + } + for(let key1 in loc) { + let modulename = 'locutus/' + key1; + printGroup(modulename, loc[key1]); + } + let modulename = 'locutus'; + printGroup(modulename, loc); +} + +let printSingle = (loc:c,key1:string,key2:string,key3:string):void => { + console.log('declare module "locutus/' + key1 + '/' + key2 + '/' + key3 + '" {'); + console.log('\tfunction ' + key3 + arg(loc,key1,key2,key3) + ':any;'); + console.log('\texport = ' + key3 + ';'); + console.log('}'); +} + +let printGroup = (modulename:string,loc:{}):void => { + let s:string[] = []; + let c = ''; + console.log('declare module "' + modulename + '" {'); + for(let key in loc) { + let com = ''; + let tmp = replace(key); + if(tmp == key) { + s.push(key); + } else { + com = '// '; + // s.push('"' + key + '":' + tmp); + c += ' /* ,"' + key + '":' + tmp + ' */'; + } + console.log('\t' + com + 'import ' + tmp + ' = require("' + modulename + '/' + key + '");'); + } + console.log('\texport {' + s.join(',') + c + '};'); + console.log('}'); +} + +let replace = (name:string):string => { + if(name == 'var') { + return 'Var'; + } + // if(name == 'string') { + // return 'String'; + // } + return name.replace('-','_'); +} + +let func = (loc:c,key1:string,key2:string,key3:string):string => { + return '"' + key3 + '":' + arg(loc,key1,key2,key3) + ' => any'; +} + +const ARG1 = "(...args:any[])"; + +let arg = (loc:c,key1:string,key2:string,key3:string):string => { + let src = loc[key1][key2][key3].toString(); + let mArguments = /[^a-zA-Z0-9_]arguments[^a-zA-Z0-9_]/; + if(mArguments.test(src)) { + return ARG1; + } + let mFunction = /^function [a-zA-Z0-9_]+\(/g; + let result1 = mFunction.exec(src); + if(result1 == null) { + return ARG1; + } + let mFunction2 = /(\s*[,]?\s*[a-zA-Z0-9_]+)*\)/g; + mFunction2.lastIndex = mFunction.lastIndex; + let result12 = mFunction2.exec(src); + let mParameter = /\s*[,]?\s*[a-zA-Z0-9_]+/g; + let args:string[] = []; + let i = 0; + let result2:any; + while((result2 = mParameter.exec(result12[0])) != null) { + args.push(result2[0]+'?:any'); + i++; + } + return '('+args.join('')+')'; +} + +let test = ():void => { + console.log('/// '); + for(let key1 in loc) { + for(let key2 in loc[key1]) { + for(let key3 in loc[key1][key2]) { + let modulename = 'locutus/' + key1 + '/' + key2 + '/' + key3; + testsub(modulename); + } + } + } + for(let key1 in loc) { + for(let key2 in loc[key1]) { + let modulename = 'locutus/' + key1 + '/' + key2; + testsub(modulename); + } + } + for(let key1 in loc) { + let modulename = 'locutus/' + key1; + testsub(modulename); + } + let modulename = 'locutus'; + testsub(modulename); +} + +let testsub = (modulename:string):void => { + let varname = modulename.replace(/[-/]/g,'_'); + console.log("import " + varname + " = require('" + modulename + "');"); +} + +let settings = ():void => { + let s = ''; + for(let key1 in loc) { + if(key1 != 'php') { + continue; + } + for(let key2 in loc[key1]) { + for(let key3 in loc[key1][key2]) { + if(s != '') { + s += ',\n'; + } + let len = 21 - key3.length; + let tab = ''; + while(len > 0) { + tab += '\t'; + len -= 4; + } + //"var_dump": {"cod":"var_dump", "mod":["var_dump","locutus/php/var/var_dump"]} + s += '\t\t\t\t"' + key3 + '":' + tab + '{"cod":"' + key3 + '","mod":["' + key3 + '","locutus/' + key1 + '/' + key2 + '/' + key3 + '"]}'; + } + } + } + console.log(s); +} + +run(); From fc61cd3b887486c91e1be65f3bca5fda284a9c57 Mon Sep 17 00:00:00 2001 From: Radu Woinaroski Date: Tue, 31 May 2016 21:07:42 +0200 Subject: [PATCH 149/402] mCustomScrollbar, fixed CustomScrollbarOptions for mouseWheel --- mCustomScrollbar/mCustomScrollbar.d.ts | 43 ++++++++++++++++++++++++-- 1 file changed, 41 insertions(+), 2 deletions(-) diff --git a/mCustomScrollbar/mCustomScrollbar.d.ts b/mCustomScrollbar/mCustomScrollbar.d.ts index 4aad109c66..08e532d7bf 100644 --- a/mCustomScrollbar/mCustomScrollbar.d.ts +++ b/mCustomScrollbar/mCustomScrollbar.d.ts @@ -36,9 +36,48 @@ declare namespace MCustomScrollbar { */ scrollInertia?: number; /** - * Mouse wheel support, value: true, false + * Mouse wheel support */ - mouseWheel?: boolean; + mouseWheel?: { + /** + * Enable or disable content scrolling via mouse-wheel. + */ + enable?: boolean; + /** + * Set the mouse-wheel scrolling amount (in pixels). + * The default value "auto" adjusts scrolling amount according to scrollable content length. + */ + scrollAmount?: number; + /** + * Define the mouse-wheel scrolling axis when both vertical and horizontal scrollbars are present. + * Set axis: "y" (default) for vertical or axis: "x" for horizontal scrolling. + */ + axis?: "x"|"y"; + /** + * Prevent the default behaviour which automatically scrolls the parent element when end + * or beginning of scrolling is reached (same bahavior with browser’s native scrollbar). + */ + preventDefault?: boolean; + /** + * Set the number of pixels one wheel notch scrolls. The default value “auto” uses the OS/browser value. + */ + deltaFactor?: number; + /** + * Enable or disable mouse-wheel (delta) acceleration. + * Setting normalizeDelta: true translates mouse-wheel delta value to -1 or 1. + */ + normalizeDelta?:boolean; + /** + * Invert mouse-wheel scrolling direction. + * Set to true to scroll down or right when mouse-wheel is turned upwards. + */ + invert?: boolean; + /** + * Set the tags that disable mouse-wheel when cursor is over them. + * Default value: ["select","option","keygen","datalist","textarea"] + */ + disableOver?: string[] + } /** * Mouse wheel scrolling pixels amount, value in pixels (integer) or "auto" (script calculates and sets pixels amount according to content length) */ From 752e1faa8d6af023743aa4de3970fae19eb56c58 Mon Sep 17 00:00:00 2001 From: Ryan McNamara Date: Tue, 31 May 2016 16:08:16 -0700 Subject: [PATCH 150/402] Add dagre-d3 type for transition --- dagre-d3/dagre-d3-tests.ts | 3 +++ dagre-d3/dagre-d3.d.ts | 2 ++ 2 files changed, 5 insertions(+) diff --git a/dagre-d3/dagre-d3-tests.ts b/dagre-d3/dagre-d3-tests.ts index ef5fddffac..6451913a89 100644 --- a/dagre-d3/dagre-d3-tests.ts +++ b/dagre-d3/dagre-d3-tests.ts @@ -11,6 +11,9 @@ namespace DagreD3Tests { predecessors["a"] = graph.predecessors("a"); successors["a"] = graph.successors("a"); + graph.transition = (selection: d3.Selection) => { + return d3.transition(); + }; const render = new dagreD3.render(); const svg = d3.select("svg"); diff --git a/dagre-d3/dagre-d3.d.ts b/dagre-d3/dagre-d3.d.ts index 68e24c2fa5..a0ab31e041 100644 --- a/dagre-d3/dagre-d3.d.ts +++ b/dagre-d3/dagre-d3.d.ts @@ -20,6 +20,8 @@ declare namespace Dagre { height: number; predecessors(id: string): string[]; successors(id: string): string[]; + // see source of http://cpettitt.github.io/project/dagre-d3/latest/demo/interactive-demo.html + transition?(selection: d3.Selection): d3.Transition; width: number; } From ce1b9ab23456cf096a31ea0359bdf098bd2b7408 Mon Sep 17 00:00:00 2001 From: Thomas Townsend Date: Thu, 2 Jun 2016 14:43:58 +0200 Subject: [PATCH 151/402] Add immutable typings (#9412) * Add immutable typings * Fix header * Rename immutable test --- immutable/immutable-tests.ts | 329 +++++ immutable/immutable.d.ts | 2546 ++++++++++++++++++++++++++++++++++ 2 files changed, 2875 insertions(+) create mode 100644 immutable/immutable-tests.ts create mode 100644 immutable/immutable.d.ts diff --git a/immutable/immutable-tests.ts b/immutable/immutable-tests.ts new file mode 100644 index 0000000000..17240ebe9c --- /dev/null +++ b/immutable/immutable-tests.ts @@ -0,0 +1,329 @@ +/// + +import immutable = require('immutable') + +// List tests + +let list: immutable.List = immutable.List([0, 1, 2, 3, 4, 5]); +let list1: immutable.List = immutable.List(list); + +list = immutable.List.of(0, 1, 2, 3, 4); +let bool: boolean = immutable.List.isList(list); + +list = list.set(0, 1); +list = list.delete(0); +list = list.remove(0); +list = list.insert(0, 1); +list = list.clear(); +list = list.push(0, 1, 2, 3, 4, 5); +list = list.pop(); +list = list.unshift(1, 2, 3); +list = list.shift(); +list = list.update((value: immutable.List) => value); +list = list.update(1, (value: number) => value); +list = list.update(1, 1, (value: number) => value); +list = list.merge(list1, list); +list = list.merge([0, 1, 2], [3, 4, 5]); +list = list.mergeWith((prev: number, next: number, key: number) => prev, list, list1); +list = list.mergeWith((prev: number, next: number, key: number) => prev, [0, 1, 2], [3, 4, 5]); +list = list.mergeDeep(list1, list); +list = list.mergeDeep([0, 1, 2], [3, 4, 5]); +list = list.mergeDeepWith((prev: number, next: number, key: number) => prev, list, list1); +list = list.mergeDeepWith((prev: number, next: number, key: number) => prev, [0, 1, 2], [3, 4, 5]); +list = list.setSize(5); +list = list.setIn([0, 1, 2], 5); +list = list.deleteIn([0, 1, 2]); +list = list.removeIn([0, 1, 2]); +list = list.updateIn([0, 1, 2], value => value); +list = list.updateIn([0, 1, 2], 1, value => value); +list = list.mergeIn([0, 1, 2], list, list1); +list = list.mergeIn([0, 1, 2], [0, 1, 2], [3, 4, 5]); +list = list.mergeDeepIn([0, 1, 2], list, list1); +list = list.mergeDeepIn([0, 1, 2], [0, 1, 2], [3, 4, 5]); +list = list.withMutations((mutable: immutable.List) => mutable); +list = list.asMutable(); +list = list.asImmutable(); + +// Collection.Indexed +let indexedSeq: immutable.Seq.Indexed = list.toSeq(); + +// Iterable tests +let value: number = list.get(0); +value = list.get(0, 1); +list = list.interpose(0); +list = list.interleave(list, list1); +list = list.splice(0, 2, 4, 5, 6); +list = list.zip(list1); +let indexedIterable: immutable.Iterable.Indexed = list.zipWith( + (value: number, other: number) => value + other, + list1 +); +let indexedIterable1: immutable.Iterable.Indexed = list.zipWith( + (value: number, other: number, third: number) => value + other + third, + list1, + indexedIterable +); +indexedIterable = list.zipWith( + (value: number, other: number, third: number) => value + other + third, + list1, + indexedIterable1 +); +value = list.indexOf(1); +value = list.lastIndexOf(1); +value = list.findIndex((value: number, index: number, iter: immutable.List) => true); +value = list.findLastIndex((value: number, index: number, iter: immutable.List) => true); +value = list.size; + +bool = list.equals(list1); +value = list.hashCode(); +bool = list.has(1); +bool = list.includes(1); +bool = list.contains(1); +value = list.first(); +value = list.last(); +let toArr: number[] = list.toArray(); +let toMap: immutable.Map = list.toMap(); +let toOrderedMap: immutable.OrderedMap = list.toOrderedMap(); +let toSet: immutable.Set = list.toSet(); +let toOrderedSet: immutable.OrderedSet = list.toOrderedSet(); +list = list.toList(); +let toStack: immutable.Stack = list.toStack(); +let toKeyedSeq: immutable.Seq.Keyed = list.toKeyedSeq(); +indexedSeq = list.toIndexedSeq(); +let toSetSeq: immutable.Seq.Set = list.toSetSeq(); + +let iter: immutable.Iterator = list.keys(); +iter = list.values(); +let iter1: immutable.Iterator<[number, number]> = list.entries(); + +indexedSeq = list.keySeq(); +indexedSeq = list.valueSeq(); +let indexedSeq1: immutable.Seq.Indexed<[number, number]> = list.entrySeq(); + +let iter2: immutable.Iterable = list.map( + (value: number, key: number, iter: immutable.List) => "foo" +) + +list = list.filterNot((value: number, key: number, iter: immutable.List) => true); +list = list.reverse(); +list = list.sort((valA: number, valB: number) => 0); +list = list.sortBy( + (value: number, key: number, iter: immutable.List) => "foo", + (valueA: string, valueB: string) => 0 +); + +let keyedSeq2: immutable.Seq.Keyed> = list.groupBy( + (value: number, key: number, iter: immutable.List) => "" +); + +value = list.forEach((value: number, key: number, iter: immutable.List) => true); +list = list.slice(0, 1); +list = list.rest(); +list = list.butLast(); +list = list.skip(0); +list = list.skipLast(0); +list = list.skipWhile( + (value: number, key: number, iter: immutable.List) => true +); +list = list.take(2); +list = list.takeLast(2); +list = list.takeWhile( + (value: number, key: number, iter: immutable.List) => true +); +list = list.takeUntil( + (value: number, key: number, iter: immutable.List) => true +); +list = list.concat(list1, 2, 3); +list = list.flatten(1); +list = list.flatten(true); +let str: string = list.reduce( + (red: string, value: number, key: number, iter: immutable.List) => red + "bar", + "foo" +); +str = list.reduceRight( + (red: string, value: number, key: number, iter: immutable.List) => red + "bar", + "foo" +); +bool = list.every( + (value: number, key: number, iter: immutable.List) => true +); +bool = list.some( + (value: number, key: number, iter: immutable.List) => true +); +str = list.join(","); +bool = list.isEmpty(); +value = list.count(); +value = list.count( + (value: number, key: number, iter: immutable.List) => true +); +let keyedSeq3: immutable.Seq.Keyed = list.countBy( + (value: number, key: number, iter: immutable.List) => "foo" +); +value = list.find( + (value: number, key: number, iter: immutable.List) => true, + null, + 0 +); +value = list.findLast( + (value: number, key: number, iter: immutable.List) => true, + null, + 0 +); +let tuple: [number, number] = list.findEntry( + (value: number, key: number, iter: immutable.List) => true, + null, + 0 +); +tuple = list.findLastEntry( + (value: number, key: number, iter: immutable.List) => true, + null, + 0 +); +value = list.findKey( + (value: number, key: number, iter: immutable.List) => true, + null +); +value = list.findLastKey( + (value: number, key: number, iter: immutable.List) => true, + null +); +value = list.keyOf(0); +value = list.lastKeyOf(0); +value = list.max((valA: number, valB: number) => 0); +value = list.maxBy( + (value: number, key: number, iter: immutable.List) => "foo", + (valueA: string, valueB: string) => 0 +); +value = list.min((valA: number, valB: number) => 0); +value = list.minBy( + (value: number, key: number, iter: immutable.List) => "foo", + (valueA: string, valueB: string) => 0 +); +bool = list.isSubset(list1); +bool = list.isSubset([0, 1, 2]); +bool = list.isSuperset(list1); +bool = list.isSuperset([0, 1, 2]); + + +// Map tests + +let map: immutable.Map = immutable.Map(); +map = immutable.Map([["foo", 1], ["bar", 2]]); +let map1: immutable.Map = immutable.Map(map); +map = map.set("baz", 3); +map.delete("foo"); +map.remove("foo"); +map = map.clear(); +map = map.update((value: immutable.Map) => value); +map = map.update("foo", (value: number) => value); +map = map.update("bar", 1, (value: number) => value); +map = map.merge(map1, map); +map = map.merge({ "foo": 0, "bar": 1}, {"baz": 2}); +map = map.mergeWith((prev: number, next: number, key: string) => prev, map, map1); +map = map.mergeWith((prev: number, next: number, key: string) => prev,{ "foo": 0, "bar": 1}, {"baz": 2}); +map = map.mergeDeep(map1, map); +map = map.mergeDeep({ "foo": 0, "bar": 1}, {"baz": 2}); +map = map.mergeDeepWith((prev: number, next: number, key: string) => prev, map, map1); +map = map.mergeDeepWith((prev: number, next: number, key: string) => prev, { "foo": 0, "bar": 1}, {"baz": 2}); +map = map.setIn([0, 1, 2], 5); +map = map.deleteIn([0, 1, 2]); +map = map.removeIn([0, 1, 2]); +map = map.updateIn([0, 1, 2], value => value); +map = map.updateIn([0, 1, 2], 1, value => value); +map = map.mergeIn([0, 1, 2], map, map1); +map = map.mergeIn([0, 1, 2], { "foo": 0, "bar": 1}, {"baz": 2}); +map = map.mergeDeepIn([0, 1, 2], map, map1); +map = map.mergeDeepIn([0, 1, 2], { "foo": 0, "bar": 1}, {"baz": 2}); +map = map.withMutations((mutable: immutable.Map) => mutable); +map = map.asMutable(); +map = map.asImmutable(); + +bool = immutable.Map.isMap(map); +map = immutable.Map.of("foo", 0, "bar", 1); + +// OrderedMap tests +bool = immutable.OrderedMap.isOrderedMap(toOrderedMap); +toOrderedMap = immutable.OrderedMap(toOrderedMap); + +// Set tests +let set: immutable.Set = immutable.Set.of(0, 1, 2, 3); +bool = immutable.Set.isSet(set); +set = immutable.Set.fromKeys(toMap); +let set1: immutable.Set = immutable.Set.fromKeys({ "foo": 1, "bar": 2}); +set = immutable.Set(); +set = immutable.Set(set); +set = set.add(3); +set.delete(1); +set.remove(2); +set = set.clear(); +set = set.union(map, list); +set = set.union([1, 2, 3], [4, 5, 6]); +set = set.merge(map1, list); +set = set.merge([1, 2, 3], [4, 5, 6]); +set = set.intersect(map1, list); +set = set.intersect([1, 2, 3], [4, 5, 6]); +set = set.subtract(map1, list); +set = set.subtract([1, 2, 3], [4, 5, 6]); +set = set.withMutations((mutable: immutable.Set) => mutable); +set = set.asMutable(); +set = set.asImmutable(); + + +// OrderedSet tests +bool = immutable.OrderedSet.isOrderedSet(set); +let orderedSet1: immutable.OrderedSet = immutable.OrderedSet.of(0, 1, 2, 3); +orderedSet1 = immutable.OrderedSet.fromKeys(toMap); +let orderedSet2: immutable.Set = immutable.Set.fromKeys({ "foo": 1, "bar": 2}); + +// Stack tests + +let stack: immutable.Stack = immutable.Stack(); +bool = immutable.Stack.isStack(stack); +stack = immutable.Stack.of(0, 1, 2, 3, 4, 5); +stack = immutable.Stack(list); +value = stack.peek(); +stack = stack.clear(); +stack = stack.unshift(0, 1, 2); +stack = stack.unshiftAll(list); +stack = stack.unshiftAll([1, 2, 3]); +stack = stack.shift(); +stack = stack.push(1, 2, 3); +stack = stack.pushAll(list); +stack = stack.pushAll([1, 2, 3]); +stack = stack.pop(); +stack = stack.withMutations((mutable: immutable.Stack) => mutable); +stack = stack.asMutable(); +stack = stack.asImmutable(); + + +// Range and Repeat function tests + +let funcSeqIndexed: immutable.Seq.Indexed = immutable.Range(0, 3, 1); +funcSeqIndexed = immutable.Repeat(2, 10); + + +// Seq tests +let seq: immutable.Seq = immutable.Seq(); +bool = immutable.Seq.isSeq(seq); +funcSeqIndexed = immutable.Seq.of(0, 1, 2, 3); +seq = immutable.Seq(map); +value = seq.size; +seq = seq.cacheResult(); + + +// keyed +let seqKeyed: immutable.Seq.Keyed = immutable.Seq.Keyed(); +seqKeyed = immutable.Seq.Keyed(map); +seqKeyed = seqKeyed.toSeq(); + +// indexed +let seqIndexed: immutable.Seq.Indexed = immutable.Seq.Indexed(); +seqIndexed = immutable.Seq.Indexed.of(0, 1, 2, 3); +seqIndexed = immutable.Seq.Indexed(list); +seqIndexed = seqIndexed.toSeq(); + +// indexed +let seqSet: immutable.Seq.Set = immutable.Seq.Set(); +seqSet = immutable.Seq.Set.of(0, 1, 2, 3); +seqSet = immutable.Seq.Set(list); +seqSet = seqSet.toSeq(); diff --git a/immutable/immutable.d.ts b/immutable/immutable.d.ts new file mode 100644 index 0000000000..5ca32ecfe4 --- /dev/null +++ b/immutable/immutable.d.ts @@ -0,0 +1,2546 @@ +// Type definitions for Facebook's Immutable 3.8.1 +// Project: https://github.com/facebook/immutable-js +// Definitions by: tht13 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// Core of typings are from repository itself + +/** + * Copyright (c) 2014-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + */ + +/** + * Immutable data encourages pure functions (data-in, data-out) and lends itself + * to much simpler application development and enabling techniques from + * functional programming such as lazy evaluation. + * + * While designed to bring these powerful functional concepts to JavaScript, it + * presents an Object-Oriented API familiar to Javascript engineers and closely + * mirroring that of Array, Map, and Set. It is easy and efficient to convert to + * and from plain Javascript types. + + * Note: all examples are presented in [ES6][]. To run in all browsers, they + * need to be translated to ES3. For example: + * + * // ES6 + * foo.map(x => x * x); + * // ES3 + * foo.map(function (x) { return x * x; }); + * + * [ES6]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/ECMAScript_6_support_in_Mozilla + */ + +declare namespace __Immutable { + + /** + * Deeply converts plain JS objects and arrays to Immutable Maps and Lists. + * + * If a `reviver` is optionally provided, it will be called with every + * collection as a Seq (beginning with the most nested collections + * and proceeding to the top-level collection itself), along with the key + * refering to each collection and the parent JS object provided as `this`. + * For the top level, object, the key will be `""`. This `reviver` is expected + * to return a new Immutable Iterable, allowing for custom conversions from + * deep JS objects. + * + * This example converts JSON to List and OrderedMap: + * + * Immutable.fromJS({a: {b: [10, 20, 30]}, c: 40}, function (key, value) { + * var isIndexed = Immutable.Iterable.isIndexed(value); + * return isIndexed ? value.toList() : value.toOrderedMap(); + * }); + * + * // true, "b", {b: [10, 20, 30]} + * // false, "a", {a: {b: [10, 20, 30]}, c: 40} + * // false, "", {"": {a: {b: [10, 20, 30]}, c: 40}} + * + * If `reviver` is not provided, the default behavior will convert Arrays into + * Lists and Objects into Maps. + * + * `reviver` acts similarly to the [same parameter in `JSON.parse`][1]. + * + * `Immutable.fromJS` is conservative in its conversion. It will only convert + * arrays which pass `Array.isArray` to Lists, and only raw objects (no custom + * prototype) to Map. + * + * Keep in mind, when using JS objects to construct Immutable Maps, that + * JavaScript Object properties are always strings, even if written in a + * quote-less shorthand, while Immutable Maps accept keys of any type. + * + * ```js + * var obj = { 1: "one" }; + * Object.keys(obj); // [ "1" ] + * obj["1"]; // "one" + * obj[1]; // "one" + * + * var map = Map(obj); + * map.get("1"); // "one" + * map.get(1); // undefined + * ``` + * + * Property access for JavaScript Objects first converts the key to a string, + * but since Immutable Map keys can be of any type the argument to `get()` is + * not altered. + * + * [1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter + * "Using the reviver parameter" + */ + export function fromJS( + json: any, + reviver?: (k: any, v: Iterable) => any + ): any; + + + /** + * Value equality check with semantics similar to `Object.is`, but treats + * Immutable `Iterable`s as values, equal if the second `Iterable` includes + * equivalent values. + * + * It's used throughout Immutable when checking for equality, including `Map` + * key equality and `Set` membership. + * + * var map1 = Immutable.Map({a:1, b:1, c:1}); + * var map2 = Immutable.Map({a:1, b:1, c:1}); + * assert(map1 !== map2); + * assert(Object.is(map1, map2) === false); + * assert(Immutable.is(map1, map2) === true); + * + * Note: Unlike `Object.is`, `Immutable.is` assumes `0` and `-0` are the same + * value, matching the behavior of ES6 Map key equality. + */ + export function is(first: any, second: any): boolean; + + + /** + * Lists are ordered indexed dense collections, much like a JavaScript + * Array. + * + * Lists are immutable and fully persistent with O(log32 N) gets and sets, + * and O(1) push and pop. + * + * Lists implement Deque, with efficient addition and removal from both the + * end (`push`, `pop`) and beginning (`unshift`, `shift`). + * + * Unlike a JavaScript Array, there is no distinction between an + * "unset" index and an index set to `undefined`. `List#forEach` visits all + * indices from 0 to size, regardless of whether they were explicitly defined. + */ + export module List { + + /** + * True if the provided value is a List + */ + function isList(maybeList: any): boolean; + + /** + * Creates a new List containing `values`. + */ + function of(...values: T[]): List; + } + + /** + * Create a new immutable List containing the values of the provided + * iterable-like. + */ + export function List(): List; + export function List(iter: Iterable.Indexed): List; + export function List(iter: Iterable.Set): List; + export function List(iter: Iterable.Keyed): List<[K,V]>; + export function List(array: Array): List; + export function List(iterator: Iterator): List; + export function List(iterable: Iterable): List; + + + export interface List extends Collection.Indexed { + + // Persistent changes + + /** + * Returns a new List which includes `value` at `index`. If `index` already + * exists in this List, it will be replaced. + * + * `index` may be a negative number, which indexes back from the end of the + * List. `v.set(-1, "value")` sets the last item in the List. + * + * If `index` larger than `size`, the returned List's `size` will be large + * enough to include the `index`. + */ + set(index: number, value: T): List; + + /** + * Returns a new List which excludes this `index` and with a size 1 less + * than this List. Values at indices above `index` are shifted down by 1 to + * fill the position. + * + * This is synonymous with `list.splice(index, 1)`. + * + * `index` may be a negative number, which indexes back from the end of the + * List. `v.delete(-1)` deletes the last item in the List. + * + * Note: `delete` cannot be safely used in IE8 + * @alias remove + */ + delete(index: number): List; + remove(index: number): List; + + /** + * Returns a new List with `value` at `index` with a size 1 more than this + * List. Values at indices above `index` are shifted over by 1. + * + * This is synonymous with `list.splice(index, 0, value) + */ + insert(index: number, value: T): List; + + /** + * Returns a new List with 0 size and no values. + */ + clear(): List; + + /** + * Returns a new List with the provided `values` appended, starting at this + * List's `size`. + */ + push(...values: T[]): List; + + /** + * Returns a new List with a size ones less than this List, excluding + * the last index in this List. + * + * Note: this differs from `Array#pop` because it returns a new + * List rather than the removed value. Use `last()` to get the last value + * in this List. + */ + pop(): List; + + /** + * Returns a new List with the provided `values` prepended, shifting other + * values ahead to higher indices. + */ + unshift(...values: T[]): List; + + /** + * Returns a new List with a size ones less than this List, excluding + * the first index in this List, shifting all other values to a lower index. + * + * Note: this differs from `Array#shift` because it returns a new + * List rather than the removed value. Use `first()` to get the first + * value in this List. + */ + shift(): List; + + /** + * Returns a new List with an updated value at `index` with the return + * value of calling `updater` with the existing value, or `notSetValue` if + * `index` was not set. If called with a single argument, `updater` is + * called with the List itself. + * + * `index` may be a negative number, which indexes back from the end of the + * List. `v.update(-1)` updates the last item in the List. + * + * @see `Map#update` + */ + update(updater: (value: List) => List): List; + update(index: number, updater: (value: T) => T): List; + update(index: number, notSetValue: T, updater: (value: T) => T): List; + + /** + * @see `Map#merge` + */ + merge(...iterables: Iterable.Indexed[]): List; + merge(...iterables: Array[]): List; + + /** + * @see `Map#mergeWith` + */ + mergeWith( + merger: (previous?: T, next?: T, key?: number) => T, + ...iterables: Iterable.Indexed[] + ): List; + mergeWith( + merger: (previous?: T, next?: T, key?: number) => T, + ...iterables: Array[] + ): List; + + /** + * @see `Map#mergeDeep` + */ + mergeDeep(...iterables: Iterable.Indexed[]): List; + mergeDeep(...iterables: Array[]): List; + + /** + * @see `Map#mergeDeepWith` + */ + mergeDeepWith( + merger: (previous?: T, next?: T, key?: number) => T, + ...iterables: Iterable.Indexed[] + ): List; + mergeDeepWith( + merger: (previous?: T, next?: T, key?: number) => T, + ...iterables: Array[] + ): List; + + /** + * Returns a new List with size `size`. If `size` is less than this + * List's size, the new List will exclude values at the higher indices. + * If `size` is greater than this List's size, the new List will have + * undefined values for the newly available indices. + * + * When building a new List and the final size is known up front, `setSize` + * used in conjunction with `withMutations` may result in the more + * performant construction. + */ + setSize(size: number): List; + + + // Deep persistent changes + + /** + * Returns a new List having set `value` at this `keyPath`. If any keys in + * `keyPath` do not exist, a new immutable Map will be created at that key. + * + * Index numbers are used as keys to determine the path to follow in + * the List. + */ + setIn(keyPath: Array, value: any): List; + setIn(keyPath: Iterable, value: any): List; + + /** + * Returns a new List having removed the value at this `keyPath`. If any + * keys in `keyPath` do not exist, no change will occur. + * + * @alias removeIn + */ + deleteIn(keyPath: Array): List; + deleteIn(keyPath: Iterable): List; + removeIn(keyPath: Array): List; + removeIn(keyPath: Iterable): List; + + /** + * @see `Map#updateIn` + */ + updateIn( + keyPath: Array, + updater: (value: any) => any + ): List; + updateIn( + keyPath: Array, + notSetValue: any, + updater: (value: any) => any + ): List; + updateIn( + keyPath: Iterable, + updater: (value: any) => any + ): List; + updateIn( + keyPath: Iterable, + notSetValue: any, + updater: (value: any) => any + ): List; + + /** + * @see `Map#mergeIn` + */ + mergeIn( + keyPath: Iterable, + ...iterables: Iterable.Indexed[] + ): List; + mergeIn( + keyPath: Array, + ...iterables: Iterable.Indexed[] + ): List; + mergeIn( + keyPath: Array, + ...iterables: Array[] + ): List; + + /** + * @see `Map#mergeDeepIn` + */ + mergeDeepIn( + keyPath: Iterable, + ...iterables: Iterable.Indexed[] + ): List; + mergeDeepIn( + keyPath: Array, + ...iterables: Iterable.Indexed[] + ): List; + mergeDeepIn( + keyPath: Array, + ...iterables: Array[] + ): List; + + + // Transient changes + + /** + * Note: Not all methods can be used on a mutable collection or within + * `withMutations`! Only `set`, `push`, `pop`, `shift`, `unshift` and + * `merge` may be used mutatively. + * + * @see `Map#withMutations` + */ + withMutations(mutator: (mutable: List) => any): List; + + /** + * @see `Map#asMutable` + */ + asMutable(): List; + + /** + * @see `Map#asImmutable` + */ + asImmutable(): List; + } + + + /** + * Immutable Map is an unordered Iterable.Keyed of (key, value) pairs with + * `O(log32 N)` gets and `O(log32 N)` persistent sets. + * + * Iteration order of a Map is undefined, however is stable. Multiple + * iterations of the same Map will iterate in the same order. + * + * Map's keys can be of any type, and use `Immutable.is` to determine key + * equality. This allows the use of any value (including NaN) as a key. + * + * Because `Immutable.is` returns equality based on value semantics, and + * Immutable collections are treated as values, any Immutable collection may + * be used as a key. + * + * Map().set(List.of(1), 'listofone').get(List.of(1)); + * // 'listofone' + * + * Any JavaScript object may be used as a key, however strict identity is used + * to evaluate key equality. Two similar looking objects will represent two + * different keys. + * + * Implemented by a hash-array mapped trie. + */ + export module Map { + + /** + * True if the provided value is a Map + */ + function isMap(maybeMap: any): boolean; + + /** + * Creates a new Map from alternating keys and values + */ + function of(...keyValues: (K|V)[]): Map; + } + + /** + * Creates a new Immutable Map. + * + * Created with the same key value pairs as the provided Iterable.Keyed or + * JavaScript Object or expects an Iterable of [K, V] tuple entries. + * + * var newMap = Map({key: "value"}); + * var newMap = Map([["key", "value"]]); + * + * Keep in mind, when using JS objects to construct Immutable Maps, that + * JavaScript Object properties are always strings, even if written in a + * quote-less shorthand, while Immutable Maps accept keys of any type. + * + * ```js + * var obj = { 1: "one" }; + * Object.keys(obj); // [ "1" ] + * obj["1"]; // "one" + * obj[1]; // "one" + * + * var map = Map(obj); + * map.get("1"); // "one" + * map.get(1); // undefined + * ``` + * + * Property access for JavaScript Objects first converts the key to a string, + * but since Immutable Map keys can be of any type the argument to `get()` is + * not altered. + */ + export function Map(): Map; + export function Map(iter: Iterable.Keyed): Map; + export function Map(iter: Iterable): Map; + export function Map(array: Array<[K,V]>): Map; + export function Map(obj: {[key: string]: V}): Map; + export function Map(iterator: Iterator<[K,V]>): Map; + export function Map(iterable: Iterable): Map; + + export interface Map extends Collection.Keyed { + + // Persistent changes + + /** + * Returns a new Map also containing the new key, value pair. If an equivalent + * key already exists in this Map, it will be replaced. + */ + set(key: K, value: V): Map; + + /** + * Returns a new Map which excludes this `key`. + * + * Note: `delete` cannot be safely used in IE8, but is provided to mirror + * the ES6 collection API. + * @alias remove + */ + delete(key: K): Map; + remove(key: K): Map; + + /** + * Returns a new Map containing no keys or values. + */ + clear(): Map; + + /** + * Returns a new Map having updated the value at this `key` with the return + * value of calling `updater` with the existing value, or `notSetValue` if + * the key was not set. If called with only a single argument, `updater` is + * called with the Map itself. + * + * Equivalent to: `map.set(key, updater(map.get(key, notSetValue)))`. + */ + update(updater: (value: Map) => Map): Map; + update(key: K, updater: (value: V) => V): Map; + update(key: K, notSetValue: V, updater: (value: V) => V): Map; + + /** + * Returns a new Map resulting from merging the provided Iterables + * (or JS objects) into this Map. In other words, this takes each entry of + * each iterable and sets it on this Map. + * + * If any of the values provided to `merge` are not Iterable (would return + * false for `Immutable.Iterable.isIterable`) then they are deeply converted + * via `Immutable.fromJS` before being merged. However, if the value is an + * Iterable but includes non-iterable JS objects or arrays, those nested + * values will be preserved. + * + * var x = Immutable.Map({a: 10, b: 20, c: 30}); + * var y = Immutable.Map({b: 40, a: 50, d: 60}); + * x.merge(y) // { a: 50, b: 40, c: 30, d: 60 } + * y.merge(x) // { b: 20, a: 10, d: 60, c: 30 } + * + */ + merge(...iterables: Iterable[]): Map; + merge(...iterables: {[key: string]: V}[]): Map; + + /** + * Like `merge()`, `mergeWith()` returns a new Map resulting from merging + * the provided Iterables (or JS objects) into this Map, but uses the + * `merger` function for dealing with conflicts. + * + * var x = Immutable.Map({a: 10, b: 20, c: 30}); + * var y = Immutable.Map({b: 40, a: 50, d: 60}); + * x.mergeWith((prev, next) => prev / next, y) // { a: 0.2, b: 0.5, c: 30, d: 60 } + * y.mergeWith((prev, next) => prev / next, x) // { b: 2, a: 5, d: 60, c: 30 } + * + */ + mergeWith( + merger: (previous?: V, next?: V, key?: K) => V, + ...iterables: Iterable[] + ): Map; + mergeWith( + merger: (previous?: V, next?: V, key?: K) => V, + ...iterables: {[key: string]: V}[] + ): Map; + + /** + * Like `merge()`, but when two Iterables conflict, it merges them as well, + * recursing deeply through the nested data. + * + * var x = Immutable.fromJS({a: { x: 10, y: 10 }, b: { x: 20, y: 50 } }); + * var y = Immutable.fromJS({a: { x: 2 }, b: { y: 5 }, c: { z: 3 } }); + * x.mergeDeep(y) // {a: { x: 2, y: 10 }, b: { x: 20, y: 5 }, c: { z: 3 } } + * + */ + mergeDeep(...iterables: Iterable[]): Map; + mergeDeep(...iterables: {[key: string]: V}[]): Map; + + /** + * Like `mergeDeep()`, but when two non-Iterables conflict, it uses the + * `merger` function to determine the resulting value. + * + * var x = Immutable.fromJS({a: { x: 10, y: 10 }, b: { x: 20, y: 50 } }); + * var y = Immutable.fromJS({a: { x: 2 }, b: { y: 5 }, c: { z: 3 } }); + * x.mergeDeepWith((prev, next) => prev / next, y) + * // {a: { x: 5, y: 10 }, b: { x: 20, y: 10 }, c: { z: 3 } } + * + */ + mergeDeepWith( + merger: (previous?: V, next?: V, key?: K) => V, + ...iterables: Iterable[] + ): Map; + mergeDeepWith( + merger: (previous?: V, next?: V, key?: K) => V, + ...iterables: {[key: string]: V}[] + ): Map; + + + // Deep persistent changes + + /** + * Returns a new Map having set `value` at this `keyPath`. If any keys in + * `keyPath` do not exist, a new immutable Map will be created at that key. + */ + setIn(keyPath: Array, value: any): Map; + setIn(KeyPath: Iterable, value: any): Map; + + /** + * Returns a new Map having removed the value at this `keyPath`. If any keys + * in `keyPath` do not exist, no change will occur. + * + * @alias removeIn + */ + deleteIn(keyPath: Array): Map; + deleteIn(keyPath: Iterable): Map; + removeIn(keyPath: Array): Map; + removeIn(keyPath: Iterable): Map; + + /** + * Returns a new Map having applied the `updater` to the entry found at the + * keyPath. + * + * If any keys in `keyPath` do not exist, new Immutable `Map`s will + * be created at those keys. If the `keyPath` does not already contain a + * value, the `updater` function will be called with `notSetValue`, if + * provided, otherwise `undefined`. + * + * var data = Immutable.fromJS({ a: { b: { c: 10 } } }); + * data = data.updateIn(['a', 'b', 'c'], val => val * 2); + * // { a: { b: { c: 20 } } } + * + * If the `updater` function returns the same value it was called with, then + * no change will occur. This is still true if `notSetValue` is provided. + * + * var data1 = Immutable.fromJS({ a: { b: { c: 10 } } }); + * data2 = data1.updateIn(['x', 'y', 'z'], 100, val => val); + * assert(data2 === data1); + * + */ + updateIn( + keyPath: Array, + updater: (value: any) => any + ): Map; + updateIn( + keyPath: Array, + notSetValue: any, + updater: (value: any) => any + ): Map; + updateIn( + keyPath: Iterable, + updater: (value: any) => any + ): Map; + updateIn( + keyPath: Iterable, + notSetValue: any, + updater: (value: any) => any + ): Map; + + /** + * A combination of `updateIn` and `merge`, returning a new Map, but + * performing the merge at a point arrived at by following the keyPath. + * In other words, these two lines are equivalent: + * + * x.updateIn(['a', 'b', 'c'], abc => abc.merge(y)); + * x.mergeIn(['a', 'b', 'c'], y); + * + */ + mergeIn( + keyPath: Iterable, + ...iterables: Iterable[] + ): Map; + mergeIn( + keyPath: Array, + ...iterables: Iterable[] + ): Map; + mergeIn( + keyPath: Array, + ...iterables: {[key: string]: V}[] + ): Map; + + /** + * A combination of `updateIn` and `mergeDeep`, returning a new Map, but + * performing the deep merge at a point arrived at by following the keyPath. + * In other words, these two lines are equivalent: + * + * x.updateIn(['a', 'b', 'c'], abc => abc.mergeDeep(y)); + * x.mergeDeepIn(['a', 'b', 'c'], y); + * + */ + mergeDeepIn( + keyPath: Iterable, + ...iterables: Iterable[] + ): Map; + mergeDeepIn( + keyPath: Array, + ...iterables: Iterable[] + ): Map; + mergeDeepIn( + keyPath: Array, + ...iterables: {[key: string]: V}[] + ): Map; + + + // Transient changes + + /** + * Every time you call one of the above functions, a new immutable Map is + * created. If a pure function calls a number of these to produce a final + * return value, then a penalty on performance and memory has been paid by + * creating all of the intermediate immutable Maps. + * + * If you need to apply a series of mutations to produce a new immutable + * Map, `withMutations()` creates a temporary mutable copy of the Map which + * can apply mutations in a highly performant manner. In fact, this is + * exactly how complex mutations like `merge` are done. + * + * As an example, this results in the creation of 2, not 4, new Maps: + * + * var map1 = Immutable.Map(); + * var map2 = map1.withMutations(map => { + * map.set('a', 1).set('b', 2).set('c', 3); + * }); + * assert(map1.size === 0); + * assert(map2.size === 3); + * + * Note: Not all methods can be used on a mutable collection or within + * `withMutations`! Only `set` and `merge` may be used mutatively. + * + */ + withMutations(mutator: (mutable: Map) => any): Map; + + /** + * Another way to avoid creation of intermediate Immutable maps is to create + * a mutable copy of this collection. Mutable copies *always* return `this`, + * and thus shouldn't be used for equality. Your function should never return + * a mutable copy of a collection, only use it internally to create a new + * collection. If possible, use `withMutations` as it provides an easier to + * use API. + * + * Note: if the collection is already mutable, `asMutable` returns itself. + * + * Note: Not all methods can be used on a mutable collection or within + * `withMutations`! Only `set` and `merge` may be used mutatively. + */ + asMutable(): Map; + + /** + * The yin to `asMutable`'s yang. Because it applies to mutable collections, + * this operation is *mutable* and returns itself. Once performed, the mutable + * copy has become immutable and can be safely returned from a function. + */ + asImmutable(): Map; + } + + + /** + * A type of Map that has the additional guarantee that the iteration order of + * entries will be the order in which they were set(). + * + * The iteration behavior of OrderedMap is the same as native ES6 Map and + * JavaScript Object. + * + * Note that `OrderedMap` are more expensive than non-ordered `Map` and may + * consume more memory. `OrderedMap#set` is amortized O(log32 N), but not + * stable. + */ + + export module OrderedMap { + + /** + * True if the provided value is an OrderedMap. + */ + function isOrderedMap(maybeOrderedMap: any): boolean; + } + + /** + * Creates a new Immutable OrderedMap. + * + * Created with the same key value pairs as the provided Iterable.Keyed or + * JavaScript Object or expects an Iterable of [K, V] tuple entries. + * + * The iteration order of key-value pairs provided to this constructor will + * be preserved in the OrderedMap. + * + * var newOrderedMap = OrderedMap({key: "value"}); + * var newOrderedMap = OrderedMap([["key", "value"]]); + * + */ + export function OrderedMap(): OrderedMap; + export function OrderedMap(iter: Iterable.Keyed): OrderedMap; + export function OrderedMap(iter: Iterable): OrderedMap; + export function OrderedMap(array: Array<[K,V]>): OrderedMap; + export function OrderedMap(obj: {[key: string]: V}): OrderedMap; + export function OrderedMap(iterator: Iterator<[K,V]>): OrderedMap; + export function OrderedMap(iterable: Iterable): OrderedMap; + + export interface OrderedMap extends Map {} + + + /** + * A Collection of unique values with `O(log32 N)` adds and has. + * + * When iterating a Set, the entries will be (value, value) pairs. Iteration + * order of a Set is undefined, however is stable. Multiple iterations of the + * same Set will iterate in the same order. + * + * Set values, like Map keys, may be of any type. Equality is determined using + * `Immutable.is`, enabling Sets to uniquely include other Immutable + * collections, custom value types, and NaN. + */ + export module Set { + + /** + * True if the provided value is a Set + */ + function isSet(maybeSet: any): boolean; + + /** + * Creates a new Set containing `values`. + */ + function of(...values: T[]): Set; + + /** + * `Set.fromKeys()` creates a new immutable Set containing the keys from + * this Iterable or JavaScript Object. + */ + function fromKeys(iter: Iterable): Set; + function fromKeys(obj: {[key: string]: any}): Set; + } + + /** + * Create a new immutable Set containing the values of the provided + * iterable-like. + */ + export function Set(): Set; + export function Set(iter: Iterable.Set): Set; + export function Set(iter: Iterable.Indexed): Set; + export function Set(iter: Iterable.Keyed): Set<[K,V]>; + export function Set(array: Array): Set; + export function Set(iterator: Iterator): Set; + export function Set(iterable: Iterable): Set; + + export interface Set extends Collection.Set { + + // Persistent changes + + /** + * Returns a new Set which also includes this value. + */ + add(value: T): Set; + + /** + * Returns a new Set which excludes this value. + * + * Note: `delete` cannot be safely used in IE8 + * @alias remove + */ + delete(value: T): Set; + remove(value: T): Set; + + /** + * Returns a new Set containing no values. + */ + clear(): Set; + + /** + * Returns a Set including any value from `iterables` that does not already + * exist in this Set. + * @alias merge + */ + union(...iterables: Iterable[]): Set; + union(...iterables: Array[]): Set; + merge(...iterables: Iterable[]): Set; + merge(...iterables: Array[]): Set; + + + /** + * Returns a Set which has removed any values not also contained + * within `iterables`. + */ + intersect(...iterables: Iterable[]): Set; + intersect(...iterables: Array[]): Set; + + /** + * Returns a Set excluding any values contained within `iterables`. + */ + subtract(...iterables: Iterable[]): Set; + subtract(...iterables: Array[]): Set; + + + // Transient changes + + /** + * Note: Not all methods can be used on a mutable collection or within + * `withMutations`! Only `add` may be used mutatively. + * + * @see `Map#withMutations` + */ + withMutations(mutator: (mutable: Set) => any): Set; + + /** + * @see `Map#asMutable` + */ + asMutable(): Set; + + /** + * @see `Map#asImmutable` + */ + asImmutable(): Set; + } + + + /** + * A type of Set that has the additional guarantee that the iteration order of + * values will be the order in which they were `add`ed. + * + * The iteration behavior of OrderedSet is the same as native ES6 Set. + * + * Note that `OrderedSet` are more expensive than non-ordered `Set` and may + * consume more memory. `OrderedSet#add` is amortized O(log32 N), but not + * stable. + */ + export module OrderedSet { + + /** + * True if the provided value is an OrderedSet. + */ + function isOrderedSet(maybeOrderedSet: any): boolean; + + /** + * Creates a new OrderedSet containing `values`. + */ + function of(...values: T[]): OrderedSet; + + /** + * `OrderedSet.fromKeys()` creates a new immutable OrderedSet containing + * the keys from this Iterable or JavaScript Object. + */ + function fromKeys(iter: Iterable): OrderedSet; + function fromKeys(obj: {[key: string]: any}): OrderedSet; + } + + /** + * Create a new immutable OrderedSet containing the values of the provided + * iterable-like. + */ + export function OrderedSet(): OrderedSet; + export function OrderedSet(iter: Iterable.Set): OrderedSet; + export function OrderedSet(iter: Iterable.Indexed): OrderedSet; + export function OrderedSet(iter: Iterable.Keyed): OrderedSet<[K,V]>; + export function OrderedSet(array: Array): OrderedSet; + export function OrderedSet(iterator: Iterator): OrderedSet; + export function OrderedSet(iterable: Iterable): OrderedSet; + + export interface OrderedSet extends Set {} + + + /** + * Stacks are indexed collections which support very efficient O(1) addition + * and removal from the front using `unshift(v)` and `shift()`. + * + * For familiarity, Stack also provides `push(v)`, `pop()`, and `peek()`, but + * be aware that they also operate on the front of the list, unlike List or + * a JavaScript Array. + * + * Note: `reverse()` or any inherent reverse traversal (`reduceRight`, + * `lastIndexOf`, etc.) is not efficient with a Stack. + * + * Stack is implemented with a Single-Linked List. + */ + export module Stack { + + /** + * True if the provided value is a Stack + */ + function isStack(maybeStack: any): boolean; + + /** + * Creates a new Stack containing `values`. + */ + function of(...values: T[]): Stack; + } + + /** + * Create a new immutable Stack containing the values of the provided + * iterable-like. + * + * The iteration order of the provided iterable is preserved in the + * resulting `Stack`. + */ + export function Stack(): Stack; + export function Stack(iter: Iterable.Indexed): Stack; + export function Stack(iter: Iterable.Set): Stack; + export function Stack(iter: Iterable.Keyed): Stack<[K,V]>; + export function Stack(array: Array): Stack; + export function Stack(iterator: Iterator): Stack; + export function Stack(iterable: Iterable): Stack; + + export interface Stack extends Collection.Indexed { + + // Reading values + + /** + * Alias for `Stack.first()`. + */ + peek(): T; + + + // Persistent changes + + /** + * Returns a new Stack with 0 size and no values. + */ + clear(): Stack; + + /** + * Returns a new Stack with the provided `values` prepended, shifting other + * values ahead to higher indices. + * + * This is very efficient for Stack. + */ + unshift(...values: T[]): Stack; + + /** + * Like `Stack#unshift`, but accepts a iterable rather than varargs. + */ + unshiftAll(iter: Iterable): Stack; + unshiftAll(iter: Array): Stack; + + /** + * Returns a new Stack with a size ones less than this Stack, excluding + * the first item in this Stack, shifting all other values to a lower index. + * + * Note: this differs from `Array#shift` because it returns a new + * Stack rather than the removed value. Use `first()` or `peek()` to get the + * first value in this Stack. + */ + shift(): Stack; + + /** + * Alias for `Stack#unshift` and is not equivalent to `List#push`. + */ + push(...values: T[]): Stack; + + /** + * Alias for `Stack#unshiftAll`. + */ + pushAll(iter: Iterable): Stack; + pushAll(iter: Array): Stack; + + /** + * Alias for `Stack#shift` and is not equivalent to `List#pop`. + */ + pop(): Stack; + + + // Transient changes + + /** + * Note: Not all methods can be used on a mutable collection or within + * `withMutations`! Only `set`, `push`, and `pop` may be used mutatively. + * + * @see `Map#withMutations` + */ + withMutations(mutator: (mutable: Stack) => any): Stack; + + /** + * @see `Map#asMutable` + */ + asMutable(): Stack; + + /** + * @see `Map#asImmutable` + */ + asImmutable(): Stack; + } + + + /** + * Returns a Seq.Indexed of numbers from `start` (inclusive) to `end` + * (exclusive), by `step`, where `start` defaults to 0, `step` to 1, and `end` to + * infinity. When `start` is equal to `end`, returns empty range. + * + * Range() // [0,1,2,3,...] + * Range(10) // [10,11,12,13,...] + * Range(10,15) // [10,11,12,13,14] + * Range(10,30,5) // [10,15,20,25] + * Range(30,10,5) // [30,25,20,15] + * Range(30,30,5) // [] + * + */ + export function Range(start?: number, end?: number, step?: number): Seq.Indexed; + + + /** + * Returns a Seq.Indexed of `value` repeated `times` times. When `times` is + * not defined, returns an infinite `Seq` of `value`. + * + * Repeat('foo') // ['foo','foo','foo',...] + * Repeat('bar',4) // ['bar','bar','bar','bar'] + * + */ + export function Repeat(value: T, times?: number): Seq.Indexed; + + + /** + * Creates a new Class which produces Record instances. A record is similar to + * a JS object, but enforce a specific set of allowed string keys, and have + * default values. + * + * var ABRecord = Record({a:1, b:2}) + * var myRecord = new ABRecord({b:3}) + * + * Records always have a value for the keys they define. `remove`ing a key + * from a record simply resets it to the default value for that key. + * + * myRecord.size // 2 + * myRecord.get('a') // 1 + * myRecord.get('b') // 3 + * myRecordWithoutB = myRecord.remove('b') + * myRecordWithoutB.get('b') // 2 + * myRecordWithoutB.size // 2 + * + * Values provided to the constructor not found in the Record type will + * be ignored. For example, in this case, ABRecord is provided a key "x" even + * though only "a" and "b" have been defined. The value for "x" will be + * ignored for this record. + * + * var myRecord = new ABRecord({b:3, x:10}) + * myRecord.get('x') // undefined + * + * Because Records have a known set of string keys, property get access works + * as expected, however property sets will throw an Error. + * + * Note: IE8 does not support property access. Only use `get()` when + * supporting IE8. + * + * myRecord.b // 3 + * myRecord.b = 5 // throws Error + * + * Record Classes can be extended as well, allowing for custom methods on your + * Record. This is not a common pattern in functional environments, but is in + * many JS programs. + * + * Note: TypeScript does not support this type of subclassing. + * + * class ABRecord extends Record({a:1,b:2}) { + * getAB() { + * return this.a + this.b; + * } + * } + * + * var myRecord = new ABRecord({b: 3}) + * myRecord.getAB() // 4 + * + */ + export module Record { + export interface Class { + new (): Map; + new (values: {[key: string]: any}): Map; + new (values: Iterable): Map; // deprecated + + (): Map; + (values: {[key: string]: any}): Map; + (values: Iterable): Map; // deprecated + } + } + + export function Record( + defaultValues: {[key: string]: any}, name?: string + ): Record.Class; + + + /** + * Represents a sequence of values, but may not be backed by a concrete data + * structure. + * + * **Seq is immutable** — Once a Seq is created, it cannot be + * changed, appended to, rearranged or otherwise modified. Instead, any + * mutative method called on a `Seq` will return a new `Seq`. + * + * **Seq is lazy** — Seq does as little work as necessary to respond to any + * method call. Values are often created during iteration, including implicit + * iteration when reducing or converting to a concrete data structure such as + * a `List` or JavaScript `Array`. + * + * For example, the following performs no work, because the resulting + * Seq's values are never iterated: + * + * var oddSquares = Immutable.Seq.of(1,2,3,4,5,6,7,8) + * .filter(x => x % 2).map(x => x * x); + * + * Once the Seq is used, it performs only the work necessary. In this + * example, no intermediate data structures are ever created, filter is only + * called three times, and map is only called once: + * + * console.log(oddSquares.get(1)); // 9 + * + * Seq allows for the efficient chaining of operations, + * allowing for the expression of logic that can otherwise be very tedious: + * + * Immutable.Seq({a:1, b:1, c:1}) + * .flip().map(key => key.toUpperCase()).flip().toObject(); + * // Map { A: 1, B: 1, C: 1 } + * + * As well as expressing logic that would otherwise be memory or time limited: + * + * Immutable.Range(1, Infinity) + * .skip(1000) + * .map(n => -n) + * .filter(n => n % 2 === 0) + * .take(2) + * .reduce((r, n) => r * n, 1); + * // 1006008 + * + * Seq is often used to provide a rich collection API to JavaScript Object. + * + * Immutable.Seq({ x: 0, y: 1, z: 2 }).map(v => v * 2).toObject(); + * // { x: 0, y: 2, z: 4 } + */ + + export module Seq { + /** + * True if `maybeSeq` is a Seq, it is not backed by a concrete + * structure such as Map, List, or Set. + */ + function isSeq(maybeSeq: any): boolean; + + /** + * Returns a Seq of the values provided. Alias for `Seq.Indexed.of()`. + */ + function of(...values: T[]): Seq.Indexed; + + + /** + * `Seq` which represents key-value pairs. + */ + export module Keyed {} + + /** + * Always returns a Seq.Keyed, if input is not keyed, expects an + * iterable of [K, V] tuples. + */ + export function Keyed(): Seq.Keyed; + export function Keyed(seq: Iterable.Keyed): Seq.Keyed; + export function Keyed(seq: Iterable): Seq.Keyed; + export function Keyed(array: Array<[K,V]>): Seq.Keyed; + export function Keyed(obj: {[key: string]: V}): Seq.Keyed; + export function Keyed(iterator: Iterator<[K,V]>): Seq.Keyed; + export function Keyed(iterable: Iterable): Seq.Keyed; + + export interface Keyed extends Seq, Iterable.Keyed { + + /** + * Returns itself + */ + toSeq(): this + } + + + /** + * `Seq` which represents an ordered indexed list of values. + */ + module Indexed { + + /** + * Provides an Seq.Indexed of the values provided. + */ + function of(...values: T[]): Seq.Indexed; + } + + /** + * Always returns Seq.Indexed, discarding associated keys and + * supplying incrementing indices. + */ + export function Indexed(): Seq.Indexed; + export function Indexed(seq: Iterable.Indexed): Seq.Indexed; + export function Indexed(seq: Iterable.Set): Seq.Indexed; + export function Indexed(seq: Iterable.Keyed): Seq.Indexed<[K,V]>; + export function Indexed(array: Array): Seq.Indexed; + export function Indexed(iterator: Iterator): Seq.Indexed; + export function Indexed(iterable: Iterable): Seq.Indexed; + + export interface Indexed extends Seq, Iterable.Indexed { + + /** + * Returns itself + */ + toSeq(): this + } + + + /** + * `Seq` which represents a set of values. + * + * Because `Seq` are often lazy, `Seq.Set` does not provide the same guarantee + * of value uniqueness as the concrete `Set`. + */ + export module Set { + + /** + * Returns a Seq.Set of the provided values + */ + function of(...values: T[]): Seq.Set; + } + + /** + * Always returns a Seq.Set, discarding associated indices or keys. + */ + export function Set(): Seq.Set; + export function Set(seq: Iterable.Set): Seq.Set; + export function Set(seq: Iterable.Indexed): Seq.Set; + export function Set(seq: Iterable.Keyed): Seq.Set<[K,V]>; + export function Set(array: Array): Seq.Set; + export function Set(iterator: Iterator): Seq.Set; + export function Set(iterable: Iterable): Seq.Set; + + export interface Set extends Seq, Iterable.Set { + + /** + * Returns itself + */ + toSeq(): this + } + + } + + /** + * Creates a Seq. + * + * Returns a particular kind of `Seq` based on the input. + * + * * If a `Seq`, that same `Seq`. + * * If an `Iterable`, a `Seq` of the same kind (Keyed, Indexed, or Set). + * * If an Array-like, an `Seq.Indexed`. + * * If an Object with an Iterator, an `Seq.Indexed`. + * * If an Iterator, an `Seq.Indexed`. + * * If an Object, a `Seq.Keyed`. + * + */ + export function Seq(): Seq; + export function Seq(seq: Seq): Seq; + export function Seq(iterable: Iterable): Seq; + export function Seq(array: Array): Seq.Indexed; + export function Seq(obj: {[key: string]: V}): Seq.Keyed; + export function Seq(iterator: Iterator): Seq.Indexed; + export function Seq(iterable: Iterable): Seq.Indexed; + + export interface Seq extends Iterable { + + /** + * Some Seqs can describe their size lazily. When this is the case, + * size will be an integer. Otherwise it will be undefined. + * + * For example, Seqs returned from `map()` or `reverse()` + * preserve the size of the original `Seq` while `filter()` does not. + * + * Note: `Range`, `Repeat` and `Seq`s made from `Array`s and `Object`s will + * always have a size. + */ + size: number/*?*/; + + + // Force evaluation + + /** + * Because Sequences are lazy and designed to be chained together, they do + * not cache their results. For example, this map function is called a total + * of 6 times, as each `join` iterates the Seq of three values. + * + * var squares = Seq.of(1,2,3).map(x => x * x); + * squares.join() + squares.join(); + * + * If you know a `Seq` will be used multiple times, it may be more + * efficient to first cache it in memory. Here, the map function is called + * only 3 times. + * + * var squares = Seq.of(1,2,3).map(x => x * x).cacheResult(); + * squares.join() + squares.join(); + * + * Use this method judiciously, as it must fully evaluate a Seq which can be + * a burden on memory and possibly performance. + * + * Note: after calling `cacheResult`, a Seq will always have a `size`. + */ + cacheResult(): this; + } + + /** + * The `Iterable` is a set of (key, value) entries which can be iterated, and + * is the base class for all collections in `immutable`, allowing them to + * make use of all the Iterable methods (such as `map` and `filter`). + * + * Note: An iterable is always iterated in the same order, however that order + * may not always be well defined, as is the case for the `Map` and `Set`. + */ + export module Iterable { + /** + * True if `maybeIterable` is an Iterable, or any of its subclasses. + */ + function isIterable(maybeIterable: any): boolean; + + /** + * True if `maybeKeyed` is an Iterable.Keyed, or any of its subclasses. + */ + function isKeyed(maybeKeyed: any): boolean; + + /** + * True if `maybeIndexed` is a Iterable.Indexed, or any of its subclasses. + */ + function isIndexed(maybeIndexed: any): boolean; + + /** + * True if `maybeAssociative` is either a keyed or indexed Iterable. + */ + function isAssociative(maybeAssociative: any): boolean; + + /** + * True if `maybeOrdered` is an Iterable where iteration order is well + * defined. True for Iterable.Indexed as well as OrderedMap and OrderedSet. + */ + function isOrdered(maybeOrdered: any): boolean; + + + /** + * Keyed Iterables have discrete keys tied to each value. + * + * When iterating `Iterable.Keyed`, each iteration will yield a `[K, V]` + * tuple, in other words, `Iterable#entries` is the default iterator for + * Keyed Iterables. + */ + export module Keyed {} + + /** + * Creates an Iterable.Keyed + * + * Similar to `Iterable()`, however it expects iterable-likes of [K, V] + * tuples if not constructed from a Iterable.Keyed or JS Object. + */ + export function Keyed(iter: Iterable.Keyed): Iterable.Keyed; + export function Keyed(iter: Iterable): Iterable.Keyed; + export function Keyed(array: Array<[K,V]>): Iterable.Keyed; + export function Keyed(obj: {[key: string]: V}): Iterable.Keyed; + export function Keyed(iterator: Iterator<[K,V]>): Iterable.Keyed; + export function Keyed(iterable: Iterable): Iterable.Keyed; + + export interface Keyed extends Iterable { + + /** + * Returns Seq.Keyed. + * @override + */ + toSeq(): Seq.Keyed; + + + // Sequence functions + + /** + * Returns a new Iterable.Keyed of the same type where the keys and values + * have been flipped. + * + * Seq({ a: 'z', b: 'y' }).flip() // { z: 'a', y: 'b' } + * + */ + flip(): this; + + /** + * Returns a new Iterable.Keyed of the same type with keys passed through + * a `mapper` function. + * + * Seq({ a: 1, b: 2 }) + * .mapKeys(x => x.toUpperCase()) + * // Seq { A: 1, B: 2 } + * + */ + mapKeys( + mapper: (key?: K, value?: V, iter?: this) => M, + context?: any + ): /*this*/Iterable.Keyed; + + /** + * Returns a new Iterable.Keyed of the same type with entries + * ([key, value] tuples) passed through a `mapper` function. + * + * Seq({ a: 1, b: 2 }) + * .mapEntries(([k, v]) => [k.toUpperCase(), v * 2]) + * // Seq { A: 2, B: 4 } + * + */ + mapEntries( + mapper: ( + entry?: [K, V], + index?: number, + iter?: this + ) => [KM, VM], + context?: any + ): /*this*/Iterable.Keyed; + } + + + /** + * Indexed Iterables have incrementing numeric keys. They exhibit + * slightly different behavior than `Iterable.Keyed` for some methods in order + * to better mirror the behavior of JavaScript's `Array`, and add methods + * which do not make sense on non-indexed Iterables such as `indexOf`. + * + * Unlike JavaScript arrays, `Iterable.Indexed`s are always dense. "Unset" + * indices and `undefined` indices are indistinguishable, and all indices from + * 0 to `size` are visited when iterated. + * + * All Iterable.Indexed methods return re-indexed Iterables. In other words, + * indices always start at 0 and increment until size. If you wish to + * preserve indices, using them as keys, convert to a Iterable.Keyed by + * calling `toKeyedSeq`. + */ + export module Indexed {} + + /** + * Creates a new Iterable.Indexed. + */ + export function Indexed(iter: Iterable.Indexed): Iterable.Indexed; + export function Indexed(iter: Iterable.Set): Iterable.Indexed; + export function Indexed(iter: Iterable.Keyed): Iterable.Indexed<[K,V]>; + export function Indexed(array: Array): Iterable.Indexed; + export function Indexed(iterator: Iterator): Iterable.Indexed; + export function Indexed(iterable: Iterable): Iterable.Indexed; + + export interface Indexed extends Iterable { + + // Reading values + + /** + * Returns the value associated with the provided index, or notSetValue if + * the index is beyond the bounds of the Iterable. + * + * `index` may be a negative number, which indexes back from the end of the + * Iterable. `s.get(-1)` gets the last item in the Iterable. + */ + get(index: number, notSetValue?: T): T; + + + // Conversion to Seq + + /** + * Returns Seq.Indexed. + * @override + */ + toSeq(): Seq.Indexed; + + /** + * If this is an iterable of [key, value] entry tuples, it will return a + * Seq.Keyed of those entries. + */ + fromEntrySeq(): Seq.Keyed; + + + // Combination + + /** + * Returns an Iterable of the same type with `separator` between each item + * in this Iterable. + */ + interpose(separator: T): this; + + /** + * Returns an Iterable of the same type with the provided `iterables` + * interleaved into this iterable. + * + * The resulting Iterable includes the first item from each, then the + * second from each, etc. + * + * I.Seq.of(1,2,3).interleave(I.Seq.of('A','B','C')) + * // Seq [ 1, 'A', 2, 'B', 3, 'C' ] + * + * The shortest Iterable stops interleave. + * + * I.Seq.of(1,2,3).interleave( + * I.Seq.of('A','B'), + * I.Seq.of('X','Y','Z') + * ) + * // Seq [ 1, 'A', 'X', 2, 'B', 'Y' ] + */ + interleave(...iterables: Array>): this; + + /** + * Splice returns a new indexed Iterable by replacing a region of this + * Iterable with new values. If values are not provided, it only skips the + * region to be removed. + * + * `index` may be a negative number, which indexes back from the end of the + * Iterable. `s.splice(-2)` splices after the second to last item. + * + * Seq(['a','b','c','d']).splice(1, 2, 'q', 'r', 's') + * // Seq ['a', 'q', 'r', 's', 'd'] + * + */ + splice( + index: number, + removeNum: number, + ...values: Array | T> + ): this; + + /** + * Returns an Iterable of the same type "zipped" with the provided + * iterables. + * + * Like `zipWith`, but using the default `zipper`: creating an `Array`. + * + * var a = Seq.of(1, 2, 3); + * var b = Seq.of(4, 5, 6); + * var c = a.zip(b); // Seq [ [ 1, 4 ], [ 2, 5 ], [ 3, 6 ] ] + * + */ + zip(...iterables: Array>): this; + + /** + * Returns an Iterable of the same type "zipped" with the provided + * iterables by using a custom `zipper` function. + * + * var a = Seq.of(1, 2, 3); + * var b = Seq.of(4, 5, 6); + * var c = a.zipWith((a, b) => a + b, b); // Seq [ 5, 7, 9 ] + * + */ + zipWith( + zipper: (value: T, otherValue: U) => Z, + otherIterable: Iterable + ): Iterable.Indexed; + zipWith( + zipper: (value: T, otherValue: U, thirdValue: V) => Z, + otherIterable: Iterable, + thirdIterable: Iterable + ): Iterable.Indexed; + zipWith( + zipper: (...any: Array) => Z, + ...iterables: Array> + ): Iterable.Indexed; + + + // Search for value + + /** + * Returns the first index at which a given value can be found in the + * Iterable, or -1 if it is not present. + */ + indexOf(searchValue: T): number; + + /** + * Returns the last index at which a given value can be found in the + * Iterable, or -1 if it is not present. + */ + lastIndexOf(searchValue: T): number; + + /** + * Returns the first index in the Iterable where a value satisfies the + * provided predicate function. Otherwise -1 is returned. + */ + findIndex( + predicate: (value?: T, index?: number, iter?: this) => boolean, + context?: any + ): number; + + /** + * Returns the last index in the Iterable where a value satisfies the + * provided predicate function. Otherwise -1 is returned. + */ + findLastIndex( + predicate: (value?: T, index?: number, iter?: this) => boolean, + context?: any + ): number; + } + + + /** + * Set Iterables only represent values. They have no associated keys or + * indices. Duplicate values are possible in Seq.Sets, however the + * concrete `Set` does not allow duplicate values. + * + * Iterable methods on Iterable.Set such as `map` and `forEach` will provide + * the value as both the first and second arguments to the provided function. + * + * var seq = Seq.Set.of('A', 'B', 'C'); + * assert.equal(seq.every((v, k) => v === k), true); + * + */ + export module Set {} + + /** + * Similar to `Iterable()`, but always returns a Iterable.Set. + */ + export function Set(iter: Iterable.Set): Iterable.Set; + export function Set(iter: Iterable.Indexed): Iterable.Set; + export function Set(iter: Iterable.Keyed): Iterable.Set<[K,V]>; + export function Set(array: Array): Iterable.Set; + export function Set(iterator: Iterator): Iterable.Set; + export function Set(iterable: Iterable): Iterable.Set; + + export interface Set extends Iterable { + + /** + * Returns Seq.Set. + * @override + */ + toSeq(): Seq.Set; + } + + } + + /** + * Creates an Iterable. + * + * The type of Iterable created is based on the input. + * + * * If an `Iterable`, that same `Iterable`. + * * If an Array-like, an `Iterable.Indexed`. + * * If an Object with an Iterator, an `Iterable.Indexed`. + * * If an Iterator, an `Iterable.Indexed`. + * * If an Object, an `Iterable.Keyed`. + * + * This methods forces the conversion of Objects and Strings to Iterables. + * If you want to ensure that a Iterable of one item is returned, use + * `Seq.of`. + */ + export function Iterable(iterable: Iterable): Iterable; + export function Iterable(array: Array): Iterable.Indexed; + export function Iterable(obj: {[key: string]: V}): Iterable.Keyed; + export function Iterable(iterator: Iterator): Iterable.Indexed; + export function Iterable(iterable: Iterable): Iterable.Indexed; + export function Iterable(value: V): Iterable.Indexed; + + export interface Iterable { + + // Value equality + + /** + * True if this and the other Iterable have value equality, as defined + * by `Immutable.is()`. + * + * Note: This is equivalent to `Immutable.is(this, other)`, but provided to + * allow for chained expressions. + */ + equals(other: Iterable): boolean; + + /** + * Computes and returns the hashed identity for this Iterable. + * + * The `hashCode` of an Iterable is used to determine potential equality, + * and is used when adding this to a `Set` or as a key in a `Map`, enabling + * lookup via a different instance. + * + * var a = List.of(1, 2, 3); + * var b = List.of(1, 2, 3); + * assert(a !== b); // different instances + * var set = Set.of(a); + * assert(set.has(b) === true); + * + * If two values have the same `hashCode`, they are [not guaranteed + * to be equal][Hash Collision]. If two values have different `hashCode`s, + * they must not be equal. + * + * [Hash Collision]: http://en.wikipedia.org/wiki/Collision_(computer_science) + */ + hashCode(): number; + + + // Reading values + + /** + * Returns the value associated with the provided key, or notSetValue if + * the Iterable does not contain this key. + * + * Note: it is possible a key may be associated with an `undefined` value, + * so if `notSetValue` is not provided and this method returns `undefined`, + * that does not guarantee the key was not found. + */ + get(key: K, notSetValue?: V): V; + + /** + * True if a key exists within this `Iterable`, using `Immutable.is` to determine equality + */ + has(key: K): boolean; + + /** + * True if a value exists within this `Iterable`, using `Immutable.is` to determine equality + * @alias contains + */ + includes(value: V): boolean; + contains(value: V): boolean; + + /** + * The first value in the Iterable. + */ + first(): V; + + /** + * The last value in the Iterable. + */ + last(): V; + + + // Reading deep values + + /** + * Returns the value found by following a path of keys or indices through + * nested Iterables. + */ + getIn(searchKeyPath: Array, notSetValue?: any): any; + getIn(searchKeyPath: Iterable, notSetValue?: any): any; + + /** + * True if the result of following a path of keys or indices through nested + * Iterables results in a set value. + */ + hasIn(searchKeyPath: Array): boolean; + hasIn(searchKeyPath: Iterable): boolean; + + + // Conversion to JavaScript types + + /** + * Deeply converts this Iterable to equivalent JS. + * + * `Iterable.Indexeds`, and `Iterable.Sets` become Arrays, while + * `Iterable.Keyeds` become Objects. + * + * @alias toJSON + */ + toJS(): any; + + /** + * Shallowly converts this iterable to an Array, discarding keys. + */ + toArray(): Array; + + /** + * Shallowly converts this Iterable to an Object. + * + * Throws if keys are not strings. + */ + toObject(): { [key: string]: V }; + + + // Conversion to Collections + + /** + * Converts this Iterable to a Map, Throws if keys are not hashable. + * + * Note: This is equivalent to `Map(this.toKeyedSeq())`, but provided + * for convenience and to allow for chained expressions. + */ + toMap(): Map; + + /** + * Converts this Iterable to a Map, maintaining the order of iteration. + * + * Note: This is equivalent to `OrderedMap(this.toKeyedSeq())`, but + * provided for convenience and to allow for chained expressions. + */ + toOrderedMap(): OrderedMap; + + /** + * Converts this Iterable to a Set, discarding keys. Throws if values + * are not hashable. + * + * Note: This is equivalent to `Set(this)`, but provided to allow for + * chained expressions. + */ + toSet(): Set; + + /** + * Converts this Iterable to a Set, maintaining the order of iteration and + * discarding keys. + * + * Note: This is equivalent to `OrderedSet(this.valueSeq())`, but provided + * for convenience and to allow for chained expressions. + */ + toOrderedSet(): OrderedSet; + + /** + * Converts this Iterable to a List, discarding keys. + * + * Note: This is equivalent to `List(this)`, but provided to allow + * for chained expressions. + */ + toList(): List; + + /** + * Converts this Iterable to a Stack, discarding keys. Throws if values + * are not hashable. + * + * Note: This is equivalent to `Stack(this)`, but provided to allow for + * chained expressions. + */ + toStack(): Stack; + + + // Conversion to Seq + + /** + * Converts this Iterable to a Seq of the same kind (indexed, + * keyed, or set). + */ + toSeq(): Seq; + + /** + * Returns a Seq.Keyed from this Iterable where indices are treated as keys. + * + * This is useful if you want to operate on an + * Iterable.Indexed and preserve the [index, value] pairs. + * + * The returned Seq will have identical iteration order as + * this Iterable. + * + * Example: + * + * var indexedSeq = Immutable.Seq.of('A', 'B', 'C'); + * indexedSeq.filter(v => v === 'B').toString() // Seq [ 'B' ] + * var keyedSeq = indexedSeq.toKeyedSeq(); + * keyedSeq.filter(v => v === 'B').toString() // Seq { 1: 'B' } + * + */ + toKeyedSeq(): Seq.Keyed; + + /** + * Returns an Seq.Indexed of the values of this Iterable, discarding keys. + */ + toIndexedSeq(): Seq.Indexed; + + /** + * Returns a Seq.Set of the values of this Iterable, discarding keys. + */ + toSetSeq(): Seq.Set; + + + // Iterators + + /** + * An iterator of this `Iterable`'s keys. + * + * Note: this will return an ES6 iterator which does not support Immutable JS sequence algorithms. Use `keySeq` instead, if this is what you want. + */ + keys(): Iterator; + + /** + * An iterator of this `Iterable`'s values. + * + * Note: this will return an ES6 iterator which does not support Immutable JS sequence algorithms. Use `valueSeq` instead, if this is what you want. + */ + values(): Iterator; + + /** + * An iterator of this `Iterable`'s entries as `[key, value]` tuples. + * + * Note: this will return an ES6 iterator which does not support Immutable JS sequence algorithms. Use `entrySeq` instead, if this is what you want. + */ + entries(): Iterator<[K, V]>; + + + // Iterables (Seq) + + /** + * Returns a new Seq.Indexed of the keys of this Iterable, + * discarding values. + */ + keySeq(): Seq.Indexed; + + /** + * Returns an Seq.Indexed of the values of this Iterable, discarding keys. + */ + valueSeq(): Seq.Indexed; + + /** + * Returns a new Seq.Indexed of [key, value] tuples. + */ + entrySeq(): Seq.Indexed<[K, V]>; + + + // Sequence algorithms + + /** + * Returns a new Iterable of the same type with values passed through a + * `mapper` function. + * + * Seq({ a: 1, b: 2 }).map(x => 10 * x) + * // Seq { a: 10, b: 20 } + * + */ + map( + mapper: (value?: V, key?: K, iter?: this) => M, + context?: any + ): /*this*/Iterable; + + /** + * Returns a new Iterable of the same type with only the entries for which + * the `predicate` function returns true. + * + * Seq({a:1,b:2,c:3,d:4}).filter(x => x % 2 === 0) + * // Seq { b: 2, d: 4 } + * + */ + filter( + predicate: (value?: V, key?: K, iter?: this) => boolean, + context?: any + ): this; + + /** + * Returns a new Iterable of the same type with only the entries for which + * the `predicate` function returns false. + * + * Seq({a:1,b:2,c:3,d:4}).filterNot(x => x % 2 === 0) + * // Seq { a: 1, c: 3 } + * + */ + filterNot( + predicate: (value?: V, key?: K, iter?: this) => boolean, + context?: any + ): this; + + /** + * Returns a new Iterable of the same type in reverse order. + */ + reverse(): this; + + /** + * Returns a new Iterable of the same type which includes the same entries, + * stably sorted by using a `comparator`. + * + * If a `comparator` is not provided, a default comparator uses `<` and `>`. + * + * `comparator(valueA, valueB)`: + * + * * Returns `0` if the elements should not be swapped. + * * Returns `-1` (or any negative number) if `valueA` comes before `valueB` + * * Returns `1` (or any positive number) if `valueA` comes after `valueB` + * * Is pure, i.e. it must always return the same value for the same pair + * of values. + * + * When sorting collections which have no defined order, their ordered + * equivalents will be returned. e.g. `map.sort()` returns OrderedMap. + */ + sort(comparator?: (valueA: V, valueB: V) => number): this; + + /** + * Like `sort`, but also accepts a `comparatorValueMapper` which allows for + * sorting by more sophisticated means: + * + * hitters.sortBy(hitter => hitter.avgHits); + * + */ + sortBy( + comparatorValueMapper: (value?: V, key?: K, iter?: this) => C, + comparator?: (valueA: C, valueB: C) => number + ): this; + + /** + * Returns a `Iterable.Keyed` of `Iterable.Keyeds`, grouped by the return + * value of the `grouper` function. + * + * Note: This is always an eager operation. + */ + groupBy( + grouper: (value?: V, key?: K, iter?: this) => G, + context?: any + ): Seq.Keyed; + + + // Side effects + + /** + * The `sideEffect` is executed for every entry in the Iterable. + * + * Unlike `Array#forEach`, if any call of `sideEffect` returns + * `false`, the iteration will stop. Returns the number of entries iterated + * (including the last iteration which returned false). + */ + forEach( + sideEffect: (value?: V, key?: K, iter?: this) => any, + context?: any + ): number; + + + // Creating subsets + + /** + * Returns a new Iterable of the same type representing a portion of this + * Iterable from start up to but not including end. + * + * If begin is negative, it is offset from the end of the Iterable. e.g. + * `slice(-2)` returns a Iterable of the last two entries. If it is not + * provided the new Iterable will begin at the beginning of this Iterable. + * + * If end is negative, it is offset from the end of the Iterable. e.g. + * `slice(0, -1)` returns an Iterable of everything but the last entry. If + * it is not provided, the new Iterable will continue through the end of + * this Iterable. + * + * If the requested slice is equivalent to the current Iterable, then it + * will return itself. + */ + slice(begin?: number, end?: number): this; + + /** + * Returns a new Iterable of the same type containing all entries except + * the first. + */ + rest(): this; + + /** + * Returns a new Iterable of the same type containing all entries except + * the last. + */ + butLast(): this; + + /** + * Returns a new Iterable of the same type which excludes the first `amount` + * entries from this Iterable. + */ + skip(amount: number): this; + + /** + * Returns a new Iterable of the same type which excludes the last `amount` + * entries from this Iterable. + */ + skipLast(amount: number): this; + + /** + * Returns a new Iterable of the same type which includes entries starting + * from when `predicate` first returns false. + * + * Seq.of('dog','frog','cat','hat','god') + * .skipWhile(x => x.match(/g/)) + * // Seq [ 'cat', 'hat', 'god' ] + * + */ + skipWhile( + predicate: (value?: V, key?: K, iter?: this) => boolean, + context?: any + ): this; + + /** + * Returns a new Iterable of the same type which includes entries starting + * from when `predicate` first returns true. + * + * Seq.of('dog','frog','cat','hat','god') + * .skipUntil(x => x.match(/hat/)) + * // Seq [ 'hat', 'god' ] + * + */ + skipUntil( + predicate: (value?: V, key?: K, iter?: this) => boolean, + context?: any + ): this; + + /** + * Returns a new Iterable of the same type which includes the first `amount` + * entries from this Iterable. + */ + take(amount: number): this; + + /** + * Returns a new Iterable of the same type which includes the last `amount` + * entries from this Iterable. + */ + takeLast(amount: number): this; + + /** + * Returns a new Iterable of the same type which includes entries from this + * Iterable as long as the `predicate` returns true. + * + * Seq.of('dog','frog','cat','hat','god') + * .takeWhile(x => x.match(/o/)) + * // Seq [ 'dog', 'frog' ] + * + */ + takeWhile( + predicate: (value?: V, key?: K, iter?: this) => boolean, + context?: any + ): this; + + /** + * Returns a new Iterable of the same type which includes entries from this + * Iterable as long as the `predicate` returns false. + * + * Seq.of('dog','frog','cat','hat','god').takeUntil(x => x.match(/at/)) + * // ['dog', 'frog'] + * + */ + takeUntil( + predicate: (value?: V, key?: K, iter?: this) => boolean, + context?: any + ): this; + + + // Combination + + /** + * Returns a new Iterable of the same type with other values and + * iterable-like concatenated to this one. + * + * For Seqs, all entries will be present in + * the resulting iterable, even if they have the same key. + */ + concat(...valuesOrIterables: Array|V>): this; + + /** + * Flattens nested Iterables. + * + * Will deeply flatten the Iterable by default, returning an Iterable of the + * same type, but a `depth` can be provided in the form of a number or + * boolean (where true means to shallowly flatten one level). A depth of 0 + * (or shallow: false) will deeply flatten. + * + * Flattens only others Iterable, not Arrays or Objects. + * + * Note: `flatten(true)` operates on Iterable> and + * returns Iterable + */ + flatten(depth?: number): this; + flatten(shallow?: boolean): this; + + /** + * Flat-maps the Iterable, returning an Iterable of the same type. + * + * Similar to `iter.map(...).flatten(true)`. + */ + flatMap( + mapper: (value?: V, key?: K, iter?: this) => Iterable, + context?: any + ): /*this*/Iterable; + flatMap( + mapper: (value?: V, key?: K, iter?: this) => /*iterable-like*/any, + context?: any + ): /*this*/Iterable; + + + // Reducing a value + + /** + * Reduces the Iterable to a value by calling the `reducer` for every entry + * in the Iterable and passing along the reduced value. + * + * If `initialReduction` is not provided, or is null, the first item in the + * Iterable will be used. + * + * @see `Array#reduce`. + */ + reduce( + reducer: (reduction?: R, value?: V, key?: K, iter?: this) => R, + initialReduction?: R, + context?: any + ): R; + + /** + * Reduces the Iterable in reverse (from the right side). + * + * Note: Similar to this.reverse().reduce(), and provided for parity + * with `Array#reduceRight`. + */ + reduceRight( + reducer: (reduction?: R, value?: V, key?: K, iter?: this) => R, + initialReduction?: R, + context?: any + ): R; + + /** + * True if `predicate` returns true for all entries in the Iterable. + */ + every( + predicate: (value?: V, key?: K, iter?: this) => boolean, + context?: any + ): boolean; + + /** + * True if `predicate` returns true for any entry in the Iterable. + */ + some( + predicate: (value?: V, key?: K, iter?: this) => boolean, + context?: any + ): boolean; + + /** + * Joins values together as a string, inserting a separator between each. + * The default separator is `","`. + */ + join(separator?: string): string; + + /** + * Returns true if this Iterable includes no values. + * + * For some lazy `Seq`, `isEmpty` might need to iterate to determine + * emptiness. At most one iteration will occur. + */ + isEmpty(): boolean; + + /** + * Returns the size of this Iterable. + * + * Regardless of if this Iterable can describe its size lazily (some Seqs + * cannot), this method will always return the correct size. E.g. it + * evaluates a lazy `Seq` if necessary. + * + * If `predicate` is provided, then this returns the count of entries in the + * Iterable for which the `predicate` returns true. + */ + count(): number; + count( + predicate: (value?: V, key?: K, iter?: this) => boolean, + context?: any + ): number; + + /** + * Returns a `Seq.Keyed` of counts, grouped by the return value of + * the `grouper` function. + * + * Note: This is not a lazy operation. + */ + countBy( + grouper: (value?: V, key?: K, iter?: this) => G, + context?: any + ): Seq.Keyed; + + + // Search for value + + /** + * Returns the first value for which the `predicate` returns true. + */ + find( + predicate: (value?: V, key?: K, iter?: this) => boolean, + context?: any, + notSetValue?: V + ): V; + + /** + * Returns the last value for which the `predicate` returns true. + * + * Note: `predicate` will be called for each entry in reverse. + */ + findLast( + predicate: (value?: V, key?: K, iter?: this) => boolean, + context?: any, + notSetValue?: V + ): V; + + /** + * Returns the first [key, value] entry for which the `predicate` returns true. + */ + findEntry( + predicate: (value?: V, key?: K, iter?: this) => boolean, + context?: any, + notSetValue?: V + ): [K, V]; + + /** + * Returns the last [key, value] entry for which the `predicate` + * returns true. + * + * Note: `predicate` will be called for each entry in reverse. + */ + findLastEntry( + predicate: (value?: V, key?: K, iter?: this) => boolean, + context?: any, + notSetValue?: V + ): [K, V]; + + /** + * Returns the key for which the `predicate` returns true. + */ + findKey( + predicate: (value?: V, key?: K, iter?: this) => boolean, + context?: any + ): K; + + /** + * Returns the last key for which the `predicate` returns true. + * + * Note: `predicate` will be called for each entry in reverse. + */ + findLastKey( + predicate: (value?: V, key?: K, iter?: this) => boolean, + context?: any + ): K; + + /** + * Returns the key associated with the search value, or undefined. + */ + keyOf(searchValue: V): K; + + /** + * Returns the last key associated with the search value, or undefined. + */ + lastKeyOf(searchValue: V): K; + + /** + * Returns the maximum value in this collection. If any values are + * comparatively equivalent, the first one found will be returned. + * + * The `comparator` is used in the same way as `Iterable#sort`. If it is not + * provided, the default comparator is `>`. + * + * When two values are considered equivalent, the first encountered will be + * returned. Otherwise, `max` will operate independent of the order of input + * as long as the comparator is commutative. The default comparator `>` is + * commutative *only* when types do not differ. + * + * If `comparator` returns 0 and either value is NaN, undefined, or null, + * that value will be returned. + */ + max(comparator?: (valueA: V, valueB: V) => number): V; + + /** + * Like `max`, but also accepts a `comparatorValueMapper` which allows for + * comparing by more sophisticated means: + * + * hitters.maxBy(hitter => hitter.avgHits); + * + */ + maxBy( + comparatorValueMapper: (value?: V, key?: K, iter?: this) => C, + comparator?: (valueA: C, valueB: C) => number + ): V; + + /** + * Returns the minimum value in this collection. If any values are + * comparatively equivalent, the first one found will be returned. + * + * The `comparator` is used in the same way as `Iterable#sort`. If it is not + * provided, the default comparator is `<`. + * + * When two values are considered equivalent, the first encountered will be + * returned. Otherwise, `min` will operate independent of the order of input + * as long as the comparator is commutative. The default comparator `<` is + * commutative *only* when types do not differ. + * + * If `comparator` returns 0 and either value is NaN, undefined, or null, + * that value will be returned. + */ + min(comparator?: (valueA: V, valueB: V) => number): V; + + /** + * Like `min`, but also accepts a `comparatorValueMapper` which allows for + * comparing by more sophisticated means: + * + * hitters.minBy(hitter => hitter.avgHits); + * + */ + minBy( + comparatorValueMapper: (value?: V, key?: K, iter?: this) => C, + comparator?: (valueA: C, valueB: C) => number + ): V; + + + // Comparison + + /** + * True if `iter` includes every value in this Iterable. + */ + isSubset(iter: Iterable): boolean; + isSubset(iter: Array): boolean; + + /** + * True if this Iterable includes every value in `iter`. + */ + isSuperset(iter: Iterable): boolean; + isSuperset(iter: Array): boolean; + + + /** + * Note: this is here as a convenience to work around an issue with + * TypeScript https://github.com/Microsoft/TypeScript/issues/285, but + * Iterable does not define `size`, instead `Seq` defines `size` as + * nullable number, and `Collection` defines `size` as always a number. + * + * @ignore + */ + size: number; + } + + + /** + * Collection is the abstract base class for concrete data structures. It + * cannot be constructed directly. + * + * Implementations should extend one of the subclasses, `Collection.Keyed`, + * `Collection.Indexed`, or `Collection.Set`. + */ + export module Collection { + + + /** + * `Collection` which represents key-value pairs. + */ + export module Keyed {} + + export interface Keyed extends Collection, Iterable.Keyed { + + /** + * Returns Seq.Keyed. + * @override + */ + toSeq(): Seq.Keyed; + } + + + /** + * `Collection` which represents ordered indexed values. + */ + export module Indexed {} + + export interface Indexed extends Collection, Iterable.Indexed { + + /** + * Returns Seq.Indexed. + * @override + */ + toSeq(): Seq.Indexed; + } + + + /** + * `Collection` which represents values, unassociated with keys or indices. + * + * `Collection.Set` implementations should guarantee value uniqueness. + */ + export module Set {} + + export interface Set extends Collection, Iterable.Set { + + /** + * Returns Seq.Set. + * @override + */ + toSeq(): Seq.Set; + } + + } + + export interface Collection extends Iterable { + + /** + * All collections maintain their current `size` as an integer. + */ + size: number; + } + + + /** + * ES6 Iterator. + * + * This is not part of the Immutable library, but a common interface used by + * many types in ES6 JavaScript. + * + * @ignore + */ + export interface Iterator { + next(): { value: T; done: boolean; } + } + +} + +declare module "immutable" { + export = __Immutable +} From c16125cd7119cd3a3a82133649c2d68afcc37345 Mon Sep 17 00:00:00 2001 From: Dan Marshall Date: Thu, 2 Jun 2016 05:45:30 -0700 Subject: [PATCH 152/402] Updates to Bezier-js (#9441) * Added definitions for Bezier.Js * updates for maker.js and bezier.js * removed copyright * deleted bezierjs * Added definitions for Bezier.Js * updates for maker.js and bezier.js * deleted bezierjs * changed name to DefinitelyTyped * update tests for 0.8.0 * rename to bezier-js * add pdfkit reference * public clockwise * added signatures for split() * added extra signature for split() * Added definitions for Bezier.Js * updates for maker.js and bezier.js * removed copyright * deleted bezierjs * Added definitions for Bezier.Js * deleted bezierjs * changed name to DefinitelyTyped * rename to bezier-js * add pdfkit reference * public clockwise * added signatures for split() * added extra signature for split() --- bezier-js/bezier-js-tests.ts | 5 +++-- bezier-js/bezier-js.d.ts | 3 ++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/bezier-js/bezier-js-tests.ts b/bezier-js/bezier-js-tests.ts index 1814d67dc0..54c629d11b 100644 --- a/bezier-js/bezier-js-tests.ts +++ b/bezier-js/bezier-js-tests.ts @@ -31,7 +31,7 @@ function test() { bezier.get(1); bezier.getLUT()[0].x; bezier.hull(0); - bezier.inflections().values; + bezier.extrema(); bezier.intersects(bezier); bezier.length(); bezier.lineIntersects(line); @@ -48,7 +48,8 @@ function test() { bezier.scale(4); bezier.selfintersects(); bezier.simple(); - bezier.split(0, 1); + bezier.split(0, 1).clockwise; + bezier.split(0.5).left; bezier.toSVG(); bezier.update(); diff --git a/bezier-js/bezier-js.d.ts b/bezier-js/bezier-js.d.ts index 7d54a19d95..35e5cc19f1 100644 --- a/bezier-js/bezier-js.d.ts +++ b/bezier-js/bezier-js.d.ts @@ -117,7 +117,8 @@ declare module BezierJs { private __normal3(t); private __normal(t); hull(t: number): Point[]; - split(t1: number, t2?: number): Bezier | Split; + split(t1: number): Split; + split(t1: number, t2: number): Bezier; extrema(): Inflection; bbox(): BBox; overlaps(curve: Bezier): boolean; From 191daf6112933a8edb5fd9011a76bf42a8e36b12 Mon Sep 17 00:00:00 2001 From: Caleb Eggensperger Date: Thu, 2 Jun 2016 08:49:24 -0400 Subject: [PATCH 153/402] Fix component router breakage (#9442) --- angularjs/angular-component-router.d.ts | 51 +++++++++++++++++++++++++ angularjs/angular.d.ts | 44 --------------------- 2 files changed, 51 insertions(+), 44 deletions(-) diff --git a/angularjs/angular-component-router.d.ts b/angularjs/angular-component-router.d.ts index 2c56ef3a21..3b037b58b1 100644 --- a/angularjs/angular-component-router.d.ts +++ b/angularjs/angular-component-router.d.ts @@ -428,4 +428,55 @@ declare namespace angular { interface OnReuse { $routerOnReuse(next?: angular.ComponentInstruction, prev?: angular.ComponentInstruction): any; } + + /** + * Runtime representation a type that a Component or other object is instances of. + * + * An example of a `Type` is `MyCustomComponent` class, which in JavaScript is be represented by + * the `MyCustomComponent` constructor function. + */ + interface Type extends Function { + } + + /** + * `RouteDefinition` defines a route within a {@link RouteConfig} decorator. + * + * Supported keys: + * - `path` or `aux` (requires exactly one of these) + * - `component`, `loader`, `redirectTo` (requires exactly one of these) + * - `name` or `as` (optional) (requires exactly one of these) + * - `data` (optional) + * + * See also {@link Route}, {@link AsyncRoute}, {@link AuxRoute}, and {@link Redirect}. + */ + interface RouteDefinition { + path?: string; + aux?: string; + component?: Type | ComponentDefinition | string; + loader?: Function; + redirectTo?: any[]; + as?: string; + name?: string; + data?: any; + useAsDefault?: boolean; + } + + /** + * Represents either a component type (`type` is `component`) or a loader function + * (`type` is `loader`). + * + * See also {@link RouteDefinition}. + */ + interface ComponentDefinition { + type: string; + loader?: Function; + component?: Type; + } + + // Supplement IComponentOptions from angular.d.ts with router-specific + // fields. + interface IComponentOptions { + $canActivate?: () => boolean; + $routeConfig?: RouteDefinition[]; + } } diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 204c645b0c..983c0ca799 100644 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -1656,50 +1656,6 @@ declare namespace angular { // see http://angularjs.blogspot.com.br/2015/11/angularjs-15-beta2-and-14-releases.html // and http://toddmotto.com/exploring-the-angular-1-5-component-method/ /////////////////////////////////////////////////////////////////////////// - /** - * Runtime representation a type that a Component or other object is instances of. - * - * An example of a `Type` is `MyCustomComponent` class, which in JavaScript is be represented by - * the `MyCustomComponent` constructor function. - */ - interface Type extends Function { - } - - /** - * `RouteDefinition` defines a route within a {@link RouteConfig} decorator. - * - * Supported keys: - * - `path` or `aux` (requires exactly one of these) - * - `component`, `loader`, `redirectTo` (requires exactly one of these) - * - `name` or `as` (optional) (requires exactly one of these) - * - `data` (optional) - * - * See also {@link Route}, {@link AsyncRoute}, {@link AuxRoute}, and {@link Redirect}. - */ - interface RouteDefinition { - path?: string; - aux?: string; - component?: Type | ComponentDefinition | string; - loader?: Function; - redirectTo?: any[]; - as?: string; - name?: string; - data?: any; - useAsDefault?: boolean; - } - - /** - * Represents either a component type (`type` is `component`) or a loader function - * (`type` is `loader`). - * - * See also {@link RouteDefinition}. - */ - interface ComponentDefinition { - type: string; - loader?: Function; - component?: Type; - } - /** * Component definition object (a simplified directive definition object) */ From 61d2636c2cec3f3e290c9cf3d60646a192d817bc Mon Sep 17 00:00:00 2001 From: Chris Manning Date: Fri, 3 Jun 2016 00:50:23 +1200 Subject: [PATCH 154/402] Changed hapi IRouteConfiguration handler property to be optional (#9439) The hapi IRouteConfiguration handler property should be optional as the handler can alternatively be provided via the config property using the handler property of IRouteAdditionalConfigurationOptions. --- hapi/hapi.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hapi/hapi.d.ts b/hapi/hapi.d.ts index 05f4aa1047..2867dd7de9 100644 --- a/hapi/hapi.d.ts +++ b/hapi/hapi.d.ts @@ -875,7 +875,7 @@ declare module "hapi" { /** - an optional domain string or an array of domain strings for limiting the route to only requests with a matching host header field.Matching is done against the hostname part of the header only (excluding the port).Defaults to all hosts.*/ vhost?: string; /** - (required) the function called to generate the response after successful authentication and validation.The handler function is described in Route handler.If set to a string, the value is parsed the same way a prerequisite server method string shortcut is processed.Alternatively, handler can be assigned an object with a single key using the name of a registered handler type and value with the options passed to the registered handler.*/ - handler: ISessionHandler | string | IRouteHandlerConfig; + handler?: ISessionHandler | string | IRouteHandlerConfig; /** - additional route options.*/ config?: IRouteAdditionalConfigurationOptions; } From d4ab7731d392a74f71c47b0e35adee5e50863737 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roman=20W=C3=BCrsch?= Date: Thu, 2 Jun 2016 14:51:06 +0200 Subject: [PATCH 155/402] WheelEvent extends MouseEvent not SyntheticEvent (#9437) --- react/react.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/react/react.d.ts b/react/react.d.ts index 4dd185d89c..ce9d188d10 100644 --- a/react/react.d.ts +++ b/react/react.d.ts @@ -347,7 +347,7 @@ declare namespace __React { view: AbstractView; } - interface WheelEvent extends SyntheticEvent { + interface WheelEvent extends MouseEvent { deltaMode: number; deltaX: number; deltaY: number; From 65b05d550d7aeb09b8e755c89d2c7aecdd5baf04 Mon Sep 17 00:00:00 2001 From: Jeongho Nam Date: Thu, 2 Jun 2016 21:54:06 +0900 Subject: [PATCH 156/402] TypeScript-STL & Samchon-Framework (#9448) TypeScript-STL v0.9.9 Samchon Framework v1.1.0 --- .../samchon-collection-tests.ts | 7 + samchon-collection/samchon-collection.d.ts | 23 + samchon-framework/samchon-framework-tests.ts | 7 + samchon-framework/samchon-framework.d.ts | 2710 +++++++++++++++++ samchon-library/samchon-library-tests.ts | 7 + samchon-library/samchon-library.d.ts | 23 + typescript-stl/typescript-stl.d.ts | 2187 ++++++++----- 7 files changed, 4119 insertions(+), 845 deletions(-) create mode 100644 samchon-collection/samchon-collection-tests.ts create mode 100644 samchon-collection/samchon-collection.d.ts create mode 100644 samchon-framework/samchon-framework-tests.ts create mode 100644 samchon-framework/samchon-framework.d.ts create mode 100644 samchon-library/samchon-library-tests.ts create mode 100644 samchon-library/samchon-library.d.ts diff --git a/samchon-collection/samchon-collection-tests.ts b/samchon-collection/samchon-collection-tests.ts new file mode 100644 index 0000000000..028eb32caa --- /dev/null +++ b/samchon-collection/samchon-collection-tests.ts @@ -0,0 +1,7 @@ +/// + +declare var global: any; +declare var require: (name: string) => any; + +collection = require("samchon-collection"); +console.log(collection); \ No newline at end of file diff --git a/samchon-collection/samchon-collection.d.ts b/samchon-collection/samchon-collection.d.ts new file mode 100644 index 0000000000..3decceb20b --- /dev/null +++ b/samchon-collection/samchon-collection.d.ts @@ -0,0 +1,23 @@ +// Type definitions for Samchon Collection v0.0.2 +// Project: https://github.com/samchon/framework +// Definitions by: Jeongho Nam +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// ------------------------------------------------------------------------------------ +// In Samchon Collection, merging multiple 'ts' files to a module is not possible yet. +// Instead of using "import" instruction, use such trick: +// +// +// declare var global: any; +// declare var require: Function; +// +// collection = require("samchon-collection"); +// let cont: collection.ArrayCollection = new collection.ArrayCollection(); +// +// +// Those declaration of global and require can be substituted by using "node.d.ts" +// ------------------------------------------------------------------------------------ + +/// + +declare var collection: typeof samchon.collection; \ No newline at end of file diff --git a/samchon-framework/samchon-framework-tests.ts b/samchon-framework/samchon-framework-tests.ts new file mode 100644 index 0000000000..5820b158c3 --- /dev/null +++ b/samchon-framework/samchon-framework-tests.ts @@ -0,0 +1,7 @@ +/// + +declare var global: any; +declare var require: any; + +global["samchon"] = require("samchon-framework"); +console.log(samchon); \ No newline at end of file diff --git a/samchon-framework/samchon-framework.d.ts b/samchon-framework/samchon-framework.d.ts new file mode 100644 index 0000000000..9dd52e9503 --- /dev/null +++ b/samchon-framework/samchon-framework.d.ts @@ -0,0 +1,2710 @@ +// Type definitions for Samchon Framework v1.1.0 +// Project: https://github.com/samchon/framework +// Definitions by: Jeongho Nam +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// ------------------------------------------------------------------------------------ +// In Samchon Framework, merging multiple 'ts' files to a module is not possible yet. +// Instead of using "import" instruction, use such trick: +// +// +// declare var global: any; +// declare var require: Function; +// +// global["samchon"] = require("samchon-framework"); +// let invoke: samchon.protocol.Invoke = new samchon.protocol.Invoke("setValue", 3); +// +// +// Those declaration of global and require can be substituted by using "node.d.ts" +// ------------------------------------------------------------------------------------ + +/// + +/** + * Samchon Framework, A SDN framework. + * + * @author Jeongho Nam + */ +declare namespace samchon { +} +declare namespace samchon.library { +} +declare namespace samchon.collection { +} +declare namespace samchon.protocol { +} +declare namespace samchon.protocol.service { +} +declare namespace samchon.protocol.master { +} +declare namespace samchon.protocol.slave { +} +declare namespace samchon.library { + /** + *

XML is a class representing a tree structued xml objects.

+ *

The XML class provides methods and properties for working with XML objects.

+ * + *

The XML class (along with the XMLList and Namespace) implements + * the powerful XML-handling standard defined in ECMAScript for XML (E4X) specification.

+ * + *

XML class has a recursive, hierarchical relationship.

+ * + *

Relationships between XML and XMLList

+ *
    + *
  • XML contains XMLList from dictionary of XMLList.
  • + *
  • XMLList contains XML from vector of XML.
  • + *
+ * + *

Note

+ *

Do not abuse values for expressing member variables.

+ * + * + * + * + * + * + * + * + * + * + *
Standard UsageNon-standard usage abusing value
+ * <memberList>
+ *      <member id='jhnam88' name='Jeongho+Nam' birthdate='1988-03-11' />
+ *      <member id='master' name='Administartor' birthdate='2011-07-28' />
+ * </memberList> + *
+ * <member>
+ *      <id>jhnam88</id>
+ *      <name>Jeongho+Nam</name>
+ *      <birthdate>1988-03-11</birthdate>
+ * </member> + *
+ * + * @author Jeongho Nam + */ + class XML extends std.HashMap { + /** + *

Tag name of the XML.

+ * + *
    + *
  • \<tag label='property' /\>: tag => \"tag\"
  • + *
  • \<price high='1500' low='1300' open='1450' close='1320' /\>: tag => \"price\"
  • + *
+ */ + private tag; + /** + *

Value of the XML.

+ * + *
    + *
  • \26\: value => 26
  • + *
  • \: value => null
  • + *
+ */ + private value; + /** + *

Properties belongs to the XML.

+ *

A Dictionary of properties accessing each property by its key.

+ * + *
    + *
  • \high='1500' low='1300' open='1450' close='1320' /\>: + * propertyMap => {{\"high\": 1500}, {\"low\": 1300}, {\"open\": 1450}, {\"close\", 1320}}
  • + *
  • \id='jhnam88' name='Jeongho+Nam' comment='Hello.+My+name+is+Jeongho+Nam' \>: + * propertyMap => {{\"id\", \"jhnam88\"}, {\"name\", \"Jeongho Nam \"}, + * {\"comment\", \"Hello. My name is Jeongho Nam \"}}
  • + *
+ */ + private properties; + /** + *

Default Constructor.

+ * + *

If the string parameter is not omitted, constructs its tag, value and + * properties by parsing the string. If there's children, then construct the + * children XML, XMLList objects, too.

+ * + * @param str A string to be parsed + */ + constructor(str?: string); + /** + *

Construct XML objects by parsing a string.

+ */ + private construct(str); + /** + *

Parse and fetch a tag.

+ */ + private parseTag(str); + /** + *

Parse and fetch properties.

+ */ + private parseProperty(str); + /** + *

Parse and fetch a value.

+ */ + private parseValue(str); + /** + *

Parse and construct children XML objects.

+ */ + private parseChildren(str); + /** + *

Get tag.

+ */ + getTag(): string; + /** + *

Get value.

+ */ + getValue(): any; + /** + *

Test wheter a property exists or not.

+ */ + hasProperty(key: string): boolean; + /** + *

Get property by its key.

+ */ + getProperty(key: string): any; + getPropertyMap(): std.HashMap; + /** + *

Set tag (identifier) of the XML.

+ */ + setTag(str: string): void; + /** + *

Set value of the XML.

+ * + *

Do not abuse values for expressing member variables.

+ * + * + * + * + * + * + * + * + * + *
Standard UsageNon-standard usage abusing value
+ * \\n + *     \\n + *     \\n + * \ + * + * \\n + * \jhnam88\\n + * \Jeongho+Nam\\n + * \1988-03-11\\n + * \ + *
+ * + * @param val A value to set + */ + setValue(str: any): void; + /** + *

Set a property with its key.

+ */ + setProperty(key: string, value: any): void; + /** + *

Erase a property by its key.

+ * + * @param key The key of the property to erase + * @throw exception out of range + */ + eraseProperty(key: string): void; + push(...args: std.Pair[]): number; + push(...args: [L, U][]): number; + push(...xmls: XML[]): number; + push(...xmlLists: XMLList[]): number; + addAllProperties(xml: XML): void; + clearProperties(): void; + private calcMinIndex(...args); + /** + *

Decode a value.

+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
EncodedDecoded
\&\&
\<\<
\>\>
+ * + * @return A decoded string represents a value + */ + static decodeValue(str: string): string; + /** + *

Encode a value.

+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
OriginalEncoded
\&\&
\<\<
\>\>
+ * + * @return A encoded string represents a value + */ + static encodeValue(str: string): string; + /** + *

Decode a property.

+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
EncodedDecoded
\&\&
\<\<
\>\>
"\"
''
'
'\\t
\\n
\\r
+ * + * @return A decoded string represents a property + */ + static decodeProperty(str: string): string; + /** + *

Decode a property.

+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
OriginalEncoded
\&\&
\<\<
\>\>
\""
''
'
\\t'
\\n
\\r
+ * + * @return A encoded string represents a property + */ + static encodeProperty(str: string): string; + /** + *

Convert the XML to a string.

+ */ + toString(level?: number): string; + /** + *

Convert the XML to HTML string.

+ */ + toHTML(level?: number): string; + } + /** + *

List of XML(s) having same tag.

+ * + * @author Jeongho Nam + */ + class XMLList extends std.Vector { + /** + *

Default Constructor.

+ */ + constructor(); + getTag(): string; + /** + *

Convert XMLList to string.

+ * + * @param level Level(depth) of the XMLList. + */ + toString(level?: number): string; + /** + *

Convert XMLList to HTML string.

+ * + * @param level Level(depth) of the XMLList. + */ + toHTML(level?: number): string; + } +} +declare namespace samchon.collection { + /** + * A {@link Vector} who can detect element I/O events. + * + * @author Jeongho Nam + */ + class ArrayCollection extends std.Vector implements ICollection { + private insert_handler_; + private erase_handler_; + private event_dispatcher_; + /** + * @inheritdoc + */ + set_insert_handler(listener: CollectionHandler): void; + /** + * @inheritdoc + */ + set_erase_handler(listener: CollectionHandler): void; + /** + * @inheritdoc + */ + get_insert_handler(): CollectionHandler; + /** + * @inheritdoc + */ + get_erase_handler(): CollectionHandler; + /** + * @inheritdoc + */ + push(...items: U[]): 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; + /** + * @inheritdoc + */ + pop_back(): void; + /** + * @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: Event): boolean; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: EventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: EventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + addEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: EventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: EventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: "insert" | "erase", 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.protocol { + /** + *

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).

+ * + * @author Jeongho Nam + */ + abstract class Entity implements IEntity { + /** + *

Default Constructor.

+ */ + constructor(); + construct(xml: library.XML): void; + key(): any; + abstract TAG(): string; + toXML(): library.XML; + } +} +declare namespace samchon.library { + /** + * An event class. + * + *
    + *
  • Comments from - https://developer.mozilla.org/en-US/docs/Web/API/Event/
  • + *
+ * + * @author Jeongho Nam + */ + class BasicEvent implements Event { + NONE: number; + CAPTURING_PHASE: number; + AT_TARGET: number; + BUBBLING_PHASE: number; + private type_; + private target_; + 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 + */ + preventDefault(): void; + /** + * @inheritdoc + */ + stopImmediatePropagation(): void; + /** + * @inheritdoc + */ + stopPropagation(): void; + /** + * @inheritdoc + */ + type: string; + /** + * @inheritdoc + */ + target: IEventDispatcher; + /** + * @inheritdoc + */ + currentTarget: IEventDispatcher; + /** + * @inheritdoc + */ + isTrusted: boolean; + /** + * @inheritdoc + */ + bubbles: boolean; + /** + * @inheritdoc + */ + cancelable: boolean; + /** + * @inheritdoc + */ + eventPhase: number; + /** + * @inheritdoc + */ + defaultPrevented: boolean; + /** + * @inheritdoc + */ + srcElement: Element; + /** + * @inheritdoc + */ + cancelBubble: boolean; + /** + * @inheritdoc + */ + timeStamp: number; + /** + * Don't know what it is. + */ + returnValue: boolean; + } + class ProgressEvent extends BasicEvent { + static PROGRESS: string; + protected numerator_: number; + protected denominator_: number; + constructor(type: string, numerator: number, denominator: number); + numerator: number; + denominator: number; + } +} +declare namespace samchon.collection { + interface CollectionEventListener extends EventListener { + (event: CollectionEvent): void; + } + class CollectionEvent extends library.BasicEvent { + static INSERT: string; + static ERASE: string; + private first_; + private last_; + constructor(type: string, first: std.Iterator, last: std.Iterator); + container: ICollection; + first: std.Iterator; + last: std.Iterator; + } +} +declare namespace samchon.collection { + /** + * A {@link Deque} who can detect element I/O events. + * + * @author Jeongho Nam + */ + class DequeCollection extends std.Deque implements ICollection { + private insert_handler_; + private erase_handler_; + private event_dispatcher_; + /** + * @inheritdoc + */ + set_insert_handler(listener: CollectionHandler): void; + /** + * @inheritdoc + */ + set_erase_handler(listener: CollectionHandler): void; + /** + * @inheritdoc + */ + get_insert_handler(): CollectionHandler; + /** + * @inheritdoc + */ + get_erase_handler(): CollectionHandler; + /** + * @inheritdoc + */ + push(...items: U[]): 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: Event): boolean; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: EventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: EventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + addEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: EventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: EventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + } +} +declare namespace samchon.collection { + /** + * A {@link HashMap} who can detect element I/O events. + * + * @author Jeongho Nam + */ + class HashMapCollection extends std.HashMap implements ICollection> { + private insert_handler_; + private erase_handler_; + private event_dispatcher_; + /** + * @inheritdoc + */ + get_insert_handler(): MapCollectionHandler; + /** + * @inheritdoc + */ + get_erase_handler(): MapCollectionHandler; + /** + * @inheritdoc + */ + set_insert_handler(listener: MapCollectionHandler): void; + /** + * @inheritdoc + */ + set_erase_handler(listener: MapCollectionHandler): void; + /** + * @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: Event): boolean; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: EventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: EventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + addEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: EventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: EventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + } + /** + * A {@link HashMultiMap} who can detect element I/O events. + * + * @author Jeongho Nam + */ + class HashMultiMapCollection extends std.HashMap implements ICollection> { + private insert_handler_; + private erase_handler_; + private event_dispatcher_; + /** + * @inheritdoc + */ + get_insert_handler(): MapCollectionHandler; + /** + * @inheritdoc + */ + get_erase_handler(): MapCollectionHandler; + /** + * @inheritdoc + */ + set_insert_handler(listener: MapCollectionHandler): void; + /** + * @inheritdoc + */ + set_erase_handler(listener: MapCollectionHandler): void; + /** + * @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: Event): boolean; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: EventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: EventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + addEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: EventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: EventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + } +} +declare namespace samchon.collection { + /** + * A {@link HashSet} who can detect element I/O events. + * + * @author Jeongho Nam + */ + class HashSetCollection extends std.TreeSet implements ICollection { + private insert_handler_; + private erase_handler_; + private event_dispatcher_; + /** + * @inheritdoc + */ + set_insert_handler(listener: CollectionHandler): void; + /** + * @inheritdoc + */ + set_erase_handler(listener: CollectionHandler): void; + /** + * @inheritdoc + */ + get_insert_handler(): CollectionHandler; + /** + * @inheritdoc + */ + get_erase_handler(): CollectionHandler; + /** + * @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: Event): boolean; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: EventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: EventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + addEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: EventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: EventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + } + class HashMultiSetCollection extends std.TreeMultiSet implements ICollection { + private insert_handler_; + private erase_handler_; + private event_dispatcher_; + /** + * @inheritdoc + */ + set_insert_handler(listener: CollectionHandler): void; + /** + * @inheritdoc + */ + set_erase_handler(listener: CollectionHandler): void; + /** + * @inheritdoc + */ + get_insert_handler(): CollectionHandler; + /** + * @inheritdoc + */ + get_erase_handler(): CollectionHandler; + /** + * @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: Event): boolean; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: EventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: EventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + addEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: EventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: EventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + } +} +declare namespace samchon.collection { + interface CollectionHandler { + (first: std.Iterator, last: std.Iterator): void; + } + interface MapCollectionHandler extends CollectionHandler> { + (first: std.MapIterator, last: std.MapIterator): void; + } + /** + * An interface for {@link IContainer containers} who can detect element I/O events. + * + * @author Jeongho Nam + */ + interface ICollection extends std.base.IContainer, library.IEventDispatcher { + get_insert_handler(): CollectionHandler; + get_erase_handler(): CollectionHandler; + set_insert_handler(listener: CollectionHandler): any; + set_erase_handler(listener: CollectionHandler): any; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: EventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: EventListener, thisArg: Object): void; + addEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; + addEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: EventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: EventListener, thisArg: Object): void; + removeEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; + removeEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + } +} +declare namespace samchon.collection { + /** + * A {@link List} who can detect element I/O events. + * + * @author Jeongho Nam + */ + class ListCollection extends std.List implements ICollection { + private insert_handler_; + private erase_handler_; + private event_dispatcher_; + /** + * @inheritdoc + */ + set_insert_handler(listener: CollectionHandler): void; + /** + * @inheritdoc + */ + set_erase_handler(listener: CollectionHandler): void; + /** + * @inheritdoc + */ + get_insert_handler(): CollectionHandler; + /** + * @inheritdoc + */ + get_erase_handler(): CollectionHandler; + /** + * @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: Event): boolean; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: EventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: EventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + addEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: EventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: EventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + } +} +declare namespace samchon.collection { + /** + * A {@link TreeMap} who can detect element I/O events. + * + * @author Jeongho Nam + */ + class TreeMapCollection extends std.HashMap implements ICollection> { + private insert_handler_; + private erase_handler_; + private event_dispatcher_; + /** + * @inheritdoc + */ + get_insert_handler(): MapCollectionHandler; + /** + * @inheritdoc + */ + get_erase_handler(): MapCollectionHandler; + /** + * @inheritdoc + */ + set_insert_handler(listener: MapCollectionHandler): void; + /** + * @inheritdoc + */ + set_erase_handler(listener: MapCollectionHandler): void; + /** + * @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: Event): boolean; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: EventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: EventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + addEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: EventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: EventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + } + /** + * A {@link TreeMultiMap} who can detect element I/O events. + * + * @author Jeongho Nam + */ + class TreeMultiMapCollection extends std.HashMap implements ICollection> { + private insert_handler_; + private erase_handler_; + private event_dispatcher_; + /** + * @inheritdoc + */ + get_insert_handler(): MapCollectionHandler; + /** + * @inheritdoc + */ + get_erase_handler(): MapCollectionHandler; + /** + * @inheritdoc + */ + set_insert_handler(listener: MapCollectionHandler): void; + /** + * @inheritdoc + */ + set_erase_handler(listener: MapCollectionHandler): void; + /** + * @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: Event): boolean; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: EventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: EventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + addEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: EventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: EventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + } +} +declare namespace samchon.collection { + /** + * A {@link TreeMap} who can detect element I/O events. + * + * @author Jeongho Nam + */ + class TreeSetCollection extends std.TreeSet implements ICollection { + private insert_handler_; + private erase_handler_; + private event_dispatcher_; + /** + * @inheritdoc + */ + set_insert_handler(listener: CollectionHandler): void; + /** + * @inheritdoc + */ + set_erase_handler(listener: CollectionHandler): void; + /** + * @inheritdoc + */ + get_insert_handler(): CollectionHandler; + /** + * @inheritdoc + */ + get_erase_handler(): CollectionHandler; + /** + * @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: Event): boolean; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: EventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: EventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + addEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: EventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: EventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + } + /** + * A {@link TreeMultiSet} who can detect element I/O events. + * + * @author Jeongho Nam + */ + class TreeMultiSetCollection extends std.TreeMultiSet implements ICollection { + private insert_handler_; + private erase_handler_; + private event_dispatcher_; + /** + * @inheritdoc + */ + set_insert_handler(listener: CollectionHandler): void; + /** + * @inheritdoc + */ + set_erase_handler(listener: CollectionHandler): void; + /** + * @inheritdoc + */ + get_insert_handler(): CollectionHandler; + /** + * @inheritdoc + */ + get_erase_handler(): CollectionHandler; + /** + * @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: Event): boolean; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: EventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: EventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + addEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + addEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: EventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: EventListener, thisArg: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: "insert" | "erase", listener: CollectionEventListener): void; + /** + * @inheritdoc + */ + removeEventListener(type: "insert" | "erase", listener: CollectionEventListener, thisArg: Object): void; + } +} +declare namespace samchon.library { + /** + *

Case generator.

+ * + *

CaseGenerator is an abstract case generator using like a matrix.

+ *
    + *
  • nTTr(n^r) -> CombinedPermutationGenerator
  • + *
  • nPr -> PermutationGenerator
  • + *
  • n! -> 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): Array; + } + /** + *

A combined-permutation case generator.

+ *

nTTr

+ * + * @inheritdoc + * @author Jeongho Nam + */ + class CombinedPermutationGenerator extends CaseGenerator { + /** + *

An array using for dividing each element index.

+ */ + private dividerArray; + /** + *

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): Array; + } + /** + *

A permutation case generator.

+ *

nPr

+ * + * @author Jeongho Nam + * @inheritdoc + */ + 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): Array; + } + class FactorialGenerator extends PermuationGenerator { + /** + * Construct from factorial size N. + * + * @param n Factoria size N. + */ + constructor(n: number); + } +} +declare namespace samchon.library { + /** + *

The IEventDispatcher interface defines methods for adding or removing event listeners, checks + * whether specific types of event listeners are registered, and dispatches events.

+ * + *

Event targets are an important part of the Flash�� Player and Adobe AIR event model. The event + * target serves as the focal point for how events flow through the display list hierarchy. When an + * event such as a mouse click or a keypress 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 EventDispatcher. If this is impossible (that is, if the class is already extending another + * class), you can instead implement the IEventDispatcher interface, create an EventDispatcher member, + * and write simple hooks to route calls into the aggregated EventDispatcher.

+ * + *
    + *
  • Made by AS3 - http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/events/IEventDispatcher.html + *
+ * + * @see EventDispatcher + * @author Migrated by Jeongho Nam + */ + interface IEventDispatcher { + /** + *

Checks whether the EventDispatcher object has any listeners registered for a specific type + * of event. This allows you to determine where an 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 willTrigger().

+ * + *

The difference between hasEventListener() and willTrigger() is that hasEventListener() + * examines only the object to which it belongs, whereas 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 EventDispatcher object upon which the dispatchEvent() method is called.

+ * + * @param event The Event 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: BasicEvent): boolean; + /** + *

Registers an event listener object with an 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 addEventListener(). To change a listener's priority, you must first call + * 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 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 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 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 EventDispatcher instance does not copy the event listeners attached to it. (If + * your newly created node needs an event listener, you must attach the listener after creating + * the node.) However, if you move an 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: EventListener, thisArg: Object): void; + /** + * Removes a listener from the EventDispatcher object. If there is no matching listener registered + * with the 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: EventListener, thisArg: Object): void; + } + /** + *

Registers an event listener object with an 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 addEventListener(). To change a listener's priority, you must first call + * removeListener(). Then you can register the listener again with the new priority level.

+ * + * Keep in mind that after the listener is registered, subsequent calls to 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 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 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 EventDispatcher instance does not copy the event listeners attached to it. (If your + * newly created node needs an event listener, you must attach the listener after creating the + * node.) However, if you move an 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 being processed on + * this node, the event listener is not triggered during the current phase but can 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 registered again for future processing).

+ * + *
    + *
  • Made by AS3 - http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/events/EventDispatcher.html + *
+ * + * @author Migrated by Jeongho Nam + */ + class EventDispatcher implements IEventDispatcher { + /** + * The origin object who issuing events. + */ + protected target: IEventDispatcher; + /** + * Container of listeners. + */ + protected listeners: std.HashMap>>; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from the origin event dispatcher. + * + * @param target The origin object who issuing events. + */ + constructor(target: IEventDispatcher); + /** + * @inheritdoc + */ + hasEventListener(type: string): boolean; + /** + * @inheritdoc + */ + dispatchEvent(event: Event): boolean; + /** + * @inheritdoc + */ + addEventListener(type: string, listener: EventListener, thisArg?: Object): void; + /** + * @inheritdoc + */ + removeEventListener(type: string, listener: EventListener, thisArg?: Object): void; + } +} +declare namespace samchon.library { + /** + *

A utility class supporting static methods of string.

+ * + * @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, ?) )

+ * + * + let str = 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; + /** + *

Get a tabbed string by specified size.

+ */ + static tab(size: number): string; + /** + *

Get a tabbed HTLM string by specified size.

+ */ + static htmlTab(size: number): string; + /** + * Replace all HTML spaces to a literal space. + * + * @param str Target string to replace. + */ + static removeHTMLSpaces(str: string): string; + } +} +declare namespace samchon.protocol { + /** + * @author Jeongho Nam + */ + abstract class EntityArray extends std.Vector { + /** + * Default Constructor. + */ + constructor(); + /** + *

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.

+ * + * @inheritdoc + */ + 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. + */ + protected abstract createChild(xml: library.XML): Ety; + /** + * @inheritdoc + */ + key(): any; + /** + *

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: string): Ety; + /** + * @inheritdoc + */ + abstract TAG(): string; + /** + *

A tag name of children objects.

+ */ + abstract 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.

+ * + * @inheritdoc + */ + toXML(): library.XML; + } +} +declare namespace samchon.protocol { + /** + *

A network driver for an external system.

+ * + *

ExternalSystem is a boundary class interacting with an external system by network communication. + * Also, ExternalSystem is an abstract class that a network role, which one is server and which one is + * client, is not determined yet.

+ * + *

The ExternalSystem has ExternalSystemRole(s) groupped methods, handling Invoke message + * interacting with the external system, by subject or unit of a moudle. The ExternalSystemRole is + * categorized in a 'control'.

+ * + *

Note

+ *

The ExternalSystem class takes a role of interaction with external system in network level. + * However, within a framework of Samchon Framework, a boundary class like the ExternalSystem is + * not such important. You can find some evidence in a relationship between ExternalSystemArray, + * ExternalSystem and ExternalSystemRole.

+ * + *

Of course, the ExternalSystemRole is belonged to an ExternalSystem. However, if you + * access an ExternalSystemRole from an ExternalSystemArray directly, not passing by a belonged + * ExternalSystem, and send an Invoke message even you're not knowing which ExternalSystem is + * related in, it's called "Proxy pattern". + * + *

Like the explanation of "Proxy pattern", you can utilize an ExternalSystemRole as a proxy + * of an ExternalSystem. With the pattern, you can only concentrate on ExternalSystemRole itself, + * what to do with Invoke message, irrespective of the ExternalSystemRole is belonged to which + * ExternalSystem.

+ * + * @author Jeongho Nam + */ + abstract class ExternalSystem extends EntityArray implements IProtocol { + /** + *

A driver for interacting with (real, physical) external system.

+ */ + protected driver: ServerConnector; + /** + *

A name can identify an external system.

+ * + *

The name must be unique in ExternalSystemArray.

+ */ + protected name: string; + /** + *

An ip address of an external system.

+ */ + protected ip: string; + /** + *

A port number of an external system.

+ */ + protected port: number; + /** + *

Default Constructor.

+ */ + constructor(); + /** + *

Start interaction.

+ *

An abstract method starting interaction with an external system.

+ * + *

If an external systems are a server, starts connection and listening Inovoke message, + * else clients, just starts listening only. You also can addict your own procudures of starting + * the driver, but if you directly override method of abstract ExternalSystem, be careful about + * virtual inheritance.

+ */ + start(): void; + key(): any; + /** + *

Get name.

+ */ + getName(): string; + /** + *

Get ip address of the external system.

+ */ + getIP(): string; + /** + *

Get port number of the external system.

+ */ + getPort(): number; + sendData(invoke: Invoke): void; + replyData(invoke: Invoke): void; + TAG(): string; + CHILD_TAG(): string; + } +} +declare namespace samchon.protocol { + /** + *

An array of ExternalSystem(s).

+ * + *

ExternalSystemArray is an abstract class containing and managing external system drivers.

+ * + *

Also, ExternalSystemArray can access to ExternalSystemRole(s) directly. With the method, you + * can use an ExternalSystemRole as "logical proxy" of an ExternalSystem. Of course, the + * ExternalSystemRole is belonged to an ExternalSystem. However, if you access an ExternalSystemRole + * from an ExternalSystemArray directly, not passing by a belonged ExternalSystem, and send an Invoke + * message even you're not knowing which ExternalSystem is related in, the ExternalSystemRole acted + * a role of proxy.

+ * + *

It's called as "Proxy pattern". With the pattern, you can only concentrate on + * ExternalSystemRole itself, what to do with Invoke message, irrespective of the ExternalSystemRole + * is belonged to which ExternalSystem.

+ * + *
    + *
  • ExternalSystemArray::getRole("something")->sendData(invoke);
  • + *
+ * + * @author Jeongho Nam + */ + abstract class ExternalSystemArray extends EntityArray implements IProtocol { + /** + * Default Constructor. + */ + constructor(); + /** + *

Start interaction.

+ *

An abstract method starting interaction with external systems.

+ * + *

If external systems are servers, starts connection to them, else clients, opens a server + * and accepts the external systems. You can addict your own procudures of starting drivers, but + * if you directly override method of abstract ExternalSystemArray, be careful about virtual + * inheritance.

+ */ + start(): void; + /** + *

Test whether has a role.

+ * + * @param name Name of an ExternalSystemRole. + * @return Whether has or not. + */ + hasRole(key: string): boolean; + /** + *

Get a role.

+ * + * @param name Name of an ExternalSystemRole + * @return A shared pointer of specialized role + */ + getRole(key: string): ExternalSystemRole; + sendData(invoke: Invoke): void; + replyData(invoke: Invoke): void; + TAG(): string; + CHILD_TAG(): string; + } +} +declare namespace samchon.protocol { + /** + *

A role belongs to an external system.

+ * + *

ExternalSystemRole is a 'control' class groupping methods, handling Invoke messages + * interacting with an external system that the ExternalSystemRole is belonged to, by a subject or + * unit of a module.

+ * + *

ExternalSystemRole can be a "logical proxy" for an ExternalSystem which is containing the + * ExternalSystemRole. Of course, the ExternalSystemRole is belonged to an ExternalSystem. However, + * if you access an ExternalSystemRole from an ExternalSystemArray directly, not passing by a + * belonged ExternalSystem, and send an Invoke message even you're not knowing which ExternalSystem + * is related in, the ExternalSystemRole acted a role of proxy.

+ * + *

It's called as "Proxy pattern". With the pattern, you can only concentrate on + * ExternalSystemRole itself, what to do with Invoke message, irrespective of the ExternalSystemRole + * is belonged to which ExternalSystem.

+ * + * @author Jeongho Nam + */ + class ExternalSystemRole extends Entity implements IProtocol { + /** + *

A driver of external system containing the ExternalSystemRole.

+ */ + protected system: ExternalSystem; + /** + *

A name representing the role.

+ */ + protected name: string; + protected sendListeners: std.HashSet; + /** + *

Construct from external system driver.

+ * + * @param system A driver of external system the ExternalSystemRole is belonged to. + */ + constructor(system: ExternalSystem); + construct(xml: library.XML): void; + getName(): string; + hasSendListener(key: string): boolean; + sendData(invoke: Invoke): void; + replyData(invoke: Invoke): void; + TAG(): string; + toXML(): library.XML; + } +} +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).

+ * + * @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): any; + /** + *

Get a key that can identify the Entity uniquely.

+ * + *

If identifier of the Entity is not atomic value, returns a string or paired object + * that can represents the composite identifier.

+ */ + key(): any; + /** + *

A tag name when represented by XML.

+ * + *
    + *
  • <TAG {...properties} />
  • + *
+ */ + 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
+ * <memberList>
+ * <member id='jhnam88' name='Jeongho+Nam' birthdate='1988-03-11' />
+ <member id='master' name='Administartor' birthdate='2011-07-28' />
+</memberList> + *
+ * <member> + * <id>jhnam88</id> + * <name>Jeongho+Nam<name> + * <birthdate>1988-03-11</birthdate> + * </member> + *
+ * + * @return An XML object representing the Entity. + */ + toXML(): library.XML; + } +} +declare namespace samchon.protocol { + /** + *

An interface for Invoke message chain.

+ * + *

IProtocol is an interface for Invoke message, which is standard message of network I/O + * in Samchon Framework, chain. The IProtocol interface is used to network drivers and some + * classes which are in a relationship of chain of responsibility with those network drivers.

+ * + *

In Samchon Framework, server side, IProtocol is one of the basic 3 + 1 components that + * can make any type of network system in Samchon Framework with IServer and IClient. Following + * the "chain of responsibility" pa1ttern, looking around classes in Samchon Framework, you + * can see all related classes with network I/O are implemented from the IProtocol.

+ * + * @see Invoke + * @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 Replied invoke message + */ + sendData(invoke: Invoke): void; + } +} +declare namespace samchon.protocol { + /** + *

Standard message of network I/O.

+ *

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 3 + 1 componenets + * (IProtocol, IServer and IClient + ServerConnector), by implemens or inherits them, like designing + * classes of S/W architecture.

+ * + * @see IProtocol + * @author Jeongho Nam + */ + class Invoke extends EntityArray { + /** + *

Listener, represent function's name.

+ */ + protected listener: string; + constructor(listener: string); + /** + * Copy Constructor. + * + * @param invoke + */ + constructor(invoke: Invoke); + constructor(xml: library.XML); + constructor(listener: string, begin: std.VectorIterator, end: std.VectorIterator); + constructor(listener: string, ...parameters: any[]); + /** + * @inheritdoc + */ + protected 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.

+ */ + apply(obj: IProtocol): boolean; + /** + * @inheritdoc + */ + TAG(): string; + /** + * @inheritdoc + */ + CHILD_TAG(): string; + } +} +declare namespace samchon.protocol { + /** + *

A history of an Invoke message.

+ * + *

InvokeHistory is a class for reporting history log of an Invoke message with elapsed time + * from a slave to its master.

+ * + *

With the elapsed time, consumed time for a process of handling the Invoke message, + * InvokeHistory is reported to the master. The master utilizies the elapsed time to estimating + * performances of each slave system. With the estimated performan index, master retrives the + * optimal solution of distributing processes.

+ * + * @author Jeongho Nam + */ + class InvokeHistory extends Entity { + /** + *

An identifier.

+ */ + protected uid: number; + /** + *

A listener of the Invoke message.

+ * + *

InvokeHistory does not archive entire data of an Invoke message. InvokeHistory only + * archives its listener. The first, formal reason is to save space, avoid wasting spaces.

+ * + *

The second, complicate reason is on an aspect of which systems are using the + * InvokeHistory class. InvokeHistory is designed to let slave reports to master elapsed time + * of a process used to handling the Invoke message. If you want to archive entire history log + * of Invoke messages, then the subject should be master, not the slave using InvokeHistory + * classes.

+ */ + protected listener: string; + /** + *

Start time of the history.

+ * + *

Means start time of a process handling the Invoke message. The start time not only + * has ordinary arguments represented Datetime (year to seconds), but also has very precise + * values under seconds, which is expressed as nano seconds (10^-9).

+ * + *

The precise start time will be used to calculate elapsed time with end time.

+ */ + protected startTime: Date; + /** + *

End time of the history.

+ * + * @details + *

Means end time of a process handling the Invoke message. The end time not only + * has ordinary arguments represented Datetime (year to seconds), but also has very precise + * values under seconds, which is expressed as nano seconds (10^-9).

+ * + *

The precise end time will be used to calculate elapsed time with start time.

+ */ + protected endTime: Date; + /** + *

Construct from an Invoke message.

+ * + *

InvokeHistory does not archive entire Invoke message, only archives its listener.

+ * + * @param invoke A message to archive its history log + */ + constructor(invoke: Invoke); + /** + *

Notify end of the process.

+ * + *

Notifies end of a process handling the matched Invoke message to InvokeHistory.

+ *

InvokeHistory archives the end datetime and calculates elapsed time as nanoseconds.

+ */ + notifyEnd(): void; + TAG(): string; + toXML(): library.XML; + /** + *

Get an Invoke message.

+ * + *

Returns an Invoke message to report to a master that how much time was elapsed on a + * process handling the Invoke message. In master, those reports are used to estimate + * performance of each slave system.

+ * + * @return An Invoke message to report master. + */ + toInvoke(): Invoke; + } +} +declare namespace samchon.protocol { + /** + * A parameter belongs to an Invoke. + * + * @see Invoke + * @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: any; + constructor(); + constructor(name: string, val: any); + constructor(name: string, type: string, val: any); + construct(xml: library.XML): void; + key(): any; + /** + * Get name. + */ + getName(): string; + /** + * Get type. + */ + getType(): string; + /** + * Get value. + */ + getValue(): any; + TAG(): string; + toXML(): library.XML; + } +} +declare namespace samchon.protocol { + /** + *

A server connector for a physical client.

+ * + *

ServerConnector is a class for a physical client connecting a server. If you want to connect + * to a server, then implements this ServerConnector and just override some methods like + * getIP(), getPort() and replyData(). That's all.

+ * + *

In Samchon Framework, package protocol, There are basic 3 + 1 components that can make any + * type of network system in Samchon Framework. The basic 3 components are IProtocol, IServer and + * IClient. The last, surplus one is the ServerConnector. Looking around classes in + * Samchon Framework, especially module master and slave which are designed for realizing + * distributed processing systems and parallel processing systems, physical client classes are all + * derived from this ServerConnector.

+ * + * + * + * @author Jeongho Nam + */ + class ServerConnector implements IProtocol { + /** + *

A parent object who listens and sends Invoke message.

+ * + *
    + *
  • ServerConnector.replyData(Invoke) -> parent.replyData(Invoke)
  • + *
+ */ + private parent; + /** + *

A socket for network I/O.

+ */ + private socket; + /** + *

Unused string from a server.

+ */ + private str; + /** + *

An open-event listener.

+ */ + onopen: Function; + /** + *

Constructor with parent.

+ */ + constructor(parent: IProtocol); + /** + *

Connects to a cloud server with specified host and port.

+ * + *

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. + * + * @throws IOError + * No host was specified and the connection failed. + * @throws SecurityError + * This error occurs in SWF content for the following reasons: + * Local untrusted SWF files may not communicate with the Internet. You can work around + * this limitation by reclassifying the file as local-with-networking or as trusted. + */ + connect(ip: string, port: number): void; + /** + *

Send data to the server.

+ */ + sendData(invoke: Invoke): void; + /** + *

Shift responsiblity of handling message to parent.

+ */ + replyData(invoke: Invoke): void; + private handleConnect(event); + /** + *

Handling replied message.

+ */ + private handleReply(event); + } +} +declare namespace samchon.protocol.service { + /** + *

An application, the top class in JS-UI.

+ * + *

The Application is separated to three part, TopMenu, Movie and ServerConnector.

+ *
    + *
  • TopMenu: Menu on the top. It's not an essential component.
  • + *
  • Movie: Correspond with Service in Server. Movie has domain UI components(Movie) for the matched Service.
  • + *
  • ServerConnector: The socket connecting to the Server.
  • + *
+ * + *

The Application and its UI-layout is not fixed, essential component for Samchon Framework in Flex, + * so it's okay to do not use the provided Application and make your custom Application. + * But the custom Application, your own, has to contain the Movie and keep the construction routine.

+ * + *

+ * + *

THE CONSTRUCTION ROUTINE

+ *
    + *
  • Socket Connection
  • + *
      + *
    • Connect to the CPP-Server
    • + *
    + *
  • Fetch authority
  • + *
      + *
    • Send a request to fetching authority
    • + *
    • The window can be navigated to other page by the authority
    • + *
    + *
  • Construct Movie
  • + *
      + *
    • Determine a Movie by URLVariables::movie and construct it
    • + *
    + *
  • All the routines are done
  • + *
+ * + * @author Jeongho Nam + */ + class Application implements IProtocol { + /** + *

Invoke Socket.

+ */ + protected socket: ServerConnector; + /** + *

A movie.

+ */ + protected movie: Movie; + /** + *

Construct from arguments.

+ * + * @param movie A movie represents a service. + * @param ip An ip address of cloud server to connect. + * @param port A port number of cloud server to connect. + */ + constructor(movie: Movie, ip: string, port: number); + private handleConnect(event); + /** + *

Handle replied message or shift the responsibility.

+ */ + replyData(invoke: Invoke): void; + /** + *

Send a data to server.

+ */ + sendData(invoke: Invoke): void; + } +} +declare namespace samchon.protocol.service { + /** + * A movie belonged to an Application. + */ + class Movie implements IProtocol { + /** + *

An application the movie is belonged to + */ + protected application: Application; + /** + * Handle replied data. + */ + replyData(invoke: Invoke): void; + /** + * Send data to server. + */ + sendData(invoke: Invoke): void; + } +} +declare namespace samchon.protocol.service { +} +declare namespace samchon.protocol.slave { + /** + * @brief A slave system. + * + * @details + *

SlaveSystem, literally, means a slave system belongs to a maste system.

+ * + *

The SlaveSystem class is used in opposite side system of master::DistributedSystem + * and master::ParallelSystem and reports elapsed time of each commmand (by Invoke message) + * for estimation of its performance.

+ * + * @inheritdoc + * @author Jeongho Nam + */ + abstract class SlaveSystem extends ExternalSystem { + /** + *

Default Constructor.

+ */ + constructor(); + /** + * @inheritdoc + */ + replyData(invoke: Invoke): void; + } +} diff --git a/samchon-library/samchon-library-tests.ts b/samchon-library/samchon-library-tests.ts new file mode 100644 index 0000000000..a2b0656d5f --- /dev/null +++ b/samchon-library/samchon-library-tests.ts @@ -0,0 +1,7 @@ +/// + +declare var global: any; +declare var require: (name: string) => any; + +library = require("samchon-library"); +console.log(library); \ No newline at end of file diff --git a/samchon-library/samchon-library.d.ts b/samchon-library/samchon-library.d.ts new file mode 100644 index 0000000000..3daecf0937 --- /dev/null +++ b/samchon-library/samchon-library.d.ts @@ -0,0 +1,23 @@ +// Type definitions for Samchon Library v0.0.2 +// Project: https://github.com/samchon/framework +// Definitions by: Jeongho Nam +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// ------------------------------------------------------------------------------------ +// In Samchon Collection, merging multiple 'ts' files to a module is not possible yet. +// Instead of using "import" instruction, use such trick: +// +// +// declare var global: any; +// declare var require: Function; +// +// library = require("samchon-library"); +// let xml: library.XML = new library.XML(); +// +// +// Those declaration of global and require can be substituted by using "node.d.ts" +// ------------------------------------------------------------------------------------ + +/// + +declare var library: typeof samchon.library; \ No newline at end of file diff --git a/typescript-stl/typescript-stl.d.ts b/typescript-stl/typescript-stl.d.ts index 659bd89cc2..1286a62084 100644 --- a/typescript-stl/typescript-stl.d.ts +++ b/typescript-stl/typescript-stl.d.ts @@ -1,9 +1,45 @@ -// Type definitions for TypeScript-STL v0.9.4 +// Type definitions for TypeScript-STL v0.9.9 // Project: https://github.com/samchon/stl // Definitions by: Jeongho Nam // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// ------------------------------------------------------------------------------------ +// In TypeScript, merging multiple 'ts' files to a module is not possible yet. +// Instead of using "import" instruction, use such trick: +// +// +// declare var global: any; +// declare var require: Function; +// +// global["std"] = require("typescript-stl"); +// let list: std.List = new std.List(); +// +// +// Those declaration of global and require can be substituted by using "node.d.ts" +// ------------------------------------------------------------------------------------ + +/** + * STL (Standard Template Library) Containers for TypeScript. + * + * @author Jeongho Nam + */ +declare namespace std { +} +/** + * Base classes composing STL in background. + * + * @author Jeongho Nam + */ declare namespace std.base { +} +/** + * Examples for supporting developers who use STL library. + * + * @author Jeongho Nam + */ +declare namespace std.example { +} +declare namespace std { /** *

Bi-directional iterator.

* @@ -16,23 +52,22 @@ declare namespace std.base { *

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/
  • - *
+ *

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

Get iterator to previous element.

*

If current iterator is the first item(equal with {@link IContainer.begin IContainer.begin()}), @@ -58,7 +93,7 @@ declare namespace std.base { /** * Get source */ - get_source(): Container; + get_source(): base.IContainer; /** *

Whether an iterator is equal with the iterator.

* @@ -83,25 +118,221 @@ declare namespace std.base { value: T; abstract swap(obj: Iterator): void; } -} -declare namespace std.base { /** - * A reverse and bi-directional iterator.

+ *

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 extends Iterator { - protected iterator_: Iterator; - constructor(iterator: Iterator); - equal_to(obj: Iterator): boolean; - equal_to(obj: ReverseIterator): boolean; + abstract class ReverseIterator, This extends ReverseIterator> extends Iterator { + protected base_: Base; + constructor(base: Base); + base(): Base; + protected abstract create_neighbor(): This; + value: T; /** * @inheritdoc */ - value: T; - swap(obj: Iterator): void; - swap(obj: ReverseIterator): void; + prev(): This; + /** + * @inheritdoc + */ + next(): This; + /** + * @inheritdoc + */ + advance(n: number): This; + /** + * @inheritdoc + */ + equal_to(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 { /** @@ -135,6 +366,8 @@ declare namespace std { * end, they perform worse than the others, and have less consistent iterators and references than {@link List}s. *

* + *

+ * *

Container properties

*
*
Sequence
@@ -150,15 +383,12 @@ declare namespace std { * *
* - *
    - *
  • Reference: http://www.cplusplus.com/reference/vector/vector/ - *
- * * @param Type of the elements. * + * @reference http://www.cplusplus.com/reference/vector/vector * @author Jeongho Nam */ - class Vector extends Array implements base.IArray { + class Vector extends Array implements base.IArrayContainer { /** * Type definition of {@link Vector}'s {@link VectorIterator iterator}. */ @@ -209,11 +439,11 @@ declare namespace std { * @param begin Input interator of the initial position in a sequence. * @param end Input interator of the final position in a sequence. */ - constructor(begin: base.Iterator, end: base.Iterator); + constructor(begin: Iterator, end: Iterator); /** * @inheritdoc */ - assign>(begin: InputIterator, end: InputIterator): void; + assign>(begin: InputIterator, end: InputIterator): void; /** * @inheritdoc */ @@ -274,10 +504,6 @@ declare namespace std { * @inheritdoc */ push_back(val: T): void; - /** - * @inheritdoc - */ - pop_back(): void; /** *

Insert an element.

* @@ -346,7 +572,92 @@ declare namespace std { * * @return An iterator that points to the first of the newly inserted elements. */ - insert>(position: VectorIterator, begin: InputIterator, end: InputIterator): VectorIterator; + 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.

* @@ -366,6 +677,45 @@ declare namespace std { * 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.

* @@ -385,7 +735,11 @@ declare namespace std { * the function call. This is the {@link end end()} if the operation erased the last element in the * sequence. */ - erase(begin: VectorIterator, end: VectorIterator): VectorIterator; + erase(first: VectorReverseIterator, last: VectorReverseIterator): VectorReverseIterator; + /** + * @hiddde + */ + protected erase_by_range(first: VectorIterator, last: VectorIterator): VectorIterator; /** * @inheritdoc */ @@ -394,15 +748,17 @@ declare namespace std { /** *

An iterator of Vector.

* + *

+ * * @param Type of the elements. * * @author Jeongho Nam */ - class VectorIterator extends base.Iterator implements base.IArrayIterator { + class VectorIterator extends Iterator implements base.IArrayIterator { /** * Sequence number of iterator in the source {@link Vector}. */ - protected index_: number; + private index_; /** *

Construct from the source {@link Vector container}.

* @@ -417,7 +773,7 @@ declare namespace std { /** * @hidden */ - protected vector: Vector; + private vector; /** * @inheritdoc */ @@ -425,6 +781,22 @@ declare namespace std { * Set value. */ value: T; + /** + * Get index. + */ + index: number; + /** + * @inheritdoc + */ + prev(): VectorIterator; + /** + * @inheritdoc + */ + next(): VectorIterator; + /** + * @inheritdoc + */ + advance(n: number): VectorIterator; /** *

Whether an iterator is equal with the iterator.

* @@ -441,19 +813,6 @@ declare namespace std { * @return Indicates whether equal or not. */ equal_to(obj: VectorIterator): boolean; - index: number; - /** - * @inheritdoc - */ - prev(): VectorIterator; - /** - * @inheritdoc - */ - next(): VectorIterator; - /** - * @inheritdoc - */ - advance(n: number): VectorIterator; /** * @inheritdoc */ @@ -462,35 +821,33 @@ declare namespace std { /** *

A reverse-iterator of Vector.

* + *

+ * * @param Type of the elements. * * @author Jeongho Nam */ - class VectorReverseIterator extends base.ReverseIterator implements base.IArrayIterator { - constructor(iterator: VectorIterator); + class VectorReverseIterator extends ReverseIterator, VectorReverseIterator> implements base.IArrayIterator { + constructor(base: VectorIterator); /** - * @hidden + * @inheritdoc + */ + protected create_neighbor(): VectorReverseIterator; + /** + * Set value. */ - private vector_iterator; - index: number; value: T; /** - * @inheritdoc + * Get index. */ - prev(): VectorReverseIterator; - /** - * @inheritdoc - */ - next(): VectorReverseIterator; - /** - * @inheritdoc - */ - advance(n: number): VectorReverseIterator; + index: number; } } declare namespace std.base { /** - *

An abstract

+ *

An abstract container.

+ * + *

* *

Container properties

*
@@ -550,6 +907,30 @@ declare namespace std.base { * @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 */ @@ -569,31 +950,7 @@ declare namespace std.base { /** * @inheritdoc */ - abstract begin(): Iterator; - /** - * @inheritdoc - */ - abstract end(): Iterator; - /** - * @inheritdoc - */ - abstract rbegin(): ReverseIterator; - /** - * @inheritdoc - */ - abstract rend(): ReverseIterator; - /** - * @inheritdoc - */ - abstract size(): number; - /** - * @inheritdoc - */ - empty(): boolean; - /** - * @inheritdoc - */ - swap(obj: Container): void; + swap(obj: IContainer): void; } } declare namespace std { @@ -601,32 +958,32 @@ 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).

+ * 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.

+ *

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}s, {@link Deque}s 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.

+ *

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}s 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.

+ *

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}s perform worse and have less consistent iterators and - * references than {@link List}s.

+ *

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

*
@@ -640,15 +997,12 @@ declare namespace std { * of the sequence. *
* - *
    - *
  • Reference: http://www.cplusplus.com/reference/deque/deque/
  • - *
- * * @param Type of the elements. * + * @reference http://www.cplusplus.com/reference/deque/deque/ * @author Jeongho Nam */ - class Deque extends base.Container implements base.IArray, base.IDeque { + class Deque extends base.Container implements base.IArrayContainer, base.IDequeContainer { /** * Type definition of {@link Deque}'s {@link DequeIterator iterator}. */ @@ -758,11 +1112,11 @@ declare namespace std { * @param begin Input interator of the initial position in a sequence. * @param end Input interator of the final position in a sequence. */ - constructor(begin: base.Iterator, end: base.Iterator); + constructor(begin: Iterator, end: Iterator); /** * @inheritdoc */ - assign>(begin: InputIterator, end: InputIterator): void; + assign>(begin: InputIterator, end: InputIterator): void; /** * @inheritdoc */ @@ -854,7 +1208,35 @@ declare namespace std { /** * @inheritdoc */ - insert>(position: DequeIterator, begin: InputIterator, end: InputIterator): DequeIterator; + 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 */ @@ -862,7 +1244,19 @@ declare namespace std { /** * @inheritdoc */ - erase(begin: DequeIterator, end: DequeIterator): DequeIterator; + 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; /** * @inheritdoc */ @@ -873,12 +1267,13 @@ declare namespace std { private swap_deque(obj); } /** - * An iterator of {@link Deque}. + *

An iterator of {@link Deque}.

+ * + *

* * @author Jeongho Nam */ - class DequeIterator extends base.Iterator implements base.IArrayIterator { - private deque; + class DequeIterator extends Iterator implements base.IArrayIterator { /** * Sequence number of iterator in the source {@link Deque}. */ @@ -894,10 +1289,30 @@ declare namespace std { * @param index Sequence number of the element in the source {@link Deque}. */ constructor(source: Deque, index: number); + /** + * @hidden + */ + private deque; /** * @inheritdoc */ value: T; + /** + * @inheritdoc + */ + index: number; + /** + * @inheritdoc + */ + prev(): DequeIterator; + /** + * @inheritdoc + */ + next(): DequeIterator; + /** + * @inheritdoc + */ + advance(n: number): DequeIterator; /** *

Whether an iterator is equal with the iterator.

* @@ -914,22 +1329,6 @@ declare namespace std { * @return Indicates whether equal or not. */ equal_to(obj: DequeIterator): boolean; - /** - * @inheritdoc - */ - index: number; - /** - * @inheritdoc - */ - prev(): DequeIterator; - /** - * @inheritdoc - */ - next(): DequeIterator; - /** - * @inheritdoc - */ - advance(n: number): DequeIterator; /** * @inheritdoc */ @@ -938,79 +1337,72 @@ declare namespace std { /** *

A reverse-iterator of Deque.

* + *

+ * * @param Type of the elements. * * @author Jeongho Nam */ - class DequeReverseIterator extends base.ReverseIterator implements base.IArrayIterator { - constructor(iterator: DequeIterator); + class DequeReverseIterator extends ReverseIterator, DequeReverseIterator> implements base.IArrayIterator { + constructor(base: DequeIterator); /** - * @hidden + * @inheritdoc + */ + protected create_neighbor(): DequeReverseIterator; + /** + * Set value. */ - private deque_iterator; - index: number; value: T; /** - * @inheritdoc + * Get index. */ - prev(): DequeReverseIterator; - /** - * @inheritdoc - */ - next(): DequeReverseIterator; - /** - * @inheritdoc - */ - advance(n: number): DequeReverseIterator; + index: number; } } 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.

+ *

{@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.

+ *

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.

+ *

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.

+ *

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).

+ * 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.
+ *
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.
+ *
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.
*
* - *
    - *
  • Reference: http://www.cplusplus.com/reference/list/list/ - *
- * * @param Type of the elements. * + * @reference http://www.cplusplus.com/reference/list/list/ * @author Jeongho Nam */ - class List extends base.Container implements base.IDeque { + class List extends base.Container implements base.IDequeContainer { /** * An iterator of beginning. */ @@ -1065,7 +1457,7 @@ declare namespace std { * @param begin Input interator of the initial position in a sequence. * @param end Input interator of the final position in a sequence. */ - constructor(begin: base.Iterator, end: base.Iterator); + constructor(begin: Iterator, end: Iterator); /** * @inheritdoc */ @@ -1073,7 +1465,7 @@ declare namespace std { /** * @inheritdoc */ - assign>(begin: InputIterator, end: InputIterator): void; + assign>(begin: InputIterator, end: InputIterator): void; /** * @inheritdoc */ @@ -1147,6 +1539,13 @@ declare namespace std { /** *

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. @@ -1157,6 +1556,14 @@ declare namespace std { */ 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 @@ -1166,7 +1573,63 @@ declare namespace std { * * @return An iterator that points to the first of the newly inserted elements. */ - insert>(position: ListIterator, begin: InputIterator, end: InputIterator): ListIterator; + 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; /** * @hidden */ @@ -1174,11 +1637,11 @@ declare namespace std { /** * @hidden */ - private insertByRepeatingVal(position, size, val); + protected insert_by_repeating_val(position: ListIterator, size: number, val: T): ListIterator; /** * @hidden */ - private insert_by_range(position, begin, end); + protected insert_by_range>(position: ListIterator, begin: InputIterator, end: InputIterator): ListIterator; /** *

Erase an element.

* @@ -1213,13 +1676,42 @@ declare namespace std { */ erase(begin: ListIterator, end: ListIterator): ListIterator; /** - * @hidden + *

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. */ - private erase_by_iterator(it); + 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; /** * @hidden */ - private erase_by_range(begin, end); + protected erase_by_range(first: ListIterator, last: ListIterator): ListIterator; /** *

Remove duplicate values.

* @@ -1458,12 +1950,16 @@ declare namespace std { private swap_list(obj); } /** - * An iterator, node of a List. + *

An iterator, node of a List.

+ * + *

+ * + * @author Jeongho Nam */ - class ListIterator extends base.Iterator { - protected prev_: ListIterator; - protected next_: ListIterator; - protected value_: T; + class ListIterator extends Iterator { + private prev_; + private next_; + private value_; /** *

Construct from the source {@link List container}.

* @@ -1480,15 +1976,12 @@ declare namespace std { /** * @inheritdoc */ - setPrev(prev: ListIterator): void; + set_prev(it: ListIterator): void; /** * @inheritdoc */ - setNext(next: ListIterator): void; - /** - * @inheritdoc - */ - equal_to(obj: ListIterator): boolean; + set_next(next: ListIterator): void; + private list(); /** * @inheritdoc */ @@ -1505,6 +1998,10 @@ declare namespace std { * @inheritdoc */ value: T; + /** + * @inheritdoc + */ + equal_to(obj: ListIterator): boolean; /** * @inheritdoc */ @@ -1513,29 +2010,22 @@ declare namespace std { /** *

A reverse-iterator of List.

* + *

+ * * @param Type of the elements. * * @author Jeongho Nam */ - class ListReverseIterator extends base.ReverseIterator { - constructor(iterator: ListIterator); + class ListReverseIterator extends ReverseIterator, ListReverseIterator> { + constructor(base: ListIterator); /** - * @hidden + * @inheritdoc + */ + protected create_neighbor(): ListReverseIterator; + /** + * @inheritdoc */ - private list_iterator; value: T; - /** - * @inheritdoc - */ - prev(): ListReverseIterator; - /** - * @inheritdoc - */ - next(): ListReverseIterator; - /** - * @inheritdoc - */ - advance(n: number): ListReverseIterator; } } declare namespace std { @@ -1568,12 +2058,11 @@ declare namespace std { * By default, if no container class is specified for a particular {@link Queue} class instantiation, the standard * container {@link List} is used.

* - *
    - *
  • Reference: http://www.cplusplus.com/reference/queue/queue/
  • - *
+ *

* * @param Type of elements. * + * @reference http://www.cplusplus.com/reference/queue/queue * @author Jeongho Nam */ class Queue { @@ -1770,7 +2259,7 @@ declare namespace std { * @param begin Input interator of the initial position in a sequence. * @param end Input interator of the final position in a sequence. */ - constructor(begin: base.Iterator, end: base.Iterator); + constructor(begin: Iterator, end: Iterator); /** * Range Constructor with compare. * @@ -1778,7 +2267,7 @@ declare namespace std { * @param end Input interator of the final position in a sequence. * @param compare A binary predicate determines order of elements. */ - constructor(begin: base.Iterator, end: base.Iterator, compare: (left: T, right: T) => boolean); + constructor(begin: Iterator, end: Iterator, compare: (left: T, right: T) => boolean); /** * @hidden */ @@ -1790,7 +2279,7 @@ declare namespace std { /** * @hidden */ - protected construct_from_range(begin: base.Iterator, end: base.Iterator): void; + protected construct_from_range(begin: Iterator, end: Iterator): void; /** *

Return size.

* @@ -1897,12 +2386,11 @@ declare namespace std { * By default, if no container class is specified for a particular {@link Stack} class instantiation, the standard * container {@link List} is used.

* - *
    - *
  • Reference: http://www.cplusplus.com/reference/stack/stack/
  • - *
+ *

* * @param Type of elements. * + * @reference http://www.cplusplus.com/reference/stack/stack * @author Jeongho Nam */ class Stack { @@ -2007,12 +2495,14 @@ declare namespace std.base { * {@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 + * position in the container. *
* *
Set
@@ -2054,6 +2544,10 @@ declare namespace std.base { * Construct from range iterators. */ constructor(begin: Iterator, end: Iterator); + /** + * @hidden + */ + protected init(): void; /** * @hidden */ @@ -2061,11 +2555,11 @@ declare namespace std.base { /** * @hidden */ - protected construct_from_container(container: Container): void; + protected construct_from_container(container: IContainer): void; /** * @hidden */ - protected construct_from_range(begin: Iterator, end: Iterator): void; + protected construct_from_range>(begin: InputIterator, end: InputIterator): void; /** * @inheritdoc */ @@ -2146,6 +2640,19 @@ declare namespace std.base { * 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

* @@ -2163,11 +2670,11 @@ declare namespace std.base { /** * @hidden */ - protected insert_by_hint(hint: SetIterator, val: T): SetIterator; + protected abstract insert_by_hint(hint: SetIterator, val: T): SetIterator; /** * @hidden */ - protected insert_by_range>(begin: InputIterator, end: InputIterator): void; + protected abstract insert_by_range>(begin: InputIterator, end: InputIterator): void; /** *

Erase an element.

*

Removes from the set container the elements whose value is key.

@@ -2193,63 +2700,86 @@ declare namespace std.base { * @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_iterator(it); /** * @hidden */ private erase_by_range(begin, end); /** - *

Abstract method handling insertion for indexing.

+ *

Abstract method handling insertions for indexing.

* - *

This method, {@link handle_insert} is designed to register the item to somewhere storing those - * {@link SetIterator iterators} for indexing, fast accessment and retrievalance.

- * - *

When {@link insert} is called, a new element will be inserted into the {@link data_ list container} - * and a new {@link SetIterator iterator} item, pointing the element, will be created and the newly - * created iterator item will be shifted into this method {@link handle_insert} after the insertion.

- * - *

If the derived one is {@link RBTree tree-based} like {@link TreeSet}, the item 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 item will be registered into the - * {@link HashSet.hash_buckets_ hash bucket}.

- * - * @param item Iterator of inserted item. - */ - protected abstract handle_insert(item: SetIterator): void; - /** - *

Abstract method handling deletion for indexing.

- * - *

This method, {@link handle_insert} is designed to unregister the item to somewhere storing + *

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 erase} is called with item, an {@link SetIterator iterator} positioning somewhere - * place to be deleted, is memorized and shifted to this method {@link handle_erase} after the deletion - * process is terminated.

+ *

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 item 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 item will be unregistered - * from the {@link HashSet.hash_buckets_ hash bucket}.

+ *

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 item Iterator of erased item. + * @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(item: SetIterator): void; + protected abstract handle_insert(first: SetIterator, last: SetIterator): void; + /** + *

Abstract method handling deletions for indexing.

+ * + *

This method, {@link handle_insert} 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; } } declare namespace std { /** *

An iterator of a Set.

* + *

+ * * @author Jeongho Nam */ - class SetIterator extends base.Iterator implements IComparable> { + class SetIterator extends Iterator implements IComparable> { private list_iterator_; /** *

Construct from source and index number.

@@ -2303,28 +2833,18 @@ declare namespace std { /** *

A reverse-iterator of Set.

* + *

+ * * @param Type of the elements. * * @author Jeongho Nam */ - class SetReverseIterator extends base.ReverseIterator { - constructor(iterator: SetIterator); - /** - * @hidden - */ - private set_iterator; + class SetReverseIterator extends ReverseIterator, SetReverseIterator> { + constructor(base: SetIterator); /** * @inheritdoc */ - prev(): SetReverseIterator; - /** - * @inheritdoc - */ - next(): SetReverseIterator; - /** - * @inheritdoc - */ - advance(n: number): SetReverseIterator; + protected create_neighbor(): SetReverseIterator; } } declare namespace std.base { @@ -2342,12 +2862,14 @@ declare namespace std.base { * {@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 + * position in the container. *
* *
Set
@@ -2363,10 +2885,6 @@ declare namespace std.base { * @author Jeongho Nam */ abstract class UniqueSet extends SetContainer { - /** - * Default Constructor. - */ - constructor(); /** * @inheritdoc */ @@ -2395,10 +2913,18 @@ declare namespace std.base { * @inheritdoc */ insert(hint: SetIterator, val: T): SetIterator; + /** + * @inheritdoc + */ + insert(hint: SetReverseIterator, val: T): SetReverseIterator; /** * @inheritdoc */ insert>(begin: InputIterator, end: InputIterator): void; + /** + * @inheritdoc + */ + swap(obj: UniqueSet): void; } } declare namespace std.base { @@ -2416,12 +2942,14 @@ declare namespace std.base { * {@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 + * position in the container. *
* *
Set
@@ -2437,14 +2965,6 @@ declare namespace std.base { * @author Jeongho Nam */ abstract class MultiSet extends SetContainer { - /** - * Default Constructor. - */ - constructor(); - /** - * @inheritdoc - */ - count(val: T): number; /** *

Insert an element.

* @@ -2460,10 +2980,18 @@ declare namespace std.base { * @inheritdoc */ insert(hint: SetIterator, val: T): SetIterator; + /** + * @inheritdoc + */ + insert(hint: SetReverseIterator, val: T): SetReverseIterator; /** * @inheritdoc */ insert>(begin: InputIterator, end: InputIterator): void; + /** + * @inheritdoc + */ + swap(obj: MultiSet): void; } } declare namespace std { @@ -2485,11 +3013,13 @@ declare namespace std { * 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
+ * position in the container. * *
Hashed
*
Hashed containers organize their elements using hash tables that allow for fast access to elements @@ -2502,41 +3032,22 @@ declare namespace std { *
No two elements in the container can have equivalent keys.
*
* - *
    - *
  • Reference: http://www.cplusplus.com/reference/unordered_set/unordered_set/
  • - *
- * * @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 { private hash_buckets_; /** - * Default Constructor. + * @hidden */ - constructor(); - /** - * Construct from elements. - */ - constructor(items: Array); - /** - * Copy Constructor. - */ - constructor(container: base.IContainer); - /** - * Construct from range iterators. - */ - constructor(begin: base.Iterator, end: base.Iterator); + protected init(): void; /** * @hidden */ protected construct_from_array(items: Array): void; - /** - * @inheritdoc - */ - assign>(begin: InputIterator, end: InputIterator): void; /** * @inheritdoc */ @@ -2552,19 +3063,23 @@ declare namespace std { /** * @hidden */ - protected insert_by_range>(begin: InputIterator, end: InputIterator): void; + protected insert_by_hint(hint: SetIterator, val: T): SetIterator; + /** + * @hidden + */ + protected insert_by_range>(first: InputIterator, last: InputIterator): void; /** * @inheritdoc */ - protected handle_insert(item: SetIterator): void; + protected handle_insert(first: SetIterator, last: SetIterator): void; /** * @inheritdoc */ - protected handle_erase(item: SetIterator): void; + protected handle_erase(first: SetIterator, last: SetIterator): void; /** * @inheritdoc */ - swap(obj: base.IContainer): void; + swap(obj: base.UniqueSet): void; /** * @hidden */ @@ -2588,11 +3103,13 @@ declare namespace std { *

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
+ * position in the container. * *
Hashed
*
Hashed containers organize their elements using hash tables that allow for fast access to elements @@ -2605,41 +3122,22 @@ declare namespace std { *
The container can hold multiple elements with equivalent keys.
*
* - *
    - *
  • Reference: http://www.cplusplus.com/reference/unordered_set/unordered_multiset/
  • - *
- * * @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 { private hash_buckets_; /** - * Default Constructor. + * @hidden */ - constructor(); - /** - * Construct from elements. - */ - constructor(items: Array); - /** - * Copy Constructor. - */ - constructor(container: base.IContainer); - /** - * Construct from range iterators. - */ - constructor(begin: base.Iterator, end: base.Iterator); + protected init(): void; /** * @hidden */ protected construct_from_array(items: Array): void; - /** - * @inheritdoc - */ - assign>(begin: InputIterator, end: InputIterator): void; /** * @inheritdoc */ @@ -2648,6 +3146,10 @@ declare namespace std { * @inheritdoc */ find(val: T): SetIterator; + /** + * @inheritdoc + */ + count(val: T): number; /** * @hidden */ @@ -2655,19 +3157,23 @@ declare namespace std { /** * @hidden */ - protected insert_by_range>(begin: InputIterator, end: InputIterator): void; + protected insert_by_hint(hint: SetIterator, val: T): SetIterator; + /** + * @hidden + */ + protected insert_by_range>(first: InputIterator, last: InputIterator): void; /** * @inheritdoc */ - protected handle_insert(it: SetIterator): void; + protected handle_insert(first: SetIterator, last: SetIterator): void; /** * @inheritdoc */ - protected handle_erase(it: SetIterator): void; + protected handle_erase(first: SetIterator, last: SetIterator): void; /** * @inheritdoc */ - swap(obj: base.IContainer): void; + swap(obj: base.MultiSet): void; /** * @hidden */ @@ -2693,12 +3199,14 @@ declare namespace std.base { * {@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 + * in the container. *
* *
Map
@@ -2713,7 +3221,7 @@ declare namespace std.base { * * @author Jeongho Nam */ - abstract class MapContainer { + abstract class MapContainer extends base.Container> { /** * Type definition of {@link MapContainer}'s {@link MapIterator iterator}. */ @@ -2744,11 +3252,15 @@ declare namespace std.base { /** * Copy Constructor. */ - constructor(container: MapContainer); + constructor(container: IContainer>); /** * Construct from range iterators. */ - constructor(begin: MapIterator, end: MapIterator); + constructor(begin: Iterator>, end: Iterator>); + /** + * @hidden + */ + protected init(): void; /** * @hidden */ @@ -2756,25 +3268,17 @@ declare namespace std.base { /** * @hidden */ - protected construct_from_container(container: MapContainer): void; + protected construct_from_container(container: IContainer>): void; /** * @hidden */ - protected construct_from_range(begin: MapIterator, end: MapIterator): void; + protected construct_from_range>>(begin: InputIterator, end: InputIterator): void; /** - *

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. + * @inheritdoc */ - assign(begin: MapIterator, end: MapIterator): void; + assign>>(first: InputIterator, last: InputIterator): void; /** - *

Clear content.

- * - *

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

+ * @inheritdoc */ clear(): void; /** @@ -2879,9 +3383,13 @@ declare namespace std.base { */ size(): number; /** - * Test whether the container is empty. + * @inheritdoc */ - empty(): boolean; + push(...args: Pair[]): number; + /** + * @inheritdoc + */ + push(...args: [Key, T][]): number; /** *

Insert an element.

* @@ -2895,6 +3403,19 @@ declare namespace std.base { * 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 {@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, pair: Pair): MapReverseIterator; /** *

Insert an element.

* @@ -2908,6 +3429,19 @@ declare namespace std.base { * 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.

* @@ -2919,7 +3453,7 @@ declare namespace std.base { * 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(begin: MapIterator, end: MapIterator): void; + insert>>(first: InputIterator, last: InputIterator): void; /** * @hidden */ @@ -2931,15 +3465,15 @@ declare namespace std.base { /** * @hidden */ - protected insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; + protected abstract insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; /** * @hidden */ - private insert_by_hint_with_tuple(hint, tuple); + private insert_by_hint_with_tuple(hint, tuple); /** * @hidden */ - protected insert_by_range(begin: MapIterator, end: MapIterator): void; + protected abstract insert_by_range>>(first: InputIterator, last: InputIterator): void; /** *

Erase an elemet by key.

* @@ -2978,6 +3512,33 @@ declare namespace std.base { * 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 */ @@ -2985,82 +3546,69 @@ declare namespace std.base { /** * @hidden */ - private erase_by_iterator(it); + private erase_by_iterator(first, last?); /** * @hidden */ private erase_by_range(begin, end); /** - *

Abstract method handling insertion for indexing.

+ *

Abstract method handling insertions for indexing.

* - *

This method, {@link handle_insert} is designed to register the item to somewhere storing those - * {@link MapIterator iterators} for indexing, fast accessment and retrievalance.

- * - *

When {@link insert} is called, a new element will be inserted into the {@link data_ list container} - * and a new {@link MapIterator iterator} item, pointing the element, will be created and the newly - * created iterator item will be shifted into this method {@link handle_insert} after the insertion.

- * - *

If the derived one is {@link RBTree tree-based} like {@link TreeMap}, the item will be - * registered into the {@link TreeMap.tree_ tree} as a {@link XTreeNode tree node item}. Else if the derived - * one is {@link HashBuckets hash-based} like {@link HashSet}, the item will be registered into the - * {@link HashMap.hash_buckets_ hash bucket}.

- * - * @param item Iterator of inserted item. - */ - protected abstract handle_insert(item: MapIterator): void; - /** - *

Abstract method handling deletion for indexing.

- * - *

This method, {@link handle_insert} is designed to unregister the item to somewhere storing + *

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 erase} is called with item, an {@link MapIterator iterator} positioning somewhere - * place to be deleted, is memorized and shifted to this method {@link handle_erase} after the deletion - * process is terminated.

+ *

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 TreeMap}, the item will be - * unregistered from the {@link TreeMap.tree_ tree} as a {@link XTreeNode tree node item}. Else if the - * derived one is {@link HashBuckets hash-based} like {@link HashSet}, the item will be unregistered - * from the {@link HashMap.hash_buckets_ hash bucket}.

+ *

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 item Iterator of erased item. + * @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(item: MapIterator): void; + protected abstract handle_insert(first: MapIterator, last: MapIterator): void; /** - *

Swap content.

+ *

Abstract method handling deletions for indexing.

* - *

Exchanges the content of the container by the content of obj, which is another - * {@link MapContainer map} of the same type. Sizes abd container type may differ.

+ *

This method, {@link handle_insert} is designed to unregister the first to last to somewhere storing + * those {@link MapIterator iterators} for indexing, fast accessment and retrievalance.

* - *

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.

+ *

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.

* - *

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.

+ *

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 obj Another {@link MapContainer 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 MapContaier container}. + * @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. */ - swap(obj: MapContainer): void; + protected abstract handle_erase(first: MapIterator, last: MapIterator): void; } } declare namespace std { /** - * An iterator of {@link MapColntainer map container}. + *

An iterator of {@link MapContainer map container}.

+ * + *

* * @author Jeongho Nam */ - class MapIterator implements IComparable> { - /** - * The source {@link MapContainer} of the iterator is directing for. - */ - protected source_: base.MapContainer; + class MapIterator extends Iterator> implements IComparable> { /** * A {@link ListIterator} pointing {@link Pair} of key and value. */ - protected list_iterator_: ListIterator>; + private list_iterator_; /** * Construct from the {@link MapContainer source map} and {@link ListIterator list iterator}. * @@ -3084,13 +3632,17 @@ declare namespace std { */ advance(step: number): MapIterator; /** - * Get source. + * @hidden */ - get_source(): base.MapContainer; + private map; /** * Get ListIterator. */ get_list_iterator(): ListIterator>; + /** + * @inheritdoc + */ + value: Pair; /** * Get first, key element. */ @@ -3115,33 +3667,27 @@ declare namespace std { hash(): number; swap(obj: MapIterator): void; } -} -declare namespace std { /** - * A reverse-iterator of {@link MapColntainer map container}. + *

A reverse-iterator of {@link MapContainer map container}.

+ * + *

* * @author Jeongho Nam */ - class MapReverseIterator extends MapIterator { + class MapReverseIterator extends ReverseIterator, MapIterator, MapReverseIterator> { + constructor(base: MapIterator); + protected create_neighbor(): MapReverseIterator; /** - * 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. + * Get first, key element. */ - constructor(source: base.MapContainer, list_iterator: ListIterator>); + first: Key; /** - * @inheritdoc + * Get second, value element. */ - prev(): MapReverseIterator; /** - * @inheritdoc + * Set second value. */ - next(): MapReverseIterator; - /** - * @inheritdoc - */ - advance(step: number): MapReverseIterator; + second: T; } } declare namespace std.base { @@ -3163,12 +3709,14 @@ declare namespace std.base { * {@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 + * in the container. *
* *
Map
@@ -3187,28 +3735,6 @@ declare namespace std.base { * @author Jeongho Nam */ abstract class UniqueMap extends MapContainer { - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from elements. - */ - constructor(items: Array>); - /** - * Contruct from tuples. - * - * @param array Tuples to be contained. - */ - constructor(array: Array<[Key, T]>); - /** - * Copy Constructor. - */ - constructor(container: MapContainer); - /** - * Construct from range iterators. - */ - constructor(begin: MapIterator, end: MapIterator); /** * @inheritdoc */ @@ -3281,6 +3807,10 @@ declare namespace std.base { * @inheritdoc */ insert(hint: MapIterator, pair: Pair): MapIterator; + /** + * @inheritdoc + */ + insert(hint: MapReverseIterator, pair: Pair): MapReverseIterator; /** * @inheritdoc */ @@ -3288,7 +3818,29 @@ declare namespace std.base { /** * @inheritdoc */ - insert(begin: MapIterator, end: MapIterator): void; + insert(hint: MapReverseIterator, tuple: [L, U]): MapReverseIterator; + /** + * @inheritdoc + */ + insert>>(first: InputIterator, last: InputIterator): void; + /** + *

Swap content.

+ * + *

Exchanges the content of the container by the content of obj, which is another + * {@link UniqueMap 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 UniqueMap 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 UniqueMap container}. + */ + swap(obj: UniqueMap): void; } } declare namespace std.base { @@ -3310,12 +3862,14 @@ declare namespace std.base { * {@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 + * in the container. *
* *
Map
@@ -3334,32 +3888,6 @@ declare namespace std.base { * @author Jeongho Nam */ abstract class MultiMap extends MapContainer { - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from elements. - */ - constructor(items: Array>); - /** - * Contruct from tuples. - * - * @param array Tuples to be contained. - */ - constructor(array: Array<[Key, T]>); - /** - * Copy Constructor. - */ - constructor(container: MapContainer); - /** - * Construct from range iterators. - */ - constructor(begin: MapIterator, end: MapIterator); - /** - * @inheritdoc - */ - count(key: Key): number; /** *

Insert elements.

* @@ -3386,6 +3914,10 @@ declare namespace std.base { * @inheritdoc */ insert(hint: MapIterator, pair: Pair): MapIterator; + /** + * @inheritdoc + */ + insert(hint: MapReverseIterator, pair: Pair): MapReverseIterator; /** * @inheritdoc */ @@ -3393,35 +3925,58 @@ declare namespace std.base { /** * @inheritdoc */ - insert(begin: MapIterator, end: MapIterator): void; + insert(hint: MapReverseIterator, tuple: [L, U]): MapReverseIterator; + /** + * @inheritdoc + */ + insert>>(first: InputIterator, last: InputIterator): void; + /** + *

Swap content.

+ * + *

Exchanges the content of the container by the content of obj, which is another + * {@link UniqueMap 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 MultiMap 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 MultiMap container}. + */ + swap(obj: MultiMap): void; } } 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.

+ *

{@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.

+ *

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).

+ *

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.

+ *

{@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
+ * position in the container. * *
Hashed
*
Hashed containers organize their elements using hash tables that allow for fast access to elements @@ -3435,56 +3990,24 @@ declare namespace std { *
No two elements in the container can have equivalent keys.
*
* - *
    - *
  • Reference: http://www.cplusplus.com/reference/unordered_map/unordered_map/
  • - *
- * * @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 { private hash_buckets_; /** - * Default Constructor. + * @hidden */ - constructor(); - /** - * Contruct from elements. - * - * @param array Elements to be contained. - */ - constructor(array: Array>); - /** - * Contruct from tuples. - * - * @param array Tuples to be contained. - */ - constructor(array: Array<[Key, T]>); - /** - * Copy Constructor. - * - * @param container Another map to copy. - */ - constructor(container: base.MapContainer); - /** - * 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: MapIterator, end: MapIterator); + protected init(): void; /** * @hidden */ protected construct_from_array(items: Array>): void; - /** - * @inheritdoc - */ - assign(begin: MapIterator, end: MapIterator): void; /** * @inheritdoc */ @@ -3500,19 +4023,23 @@ declare namespace std { /** * @hidden */ - protected insert_by_range(begin: MapIterator, end: MapIterator): void; + protected insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; + /** + * @hidden + */ + protected insert_by_range>>(first: InputIterator, last: InputIterator): void; /** * @inheritdoc */ - protected handle_insert(it: MapIterator): void; + protected handle_insert(first: MapIterator, last: MapIterator): void; /** * @inheritdoc */ - protected handle_erase(it: MapIterator): void; + protected handle_erase(first: MapIterator, last: MapIterator): void; /** * @inheritdoc */ - swap(obj: base.MapContainer): void; + swap(obj: base.UniqueMap): void; /** * @hidden */ @@ -3537,11 +4064,13 @@ declare namespace std { *

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
+ * position in the container. * *
Hashed
*
Hashed containers organize their elements using hash tables that allow for fast access to elements @@ -3555,15 +4084,12 @@ declare namespace std { *
The container can hold multiple elements with equivalent keys.
*
* - *
    - *
  • Reference: http://www.cplusplus.com/reference/unordered_map/unordered_multimap/
  • - *
- * * @param Type of the key values. * Each element in an {@link HashMap} is identified by a 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_multimap * @author Jeongho Nam */ class HashMultiMap extends base.MultiMap { @@ -3572,42 +4098,13 @@ declare namespace std { */ private hash_buckets_; /** - * Default Constructor. + * @hidden */ - constructor(); - /** - * Contruct from elements. - * - * @param array Elements to be contained. - */ - constructor(array: Array>); - /** - * Contruct from tuples. - * - * @param array Tuples to be contained. - */ - constructor(array: Array<[Key, T]>); - /** - * Copy Constructor. - * - * @param container Another map to copy. - */ - constructor(container: base.MapContainer); - /** - * 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: MapIterator, end: MapIterator); + protected init(): void; /** * @hidden */ protected construct_from_array(items: Array>): void; - /** - * @inheritdoc - */ - assign(begin: MapIterator, end: MapIterator): void; /** * @inheritdoc */ @@ -3616,6 +4113,10 @@ declare namespace std { * @inheritdoc */ find(key: Key): MapIterator; + /** + * @inheritdoc + */ + count(key: Key): number; /** * @hidden */ @@ -3623,19 +4124,23 @@ declare namespace std { /** * @hidden */ - protected insert_by_range(begin: MapIterator, end: MapIterator): void; + protected insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; + /** + * @hidden + */ + protected insert_by_range>>(first: InputIterator, last: InputIterator): void; /** * @inheritdoc */ - protected handle_insert(it: MapIterator): void; + protected handle_insert(first: MapIterator, last: MapIterator): void; /** * @inheritdoc */ - protected handle_erase(it: MapIterator): void; + protected handle_erase(first: MapIterator, last: MapIterator): void; /** * @inheritdoc */ - swap(obj: base.MapContainer): void; + swap(obj: base.MultiMap): void; /** * @hidden */ @@ -3662,12 +4167,14 @@ declare namespace std { * *

{@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 + * position in the container. *
* *
Ordered
@@ -3683,13 +4190,10 @@ declare namespace std { *
No two elements in the container can have equivalent keys.
*
* - *
    - *
  • Reference: http://www.cplusplus.com/reference/set/set/
  • - *
- * * @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 { @@ -3723,21 +4227,21 @@ declare namespace std { /** * Copy Constructor. */ - constructor(container: base.Container); + 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.Container, compare: (left: T, right: T) => boolean); + 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: base.Iterator, end: base.Iterator); + constructor(begin: Iterator, end: Iterator); /** * Range Constructor with compare. * @@ -3745,11 +4249,7 @@ declare namespace std { * @param end Input interator of the final position in a sequence. * @param compare A binary predicate determines order of elements. */ - constructor(begin: base.Iterator, end: base.Iterator, compare: (left: T, right: T) => boolean); - /** - * @inheritdoc - */ - assign>(begin: InputIterator, end: InputIterator): void; + constructor(begin: Iterator, end: Iterator, compare: (left: T, right: T) => boolean); /** * @inheritdoc */ @@ -3829,18 +4329,23 @@ declare namespace std { * @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(item: SetIterator): void; + protected handle_insert(first: SetIterator, last: SetIterator): void; /** * @inheritdoc */ - protected handle_erase(item: SetIterator): void; + protected handle_erase(first: SetIterator, last: SetIterator): void; /** * @inheritdoc */ - swap(obj: base.IContainer): void; + swap(obj: base.UniqueSet): void; /** * @hidden */ @@ -3866,12 +4371,14 @@ declare namespace std { * *

{@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 + * position in the container. *
* *
Ordered
@@ -3887,13 +4394,10 @@ declare namespace std { *
Multiple elements in the container can have equivalent keys.
*
* - *
    - *
  • Reference: http://www.cplusplus.com/reference/set/multiset/
  • - *
- * * @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 { @@ -3941,7 +4445,7 @@ declare namespace std { * @param begin Input interator of the initial position in a sequence. * @param end Input interator of the final position in a sequence. */ - constructor(begin: base.Iterator, end: base.Iterator); + constructor(begin: Iterator, end: Iterator); /** * Construct from range and compare. * @@ -3949,11 +4453,7 @@ declare namespace std { * @param end Input interator of the final position in a sequence. * @param compare A binary predicate determines order of elements. */ - constructor(begin: base.Iterator, end: base.Iterator, compare: (left: T, right: T) => boolean); - /** - * @inheritdoc - */ - assign>(begin: InputIterator, end: InputIterator): void; + constructor(begin: Iterator, end: Iterator, compare: (left: T, right: T) => boolean); /** * @inheritdoc */ @@ -3962,6 +4462,10 @@ declare namespace std { * @inheritdoc */ find(val: T): SetIterator; + /** + * @inheritdoc + */ + count(val: T): number; /** *

Return iterator to lower bound.

* @@ -4033,17 +4537,25 @@ declare namespace std { */ protected insert_by_val(val: T): any; /** - * @inheritdoc + * @hidden */ - protected handle_insert(item: SetIterator): void; + protected insert_by_hint(hint: SetIterator, val: T): SetIterator; + /** + * @hidden + */ + protected insert_by_range>(first: InputIterator, last: InputIterator): void; /** * @inheritdoc */ - protected handle_erase(item: SetIterator): void; + protected handle_insert(first: SetIterator, last: SetIterator): void; /** * @inheritdoc */ - swap(obj: base.IContainer): void; + protected handle_erase(first: SetIterator, last: SetIterator): void; + /** + * @inheritdoc + */ + swap(obj: base.MultiSet): void; /** * @hidden */ @@ -4057,27 +4569,28 @@ declare namespace std { *

{@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:

+ *

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}. + *

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} 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
+ * position in the container. * *
Ordered
*
The elements in the container follow a strict order at all times. All inserted elements are @@ -4091,13 +4604,10 @@ declare namespace std { *
No two elements in the container can have equivalent keys.
*
* - *
    - *
  • Reference: http://www.cplusplus.com/reference/map/map/
  • - *
- * * @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 { @@ -4160,7 +4670,7 @@ declare namespace std { * @param begin nput interator of the initial position in a sequence. * @param end Input interator of the final position in a sequence. */ - constructor(begin: MapIterator, end: MapIterator); + constructor(begin: Iterator>, end: Iterator>); /** * Range Constructor. * @@ -4168,11 +4678,7 @@ declare namespace std { * @param end Input interator of the final position in a sequence. * @param compare A binary predicate determines order of elements. */ - constructor(begin: MapIterator, end: MapIterator, compare: (left: Key, right: Key) => boolean); - /** - * @inheritdoc - */ - assign(begin: MapIterator, end: MapIterator): void; + constructor(begin: Iterator>, end: Iterator>, compare: (left: Key, right: Key) => boolean); /** * @inheritdoc */ @@ -4255,17 +4761,25 @@ declare namespace std { */ protected insert_by_pair(pair: Pair): any; /** - * @inheritdoc + * @hidden */ - protected handle_insert(item: MapIterator): void; + protected insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; + /** + * @hidden + */ + protected insert_by_range>>(first: InputIterator, last: InputIterator): void; /** * @inheritdoc */ - protected handle_erase(item: MapIterator): void; + protected handle_insert(first: MapIterator, last: MapIterator): void; /** * @inheritdoc */ - swap(obj: base.MapContainer): void; + protected handle_erase(first: MapIterator, last: MapIterator): void; + /** + * @inheritdoc + */ + swap(obj: base.UniqueMap): void; /** * @hidden */ @@ -4294,12 +4808,14 @@ declare namespace std { * *

{@link TreeMultiMap 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 + * position in the container. *
* *
Ordered
@@ -4318,13 +4834,10 @@ declare namespace std { *
Multiple elements in the container can have equivalent keys.
*
* - *
    - *
  • Reference: http://www.cplusplus.com/reference/map/multimap/
  • - *
- * * @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 { @@ -4384,7 +4897,7 @@ declare namespace std { * @param begin nput interator of the initial position in a sequence. * @param end Input interator of the final position in a sequence. */ - constructor(begin: MapIterator, end: MapIterator); + constructor(begin: Iterator>, end: Iterator>); /** * Range Constructor. * @@ -4392,11 +4905,7 @@ declare namespace std { * @param end Input interator of the final position in a sequence. * @param compare A binary predicate determines order of elements. */ - constructor(begin: MapIterator, end: MapIterator, compare: (left: Key, right: Key) => boolean); - /** - * @inheritdoc - */ - assign(begin: MapIterator, end: MapIterator): void; + constructor(begin: Iterator>, end: Iterator>, compare: (left: Key, right: Key) => boolean); /** * @inheritdoc */ @@ -4405,6 +4914,10 @@ declare namespace std { * @inheritdoc */ find(key: Key): MapIterator; + /** + * @inheritdoc + */ + count(key: Key): number; /** *

Return iterator to lower bound.

* @@ -4476,17 +4989,25 @@ declare namespace std { */ protected insert_by_pair(pair: Pair): any; /** - * @inheritdoc + * @hidden */ - protected handle_insert(item: MapIterator): void; + protected insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; + /** + * @hidden + */ + protected insert_by_range>>(first: InputIterator, last: InputIterator): void; /** * @inheritdoc */ - protected handle_erase(item: MapIterator): void; + protected handle_insert(first: MapIterator, last: MapIterator): void; /** * @inheritdoc */ - swap(obj: base.MapContainer): void; + protected handle_erase(first: MapIterator, last: MapIterator): void; + /** + * @inheritdoc + */ + swap(obj: base.MultiMap): void; /** * @hidden */ @@ -4508,7 +5029,7 @@ declare namespace std { * * @return Returns fn. */ - function for_each, Func extends (val: T) => any>(first: Iterator, last: Iterator, fn: Func): Func; + function for_each, Func extends (val: T) => any>(first: InputIterator, last: InputIterator, fn: Func): Func; /** *

Test condition on all elements in range.

* @@ -4527,7 +5048,7 @@ declare namespace std { * @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: Iterator, last: Iterator, pred: (val: T) => boolean): boolean; + function all_of>(first: InputIterator, last: InputIterator, pred: (val: T) => boolean): boolean; /** *

Test if any element in range fulfills condition.

* @@ -4549,7 +5070,7 @@ declare namespace std { * [first, last), and false otherwise. If [first, last) is an * {@link IContainer.empty empty} range, the function returns false. */ - function any_of>(first: Iterator, last: Iterator, pred: (val: T) => boolean): boolean; + function any_of>(first: InputIterator, last: InputIterator, pred: (val: T) => boolean): boolean; /** *

Test if no elements fulfill condition.

* @@ -4569,7 +5090,7 @@ declare namespace std { * [first, last) or if the range is {@link IContainer.empty empty}, and false * otherwise. */ - function none_of>(first: Iterator, last: Iterator, pred: (val: T) => boolean): boolean; + function none_of>(first: InputIterator, last: InputIterator, pred: (val: T) => boolean): boolean; /** *

Test whether the elements in two ranges are equal.

* @@ -4586,7 +5107,7 @@ declare namespace std { * @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: Iterator1, last1: Iterator1, first2: base.Iterator): boolean; + function equal>(first1: Iterator1, last1: Iterator1, first2: Iterator): boolean; /** *

Test whether the elements in two ranges are equal.

* @@ -4606,7 +5127,7 @@ declare namespace std { * @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: Iterator1, last1: Iterator1, first2: base.Iterator, pred: (x: T, y: T) => boolean): boolean; + function equal>(first1: Iterator1, last1: Iterator1, first2: Iterator, pred: (x: T, y: T) => boolean): boolean; /** *

Test whether range is permutation of another.

* @@ -4624,7 +5145,7 @@ declare namespace std { * @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 base.Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2): boolean; + function is_permutation, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2): boolean; /** *

Test whether range is permutation of another.

* @@ -4645,7 +5166,7 @@ declare namespace std { * @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 base.Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, pred: (x: T, y: T) => boolean): boolean; + function is_permutation, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, pred: (x: T, y: T) => boolean): boolean; /** *

Lexicographical less-than comparison.

* @@ -4671,7 +5192,7 @@ declare namespace std { * @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 base.Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, last2: Iterator2): boolean; + function lexicographical_compare, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, last2: Iterator2): boolean; /** *

Lexicographical comparison.

* @@ -4700,7 +5221,7 @@ declare namespace std { * @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 base.Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, last2: Iterator2, compare: (x: T, y: T) => boolean): boolean; + 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.

* @@ -4718,7 +5239,7 @@ declare namespace std { * @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: Iterator, last: Iterator, val: T): Iterator; + function find>(first: InputIterator, last: InputIterator, val: T): InputIterator; /** *

Find element in range.

* @@ -4737,7 +5258,7 @@ declare namespace std { * false. If pred is false for all elements, the function returns * last. */ - function find_if>(first: Iterator, last: Iterator, pred: (val: T) => boolean): Iterator; + function find_if>(first: InputIterator, last: InputIterator, pred: (val: T) => boolean): InputIterator; /** *

Find element in range.

* @@ -4755,7 +5276,7 @@ declare namespace std { * @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: Iterator, last: Iterator, pred: (val: T) => boolean): Iterator; + function find_if_not>(first: InputIterator, last: InputIterator, pred: (val: T) => boolean): InputIterator; /** *

Find last subsequence in range.

* @@ -4785,7 +5306,7 @@ declare namespace std { * [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 base.Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, last2: Iterator2): Iterator1; + function find_end, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, last2: Iterator2): Iterator1; /** *

Find last subsequence in range.

* @@ -4815,7 +5336,7 @@ declare namespace std { * [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 base.Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, last2: Iterator2, pred: (x: T, y: T) => boolean): Iterator1; + 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.

* @@ -4836,7 +5357,7 @@ declare namespace std { * @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 base.Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, last2: Iterator2): Iterator1; + function find_first_of, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, last2: Iterator2): Iterator1; /** *

Find element from set in range.

* @@ -4860,7 +5381,7 @@ declare namespace std { * @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 base.Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, last2: Iterator2, pred: (x: T, y: T) => boolean): Iterator1; + 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.

* @@ -4877,7 +5398,7 @@ declare namespace std { * @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: Iterator, last: Iterator): Iterator; + function adjacent_find>(first: InputIterator, last: InputIterator): InputIterator; /** *

Find equal adjacent elements in range.

* @@ -4897,7 +5418,7 @@ declare namespace std { * @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: Iterator, last: Iterator, pred: (x: T, y: T) => boolean): Iterator; + function adjacent_find>(first: InputIterator, last: InputIterator, pred: (x: T, y: T) => boolean): InputIterator; /** *

Search range for subsequence.

* @@ -4924,7 +5445,7 @@ declare namespace std { * 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 base.Iterator>(first1: ForwardIterator1, last1: ForwardIterator1, first2: ForwardIterator2, last2: ForwardIterator2): ForwardIterator1; + function search, ForwardIterator2 extends Iterator>(first1: ForwardIterator1, last1: ForwardIterator1, first2: ForwardIterator2, last2: ForwardIterator2): ForwardIterator1; /** *

Search range for subsequence.

* @@ -4955,7 +5476,7 @@ declare namespace std { * [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 base.Iterator>(first1: ForwardIterator1, last1: ForwardIterator1, first2: ForwardIterator2, last2: ForwardIterator2, pred: (x: T, y: T) => boolean): ForwardIterator1; + function search, ForwardIterator2 extends Iterator>(first1: ForwardIterator1, last1: ForwardIterator1, first2: ForwardIterator2, last2: ForwardIterator2, pred: (x: T, y: T) => boolean): ForwardIterator1; /** *

Search range for elements.

* @@ -5022,7 +5543,7 @@ declare namespace std { * 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 base.Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2): Pair; + function mismatch, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2): Pair; /** *

Return first position where two ranges differ.

* @@ -5048,7 +5569,7 @@ declare namespace std { * 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 base.Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, compare: (x: T, y: T) => boolean): Pair; + function mismatch, Iterator2 extends Iterator>(first1: Iterator1, last1: Iterator1, first2: Iterator2, compare: (x: T, y: T) => boolean): Pair; /** *

Count appearances of value in range.

* @@ -5064,7 +5585,7 @@ declare namespace std { * * @return The number of elements in the range [first, last) that compare equal to val. */ - function count>(first: Iterator, last: Iterator, val: T): number; + function count>(first: InputIterator, last: InputIterator, val: T): number; /** *

Return number of elements in range satisfying condition.

* @@ -5080,7 +5601,7 @@ declare namespace std { * The function shall not modify its argument. This can either be a function pointer or a function * object. */ - function count_if>(first: Iterator, last: Iterator, pred: (val: T) => boolean): number; + function count_if>(first: InputIterator, last: InputIterator, pred: (val: T) => boolean): number; /** *

Copy range of elements.

* @@ -5101,7 +5622,7 @@ declare namespace std { * * @return An iterator to the end of the destination range where elements have been copied. */ - function copy, OutputIterator extends base.Iterator>(first: InputIterator, last: InputIterator, result: OutputIterator): OutputIterator; + function copy, OutputIterator extends Iterator>(first: InputIterator, last: InputIterator, result: OutputIterator): OutputIterator; /** *

Copy elements.

* @@ -5125,7 +5646,7 @@ declare namespace std { * * @return An iterator to the end of the destination range where elements have been copied. */ - function copy_n, OutputIterator extends base.Iterator>(first: InputIterator, n: number, result: OutputIterator): OutputIterator; + function copy_n, OutputIterator extends Iterator>(first: InputIterator, n: number, result: OutputIterator): OutputIterator; /** *

Copy certain elements of range.

* @@ -5144,7 +5665,7 @@ declare namespace std { * * @return An iterator to the end of the destination range where elements have been copied. */ - function copy_if, OutputIterator extends base.Iterator>(first: InputIterator, last: InputIterator, result: OutputIterator, pred: (x: T) => boolean): OutputIterator; + function copy_if, OutputIterator extends Iterator>(first: InputIterator, last: InputIterator, result: OutputIterator, pred: (x: T) => boolean): OutputIterator; /** *

Copy range of elements backward.

* @@ -5171,7 +5692,7 @@ declare namespace std { * * @return An iterator to the first element of the destination sequence where elements have been copied. */ - function copy_backward, BidirectionalIterator2 extends base.Iterator>(first: BidirectionalIterator1, last: BidirectionalIterator1, result: BidirectionalIterator2): BidirectionalIterator2; + function copy_backward, BidirectionalIterator2 extends Iterator>(first: BidirectionalIterator1, last: BidirectionalIterator1, result: BidirectionalIterator2): BidirectionalIterator2; /** *

Fill range with value.

* @@ -5185,7 +5706,7 @@ declare namespace std { * 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; + function fill>(first: ForwardIterator, last: ForwardIterator, val: T): void; /** *

Fill sequence with value.

* @@ -5198,7 +5719,7 @@ declare namespace std { * * @return An iterator pointing to the element that follows the last element filled. */ - function fill_n>(first: OutputIterator, n: number, val: T): OutputIterator; + function fill_n>(first: OutputIterator, n: number, val: T): OutputIterator; /** *

Transform range.

* @@ -5216,7 +5737,7 @@ declare namespace std { * * @return An iterator pointing to the element that follows the last element written in the result sequence. */ - function transform, OutputIterator extends base.Iterator>(first: InputIterator, last: InputIterator, result: OutputIterator, op: (val: T) => T): OutputIterator; + function transform, OutputIterator extends Iterator>(first: InputIterator, last: InputIterator, result: OutputIterator, op: (val: T) => T): OutputIterator; /** *

Transform range.

* @@ -5237,7 +5758,7 @@ declare namespace std { * * @return An iterator pointing to the element that follows the last element written in the result sequence. */ - function transform, InputIterator2 extends base.Iterator, OutputIterator extends base.Iterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, result: OutputIterator, binary_op: (x: T, y: T) => T): OutputIterator; + function transform, InputIterator2 extends Iterator, OutputIterator extends Iterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, result: OutputIterator, binary_op: (x: T, y: T) => T): OutputIterator; /** *

Generate values for range with function.

* @@ -5251,7 +5772,7 @@ declare namespace std { * @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; + function generate>(first: ForwardIterator, last: ForwardIterator, gen: () => T): void; /** *

Generate values for sequence with function.

* @@ -5266,7 +5787,7 @@ declare namespace std { * * @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; + function generate_n>(first: ForwardIterator, n: number, gen: () => T): ForwardIterator; /** *

Remove consecutive duplicates in range.

* @@ -5289,7 +5810,7 @@ declare namespace std { * @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: Iterator, last: Iterator): Iterator; + function unique>(first: InputIterator, last: InputIterator): InputIterator; /** *

Remove consecutive duplicates in range.

* @@ -5316,7 +5837,7 @@ declare namespace std { * @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: Iterator, last: Iterator, pred: (left: t, right: t) => boolean): Iterator; + function unique>(first: InputIterator, last: InputIterator, pred: (left: t, right: t) => boolean): InputIterator; /** *

Copy range removing duplicates.

* @@ -5338,7 +5859,7 @@ declare namespace std { * * @return An iterator pointing to the end of the copied range, which contains no consecutive duplicates. */ - function unique_copy, OutputIterator extends base.Iterator>(first: InputIterator, last: InputIterator, result: OutputIterator): OutputIterator; + function unique_copy, OutputIterator extends Iterator>(first: InputIterator, last: InputIterator, result: OutputIterator): OutputIterator; /** *

Copy range removing duplicates.

* @@ -5364,7 +5885,7 @@ declare namespace std { * * @return An iterator pointing to the end of the copied range, which contains no consecutive duplicates. */ - function unique_copy, OutputIterator extends base.Iterator>(first: InputIterator, last: InputIterator, result: OutputIterator, pred: (x: T, y: T) => boolean): OutputIterator; + function unique_copy, OutputIterator extends Iterator>(first: InputIterator, last: InputIterator, result: OutputIterator, pred: (x: T, y: T) => boolean): OutputIterator; /** *

Remove value from range.

* @@ -5385,7 +5906,7 @@ declare namespace std { * first but not the element pointed by last. * @param val Value to be removed. */ - function remove>(first: Iterator, last: Iterator, val: T): Iterator; + function remove>(first: InputIterator, last: InputIterator, val: T): InputIterator; /** *

Remove elements from range.

* @@ -5408,7 +5929,7 @@ declare namespace std { * 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: Iterator, last: Iterator, pred: (left: T) => boolean): Iterator; + function remove_if>(first: InputIterator, last: InputIterator, pred: (left: T) => boolean): InputIterator; /** *

Copy range removing value.

* @@ -5432,7 +5953,7 @@ declare namespace std { * @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.Iterator>(first: InputIterator, last: InputIterator, result: OutputIterator, val: T): OutputIterator; + function remove_copy, OutputIterator extends Iterator>(first: InputIterator, last: InputIterator, result: OutputIterator, val: T): OutputIterator; /** *

Copy range removing values.

* @@ -5456,7 +5977,7 @@ declare namespace std { * @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.Iterator>(first: InputIterator, last: InputIterator, result: OutputIterator, pred: (val: T) => boolean): OutputIterator; + function remove_copy_if, OutputIterator extends Iterator>(first: InputIterator, last: InputIterator, result: OutputIterator, pred: (val: T) => boolean): OutputIterator; /** *

Replace value in range.

* @@ -5472,7 +5993,7 @@ declare namespace std { * @param old_val Value to be replaced. * @param new_val Replacement value. */ - function replace>(first: Iterator, last: Iterator, old_val: T, new_val: T): void; + function replace>(first: InputIterator, last: InputIterator, old_val: T, new_val: T): void; /** *

Replace value in range.

* @@ -5488,7 +6009,7 @@ declare namespace std { * 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; + function replace_if>(first: InputIterator, last: InputIterator, pred: (val: T) => boolean, new_val: T): void; /** *

Copy range replacing value.

* @@ -5512,7 +6033,7 @@ declare namespace std { * * @return An iterator pointing to the element that follows the last element written in the result sequence. */ - function replace_copy, OutputIterator extends base.Iterator>(first: InputIterator, last: InputIterator, result: OutputIterator, old_val: T, new_val: T): OutputIterator; + function replace_copy, OutputIterator extends Iterator>(first: InputIterator, last: InputIterator, result: OutputIterator, old_val: T, new_val: T): OutputIterator; /** *

Copy range replacing value.

* @@ -5533,7 +6054,7 @@ declare namespace std { * * @return An iterator pointing to the element that follows the last element written in the result sequence. */ - function replace_copy_if, OutputIterator extends base.Iterator>(first: InputIterator, last: InputIterator, result: OutputIterator, pred: (val: T) => boolean, new_val: T): OutputIterator; + function replace_copy_if, OutputIterator extends Iterator>(first: InputIterator, last: InputIterator, result: OutputIterator, pred: (val: T) => boolean, new_val: T): OutputIterator; /** *

Exchange values of objects pointed to by two iterators.

* @@ -5544,7 +6065,7 @@ declare namespace std { * @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: base.Iterator, y: base.Iterator): void; + function iter_swap(x: Iterator, y: Iterator): void; /** *

Exchange values of two ranges.

* @@ -5562,7 +6083,7 @@ declare namespace std { * * @return An iterator to the last element swapped in the second sequence. */ - function swap_ranges, ForwardIterator2 extends base.Iterator>(first1: ForwardIterator1, last1: ForwardIterator1, first2: ForwardIterator2): ForwardIterator2; + function swap_ranges, ForwardIterator2 extends Iterator>(first1: ForwardIterator1, last1: ForwardIterator1, first2: ForwardIterator2): ForwardIterator2; /** *

Reverse range.

* @@ -5575,7 +6096,7 @@ declare namespace std { * 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: Iterator, last: Iterator): void; + function reverse>(first: InputIterator, last: InputIterator): void; /** *

Copy range reversed.

* @@ -5593,7 +6114,7 @@ declare namespace std { * @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.Iterator>(first: BidirectionalIterator, last: BidirectionalIterator, result: OutputIterator): OutputIterator; + function reverse_copy, OutputIterator extends Iterator>(first: BidirectionalIterator, last: BidirectionalIterator, result: OutputIterator): OutputIterator; /** *

Rotate left the elements in range.

* @@ -5609,7 +6130,7 @@ declare namespace std { * * @return An iterator pointing to the element that now contains the value previously pointed by first. */ - function rotate>(first: Iterator, middle: Iterator, last: Iterator): Iterator; + function rotate>(first: InputIterator, middle: InputIterator, last: InputIterator): InputIterator; /** *

Copy range rotated left.

* @@ -5629,7 +6150,7 @@ declare namespace std { * * @return An output iterator pointing to the end of the copied range. */ - function rotate_copy, OutputIterator extends base.Iterator>(first: ForwardIterator, middle: ForwardIterator, last: ForwardIterator, result: OutputIterator): OutputIterator; + function rotate_copy, OutputIterator extends Iterator>(first: ForwardIterator, middle: ForwardIterator, last: ForwardIterator, result: OutputIterator): OutputIterator; /** *

Randomly rearrange elements in range.

* @@ -5777,7 +6298,7 @@ declare namespace std { * * @return An iterator pointing to the element that follows the last element written in the result sequence. */ - function partial_sort_copy, RandomAccessIterator extends base.Iterator>(first: InputIterator, last: InputIterator, result_first: RandomAccessIterator, result_last: RandomAccessIterator): RandomAccessIterator; + function partial_sort_copy, RandomAccessIterator extends Iterator>(first: InputIterator, last: InputIterator, result_first: RandomAccessIterator, result_last: RandomAccessIterator): RandomAccessIterator; /** *

Copy and partially sort range.

* @@ -5806,7 +6327,7 @@ declare namespace std { * * @return An iterator pointing to the element that follows the last element written in the result sequence. */ - function partial_sort_copy, RandomAccessIterator extends base.Iterator>(first: InputIterator, last: InputIterator, result_first: RandomAccessIterator, result_last: RandomAccessIterator, compare: (x: T, y: T) => boolean): RandomAccessIterator; + 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.

* @@ -5823,7 +6344,7 @@ declare namespace std { * 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; + function is_sorted>(first: ForwardIterator, last: ForwardIterator): boolean; /** *

Check whether range is sorted.

* @@ -5844,7 +6365,7 @@ declare namespace std { * 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; + function is_sorted>(first: ForwardIterator, last: ForwardIterator, compare: (x: T, y: T) => boolean): boolean; /** *

Find first unsorted element in range.

* @@ -5869,7 +6390,7 @@ declare namespace std { * @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; + function is_sorted_until>(first: ForwardIterator, last: ForwardIterator): ForwardIterator; /** *

Find first unsorted element in range.

* @@ -5894,7 +6415,7 @@ declare namespace std { * @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; + function is_sorted_until>(first: ForwardIterator, last: ForwardIterator, compare: (x: T, y: T) => boolean): ForwardIterator; /** *

Return iterator to lower bound.

* @@ -5923,7 +6444,7 @@ declare namespace std { * @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; + function lower_bound>(first: ForwardIterator, last: ForwardIterator, val: T): ForwardIterator; /** *

Return iterator to lower bound.

* @@ -5955,7 +6476,7 @@ declare namespace std { * @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; + function lower_bound>(first: ForwardIterator, last: ForwardIterator, val: T, compare: (x: T, y: T) => boolean): ForwardIterator; /** *

Return iterator to upper bound.

* @@ -5984,7 +6505,7 @@ declare namespace std { * @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; + function upper_bound>(first: ForwardIterator, last: ForwardIterator, val: T): ForwardIterator; /** *

Return iterator to upper bound.

* @@ -6016,7 +6537,7 @@ declare namespace std { * @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; + function upper_bound>(first: ForwardIterator, last: ForwardIterator, val: T, compare: (x: T, y: T) => boolean): ForwardIterator; /** *

Get subrange of equal elements.

* @@ -6046,7 +6567,7 @@ declare namespace std { * 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; + function equal_range>(first: ForwardIterator, last: ForwardIterator, val: T): Pair; /** *

Get subrange of equal elements.

* @@ -6079,7 +6600,7 @@ declare namespace std { * 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; + function equal_range>(first: ForwardIterator, last: ForwardIterator, val: T, compare: (x: T, y: T) => boolean): Pair; /** *

Get subrange of equal elements.

* @@ -6107,7 +6628,7 @@ declare namespace std { * * @return true if an element equivalent to val is found, and false otherwise. */ - function binary_search>(first: ForwardIterator, last: ForwardIterator, val: T): boolean; + function binary_search>(first: ForwardIterator, last: ForwardIterator, val: T): boolean; /** *

Get subrange of equal elements.

* @@ -6138,7 +6659,7 @@ declare namespace std { * * @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; + function binary_search>(first: ForwardIterator, last: ForwardIterator, val: T, compare: (x: T, y: T) => boolean): boolean; /** *

Test whether range is partitioned.

* @@ -6160,7 +6681,7 @@ declare namespace std { * 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; + function is_partitioned>(first: InputIterator, last: InputIterator, pred: (x: T) => boolean): boolean; /** *

Partition range in two.

* @@ -6183,7 +6704,7 @@ declare namespace std { * @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; + function partition>(first: BidirectionalIterator, last: BidirectionalIterator, pred: (x: T) => boolean): BidirectionalIterator; /** *

Partition range in two - stable ordering.

* @@ -6205,7 +6726,7 @@ declare namespace std { * @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; + function stable_partition>(first: BidirectionalIterator, last: BidirectionalIterator, pred: (x: T) => boolean): BidirectionalIterator; /** *

Partition range into two.

* @@ -6231,7 +6752,7 @@ declare namespace std { * 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.Iterator, OutputIterator2 extends base.Iterator>(first: InputIterator, last: InputIterator, result_true: OutputIterator1, result_false: OutputIterator2, pred: (val: T) => T): Pair; + function partition_copy, OutputIterator1 extends Iterator, OutputIterator2 extends Iterator>(first: InputIterator, last: InputIterator, result_true: OutputIterator1, result_false: OutputIterator2, pred: (val: T) => T): Pair; /** *

Get partition point.

* @@ -6256,7 +6777,7 @@ declare namespace std { * @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; + function partition_point>(first: ForwardIterator, last: ForwardIterator, pred: (x: T) => boolean): ForwardIterator; /** *

Merge sorted ranges.

* @@ -6278,7 +6799,7 @@ declare namespace std { * * @return An iterator pointing to the past-the-end element in the resulting sequence. */ - function merge, InputIterator2 extends base.Iterator, OutputIterator extends base.Iterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator): OutputIterator; + function merge, InputIterator2 extends Iterator, OutputIterator extends Iterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator): OutputIterator; /** *

Merge sorted ranges.

* @@ -6304,7 +6825,7 @@ declare namespace std { * * @return An iterator pointing to the past-the-end element in the resulting sequence. */ - function merge, InputIterator2 extends base.Iterator, OutputIterator extends base.Iterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator, compare: (x: T, y: T) => boolean): OutputIterator; + function merge, InputIterator2 extends Iterator, OutputIterator extends Iterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator, compare: (x: T, y: T) => boolean): OutputIterator; /** *

Merge consecutive sorted ranges.

* @@ -6326,7 +6847,7 @@ declare namespace std { * 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; + function inplace_merge>(first: BidirectionalIterator, middle: BidirectionalIterator, last: BidirectionalIterator): void; /** *

Merge consecutive sorted ranges.

* @@ -6352,7 +6873,7 @@ declare namespace std { * 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; + function inplace_merge>(first: BidirectionalIterator, middle: BidirectionalIterator, last: BidirectionalIterator, compare: (x: T, y: T) => boolean): void; /** *

Test whether sorted range includes another sorted range.

* @@ -6377,7 +6898,7 @@ declare namespace std { * [first1, last1), false otherwise. If [first2, last2) is an empty * range, the function returns true. */ - function includes, InputIterator2 extends base.Iterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2): boolean; + function includes, InputIterator2 extends Iterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2): boolean; /** *

Test whether sorted range includes another sorted range.

* @@ -6406,7 +6927,7 @@ declare namespace std { * [first1, last1), false otherwise. If [first2, last2) is an empty * range, the function returns true. */ - function includes, InputIterator2 extends base.Iterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, compare: (x: T, y: T) => boolean): boolean; + 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.

* @@ -6435,7 +6956,7 @@ declare namespace std { * * @return An iterator to the end of the constructed range. */ - function set_union, InputIterator2 extends base.Iterator, OutputIterator extends base.Iterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator): OutputIterator; + function set_union, InputIterator2 extends Iterator, OutputIterator extends Iterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator): OutputIterator; /** *

Union of two sorted ranges.

* @@ -6468,7 +6989,7 @@ declare namespace std { * * @return An iterator to the end of the constructed range. */ - function set_union, InputIterator2 extends base.Iterator, OutputIterator extends base.Iterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator, compare: (x: T, y: T) => boolean): OutputIterator; + function set_union, InputIterator2 extends Iterator, OutputIterator extends Iterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator, compare: (x: T, y: T) => boolean): OutputIterator; /** *

Intersection of two sorted ranges.

* @@ -6496,7 +7017,7 @@ declare namespace std { * * @return An iterator to the end of the constructed range. */ - function set_intersection, InputIterator2 extends base.Iterator, OutputIterator extends base.Iterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator): OutputIterator; + function set_intersection, InputIterator2 extends Iterator, OutputIterator extends Iterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator): OutputIterator; /** *

Intersection of two sorted ranges.

* @@ -6528,7 +7049,7 @@ declare namespace std { * * @return An iterator to the end of the constructed range. */ - function set_intersection, InputIterator2 extends base.Iterator, OutputIterator extends base.Iterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator, compare: (x: T, y: T) => boolean): OutputIterator; + function set_intersection, InputIterator2 extends Iterator, OutputIterator extends Iterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator, compare: (x: T, y: T) => boolean): OutputIterator; /** *

Difference of two sorted ranges.

* @@ -6562,7 +7083,7 @@ declare namespace std { * * @return An iterator to the end of the constructed range. */ - function set_difference, InputIterator2 extends base.Iterator, OutputIterator extends base.Iterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator): OutputIterator; + function set_difference, InputIterator2 extends Iterator, OutputIterator extends Iterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator): OutputIterator; /** *

Difference of two sorted ranges.

* @@ -6600,7 +7121,7 @@ declare namespace std { * * @return An iterator to the end of the constructed range. */ - function set_difference, InputIterator2 extends base.Iterator, OutputIterator extends base.Iterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator, compare: (x: T, y: T) => boolean): OutputIterator; + function set_difference, InputIterator2 extends Iterator, OutputIterator extends Iterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator, compare: (x: T, y: T) => boolean): OutputIterator; /** *

Symmetric difference of two sorted ranges.

* @@ -6634,7 +7155,7 @@ declare namespace std { * * @return An iterator to the end of the constructed range. */ - function set_symmetric_difference, InputIterator2 extends base.Iterator, OutputIterator extends base.Iterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator): OutputIterator; + function set_symmetric_difference, InputIterator2 extends Iterator, OutputIterator extends Iterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator): OutputIterator; /** *

Symmetric difference of two sorted ranges.

* @@ -6668,7 +7189,7 @@ declare namespace std { * * @return An iterator to the end of the constructed range. */ - function set_symmetric_difference, InputIterator2 extends base.Iterator, OutputIterator extends base.Iterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator, compare: (x: T, y: T) => boolean): OutputIterator; + function set_symmetric_difference, InputIterator2 extends Iterator, OutputIterator extends Iterator>(first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, result: OutputIterator, compare: (x: T, y: T) => boolean): OutputIterator; /** *

Return the smallest.

* @@ -6717,7 +7238,7 @@ declare namespace std { * * @return An iterator to smallest value in the range, or last if the range is empty. */ - function min_element>(first: ForwardIterator, last: ForwardIterator): ForwardIterator; + function min_element>(first: ForwardIterator, last: ForwardIterator): ForwardIterator; /** *

Return smallest element in range.

* @@ -6738,7 +7259,7 @@ declare namespace std { * * @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; + function min_element>(first: ForwardIterator, last: ForwardIterator, compare: (x: T, y: T) => boolean): ForwardIterator; /** *

Return largest element in range.

* @@ -6756,7 +7277,7 @@ declare namespace std { * * @return An iterator to largest value in the range, or last if the range is empty. */ - function max_element>(first: ForwardIterator, last: ForwardIterator): ForwardIterator; + function max_element>(first: ForwardIterator, last: ForwardIterator): ForwardIterator; /** *

Return largest element in range.

* @@ -6777,7 +7298,7 @@ declare namespace std { * * @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; + function max_element>(first: ForwardIterator, last: ForwardIterator, compare: (x: T, y: T) => boolean): ForwardIterator; /** *

Return smallest and largest elements in range.

* @@ -6803,7 +7324,7 @@ declare namespace std { * @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; + function minmax_element>(first: ForwardIterator, last: ForwardIterator): Pair; /** *

Return smallest and largest elements in range.

* @@ -6829,7 +7350,7 @@ declare namespace std { * @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; + function minmax_element>(first: ForwardIterator, last: ForwardIterator, compare: (x: T, y: T) => boolean): Pair; } declare namespace std { /** @@ -7314,22 +7835,6 @@ declare namespace std { const _20: PlaceHolder; } } -declare namespace std { - /** - *

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: Iterator, last: Iterator): number; -} declare namespace std { /** *

Standard exception class.

@@ -7339,10 +7844,9 @@ declare namespace std { *

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/ - *
+ *

* + * @reference http://www.cplusplus.com/reference/exception/exception * @author Jeongho Nam */ class Exception { @@ -7380,10 +7884,9 @@ declare namespace std { * *

It is used as a base class for several logical error exceptions.

* - *
    - *
  • Reference: http://www.cplusplus.com/reference/stdexcept/logic_error/ - *
+ *

* + * @reference http://www.cplusplus.com/reference/stdexcept/logic_error * @author Jeongho Nam */ class LogicError extends Exception { @@ -7406,10 +7909,9 @@ declare namespace std { *

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/ - *
+ *

* + * @reference http://www.cplusplus.com/reference/stdexcept/domain_error * @author Jeongho Nam */ class DomainError extends LogicError { @@ -7428,10 +7930,9 @@ declare namespace std { *

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/ - *
+ *

* + * @reference http://www.cplusplus.com/reference/stdexcept/invalid_argument * @author Jeongho Nam */ class InvalidArgument extends LogicError { @@ -7450,10 +7951,9 @@ declare namespace std { *

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/ - *
+ *

* + * @reference http://www.cplusplus.com/reference/stdexcept/length_error * @author Jeongho Nam */ class LengthError extends LogicError { @@ -7473,10 +7973,9 @@ declare namespace std { * 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/ - *
+ *

* + * @reference http://www.cplusplus.com/reference/stdexcept/out_of_range * @author Jeongho Nam */ class OutOfRange extends LogicError { @@ -7495,10 +7994,9 @@ declare namespace std { * *

It is used as a base class for several runtime error exceptions.

* - *
    - *
  • Reference: http://www.cplusplus.com/reference/stdexcept/runtime_error/ - *
+ *

* + * @reference http://www.cplusplus.com/reference/stdexcept/runtime_error * @author Jeongho Nam */ class RuntimeError extends Exception { @@ -7517,10 +8015,9 @@ declare namespace std { *

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/outflow_error/ - *
+ *

* + * @reference http://www.cplusplus.com/reference/stdexcept/outflow_error * @author Jeongho Nam */ class OverflowError extends RuntimeError { @@ -7539,10 +8036,9 @@ declare namespace std { *

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/ - *
+ *

* + * @reference http://www.cplusplus.com/reference/stdexcept/underflow_error * @author Jeongho Nam */ class UnderflowError extends RuntimeError { @@ -7562,10 +8058,9 @@ declare namespace std { *

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/ - *
+ *

* + * @reference http://www.cplusplus.com/reference/stdexcept/range_error * @author Jeongho Nam */ class RangeError extends RuntimeError { @@ -7592,9 +8087,11 @@ declare namespace std.base { * so that they can be interpreted when needed as more abstract (and portable) * {@link ErrorCondition error conditions}.

* + *

+ * * @author Jeongho Nam */ - class ErrorInstance { + abstract class ErrorInstance { /** * A reference to an {@link ErrorCategory} object. */ @@ -7699,10 +8196,9 @@ declare namespace std { *

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/ - *
+ *

* + * @reference http://www.cplusplus.com/reference/system_error/system_error * @author Jeongho Nam */ class SystemError extends RuntimeError { @@ -7763,10 +8259,9 @@ declare namespace std { * 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/
  • - *
+ *

* + * @reference http://www.cplusplus.com/reference/system_error/error_category * @author Jeongho Nam */ abstract class ErrorCategory { @@ -7889,10 +8384,9 @@ declare namespace std { *

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/
  • - *
+ *

* + * @reference http://www.cplusplus.com/reference/system_error/error_condition * @author Jeongho Nam */ class ErrorCondition extends base.ErrorInstance { @@ -7920,10 +8414,9 @@ declare namespace std { *

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/
  • - *
+ *

* + * @reference http://www.cplusplus.com/reference/system_error/error_code * @author Jeongho Nam */ class ErrorCode extends base.ErrorInstance { @@ -7948,13 +8441,10 @@ declare namespace std { * T2). The individual values can be accessed through its public members {@link first} and * {@link second}.

* - *
    - *
  • Reference: http://www.cplusplus.com/reference/utility/pair/
  • - *
- * * @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 { @@ -8083,12 +8573,9 @@ declare namespace std.base { * 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.

* - *
    - *
  • Reference: https://en.wikipedia.org/w/index.php?title=Red%E2%80%93black_tree&redirect=no
  • - *
- * * @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 */ @@ -8114,8 +8601,8 @@ declare namespace std.base { * @return The maximum node. */ protected fetch_maximum(node: XTreeNode): XTreeNode; - abstract is_equals(left: T, right: T): boolean; abstract is_less(left: T, right: T): boolean; + abstract is_equal_to(left: T, right: T): boolean; /** *

Insert an element with a new node.

* @@ -8632,6 +9119,10 @@ declare namespace std.base { } declare namespace std.base { /** + *

A red-black Tree storing {@link SetIterator SetIterators}.

+ * + *

+ * * @author Jeongho Nam */ class AtomicTree extends XTree> { @@ -8650,7 +9141,7 @@ declare namespace std.base { /** * @inheritdoc */ - is_equals(left: SetIterator, right: SetIterator): boolean; + is_equal_to(left: SetIterator, right: SetIterator): boolean; /** * @inheritdoc */ @@ -8709,7 +9200,7 @@ declare namespace std.base { * * @author Jeongho Nam */ - class HashBuckets { + abstract class HashBuckets { private buckets_; private item_size_; /** @@ -8726,7 +9217,7 @@ declare namespace std.base { size(): number; item_size(): number; at(index: number): Vector; - private hash_index(val); + hash_index(val: T): number; insert(val: T): void; erase(val: T): void; } @@ -8761,6 +9252,8 @@ declare namespace std.base { * beginning or the end, {@link IArray} objects perform worse and have less consistent iterators and references * than {@link List Lists}

. * + *

+ * *

Container properties

*
*
Sequence
@@ -8780,7 +9273,7 @@ declare namespace std.base { * * @author Jeongho Nam */ - interface IArray extends ILinearContainer { + interface IArrayContainer extends ILinearContainer { /** *

Request a change in capacity.

* @@ -8871,10 +9364,9 @@ declare namespace std.base { *

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/
  • - *
+ *

* + * @reference http://www.cplusplus.com/reference/iterator/RandomAccessIterator * @author Jeongho Nam */ interface IArrayIterator extends Iterator { @@ -8896,11 +9388,13 @@ declare namespace std.base { } declare namespace std.base { /** - *

An interface of

+ *

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
@@ -8980,7 +9474,7 @@ declare namespace std.base { * * @return A {@link ReverseIterator reverse iterator} to the reverse beginning of the sequence */ - rbegin(): ReverseIterator; + rbegin(): base.IReverseIterator; /** *

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

* @@ -8992,7 +9486,7 @@ declare namespace std.base { * * @return A {@link ReverseIterator reverse iterator} to the reverse end of the sequence */ - rend(): ReverseIterator; + rend(): base.IReverseIterator; /** * Return the number of elements in the Container. * @@ -9082,14 +9576,18 @@ declare namespace std.base { */ swap(obj: IContainer): void; } + interface IReverseIterator extends ReverseIterator, IReverseIterator> { + } } declare namespace std.base { /** *

An interface for deque

* + *

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

Insert element at beginning.

* @@ -9111,7 +9609,9 @@ declare namespace std.base { } declare namespace std.base { /** - *

Linear

+ *

An interface for linear containers.

+ * + *

* * @author Jeonngho Nam */ @@ -9221,6 +9721,13 @@ declare namespace std.base { } } declare namespace std.base { + /** + *

Hash buckets storing {@link MapIterator MapIterators}.

+ * + *

+ * + * @author Jeongho Nam + */ class MapHashBuckets extends HashBuckets> { private map; constructor(map: MapContainer); @@ -9229,6 +9736,10 @@ declare namespace std.base { } declare namespace std.base { /** + *

A red-black Tree storing {@link MapIterator MapIterators}.

+ * + *

+ * * @author Jeongho Nam */ class PairTree extends XTree> { @@ -9247,7 +9758,7 @@ declare namespace std.base { /** * @inheritdoc */ - is_equals(left: MapIterator, right: MapIterator): boolean; + is_equal_to(left: MapIterator, right: MapIterator): boolean; /** * @inheritdoc */ @@ -9255,6 +9766,13 @@ declare namespace std.base { } } declare namespace std.base { + /** + *

Hash buckets storing {@link SetIterator SetIterators}.

+ * + *

+ * + * @author Jeongho Nam + */ class SetHashBuckets extends HashBuckets> { private set; constructor(set: SetContainer); @@ -9312,27 +9830,6 @@ declare namespace std.base { uncle: XTreeNode; } } -/** -* STL (Standard Template Library) Containers for TypeScript. -* -* @author Jeongho Nam -*/ -declare namespace std { -} -/** - * Base classes composing STL in background. - * - * @author Jeongho Nam - */ -declare namespace std.base { -} -/** - * Examples for supporting developers who use STL library. - * - * @author Jeongho Nam - */ -declare namespace std.example { -} declare namespace std.example { function test_bind(): void; } From 32e93d9fa79e9f8c239fdf365ed0a029d53c7f80 Mon Sep 17 00:00:00 2001 From: ven Date: Thu, 2 Jun 2016 14:55:22 +0200 Subject: [PATCH 157/402] fix typo (#9450) --- angularjs/angular-resource.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/angularjs/angular-resource.d.ts b/angularjs/angular-resource.d.ts index 0fb9351342..1482c3f047 100644 --- a/angularjs/angular-resource.d.ts +++ b/angularjs/angular-resource.d.ts @@ -95,7 +95,7 @@ declare namespace angular.resource { (params: Object, data: Object, success?: Function, error?: Function): IResourceArray; } - // Baseclass for everyresource with default actions. + // Baseclass for every resource with default actions. // If you define your new actions for the resource, you will need // to extend this interface and typecast the ResourceClass to it. // From 9161d4fca9b3eeeb74e011f2bfa5e53066b838c6 Mon Sep 17 00:00:00 2001 From: Peter Hajdu Date: Thu, 2 Jun 2016 15:02:58 +0200 Subject: [PATCH 158/402] fix angular-material import as module (#9451) [TypeScript error: xxx.ts(xx,xx): Error TS2307: Cannot find module 'angular-material'.] --- angular-material/angular-material.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/angular-material/angular-material.d.ts b/angular-material/angular-material.d.ts index bb144d15d4..4af35c6701 100644 --- a/angular-material/angular-material.d.ts +++ b/angular-material/angular-material.d.ts @@ -4,6 +4,12 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// + +declare module 'angular-material' { +    var _: string; +   export = _; +} + declare namespace angular.material { interface IBottomSheetOptions { From 8ef4d9a7db3fa5bdca6bf30570620bb2c70be809 Mon Sep 17 00:00:00 2001 From: Rand Scullard Date: Thu, 2 Jun 2016 09:05:18 -0400 Subject: [PATCH 159/402] Add definitions for fontfaceobserver (#9453) --- fontfaceobserver/fontfaceobserver-tests.ts | 46 +++++++++++++++++++ .../fontfaceobserver-tests.ts.tscparams | 1 + fontfaceobserver/fontfaceobserver.d.ts | 33 +++++++++++++ 3 files changed, 80 insertions(+) create mode 100644 fontfaceobserver/fontfaceobserver-tests.ts create mode 100644 fontfaceobserver/fontfaceobserver-tests.ts.tscparams create mode 100644 fontfaceobserver/fontfaceobserver.d.ts diff --git a/fontfaceobserver/fontfaceobserver-tests.ts b/fontfaceobserver/fontfaceobserver-tests.ts new file mode 100644 index 0000000000..1ea9a7a222 --- /dev/null +++ b/fontfaceobserver/fontfaceobserver-tests.ts @@ -0,0 +1,46 @@ +/// + +function test1() { + var font = new FontFaceObserver('My Family', { + weight: 400 + }); + + font.load().then(function () { + console.log('Font is available'); + }, function () { + console.log('Font is not available'); + }); +} + +function test2() { + var font = new FontFaceObserver('My Family'); + + font.load('中国').then(function () { + console.log('Font is available'); + }, function () { + console.log('Font is not available'); + }); +} + +function test3() { + var font = new FontFaceObserver('My Family'); + + font.load(null, 5000).then(function () { + console.log('Font is available'); + }, function () { + console.log('Font is not available after waiting 5 seconds'); + }); +} + +function test4() { + var fontA = new FontFaceObserver('Family A'); + var fontB = new FontFaceObserver('Family B'); + + fontA.load().then(function () { + console.log('Family A is available'); + }); + + fontB.load().then(function () { + console.log('Family B is available'); + }); +} diff --git a/fontfaceobserver/fontfaceobserver-tests.ts.tscparams b/fontfaceobserver/fontfaceobserver-tests.ts.tscparams new file mode 100644 index 0000000000..14fce22a5c --- /dev/null +++ b/fontfaceobserver/fontfaceobserver-tests.ts.tscparams @@ -0,0 +1 @@ +--target ES6 diff --git a/fontfaceobserver/fontfaceobserver.d.ts b/fontfaceobserver/fontfaceobserver.d.ts new file mode 100644 index 0000000000..8f461dbd4f --- /dev/null +++ b/fontfaceobserver/fontfaceobserver.d.ts @@ -0,0 +1,33 @@ +// Type definitions for fontfaceobserver +// Project: https://github.com/bramstein/fontfaceobserver +// Definitions by: Rand Scullard +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +declare namespace FontFaceObserver { + interface FontVariant { + weight?: number | string; + style?: string; + stretch?: string; + } +} + +declare class FontFaceObserver { + /** + * Creates a new FontFaceObserver. + * @param fontFamilyName Name of the font family to observe. + * @param variant Description of the font variant to observe. If a property is not present it will default to normal. + */ + constructor(fontFamilyName: string, variant?: FontFaceObserver.FontVariant); + + /** + * Starts observing the loading of the specified font. Immediately returns a new Promise that resolves when the font is available and rejected when the font is not available. + * @param testString If your font doesn't contain latin characters you can pass a custom test string. + * @param timeout The default timeout for giving up on font loading is 3 seconds. You can increase or decrease this by passing a number of milliseconds. + */ + load(testString?: string, timeout?: number): Promise; +} + +declare module "fontfaceobserver" { + export = FontFaceObserver; +} From f6e169d0719685d4c2cbb92a519f354e58755f0c Mon Sep 17 00:00:00 2001 From: Craig Date: Thu, 2 Jun 2016 09:09:42 -0400 Subject: [PATCH 160/402] The click event handler for the title action of Infobox entities needs to accept an optional MouseEvent input parameter (#9452) Because the Infobox title click handler is attached to an anchor tag with a hash as its destination (), the hash can cause problems in framework like Angular when used in conjunction with a void; + getTitleClickHandler(): (mouseEvent?: MouseEvent) => void; getVisible(): boolean; getWidth(): number; getZIndex(): number; @@ -329,8 +329,8 @@ declare namespace Microsoft.Maps { showPointer?: boolean; pushpin?: Pushpin; title?: string; - titleAction?: { label?: string; eventHandler: () => void; }; - titleClickHandler?: () => void; + titleAction?: { label?: string; eventHandler: (mouseEvent?: MouseEvent) => void; }; + titleClickHandler?: (mouseEvent?: MouseEvent) => void; typeName?: InfoboxType; visible?: boolean; width?: number; From 7a4bf1d15f91989c54604cd9b904c380470abf8f Mon Sep 17 00:00:00 2001 From: trevordunn Date: Thu, 2 Jun 2016 07:29:35 -0600 Subject: [PATCH 161/402] Made GET and POST variables static (#6140) (#9455) --- preloadjs/preloadjs.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/preloadjs/preloadjs.d.ts b/preloadjs/preloadjs.d.ts index 1585842356..1a9d01b1e8 100644 --- a/preloadjs/preloadjs.d.ts +++ b/preloadjs/preloadjs.d.ts @@ -20,14 +20,14 @@ declare namespace createjs { static BINARY: string; canceled: boolean; static CSS: string; - GET: string; + static GET: string; static IMAGE: string; static JAVASCRIPT: string; static JSON: string; static JSONP: string; loaded: boolean; static MANIFEST: string; - POST: string; + static POST: string; progress: number; resultFormatter: () => any; static SOUND: string; From b13eab309f2c3240a60ad8af299c84217fee613b Mon Sep 17 00:00:00 2001 From: Rajab Shakirov Date: Thu, 2 Jun 2016 16:34:54 +0300 Subject: [PATCH 162/402] init commit react-modal (#9457) --- react-modal/react-modal-tests.tsx | 49 +++++++++++++++++++++++++++++++ react-modal/react-modal.d.ts | 28 ++++++++++++++++++ 2 files changed, 77 insertions(+) create mode 100644 react-modal/react-modal-tests.tsx create mode 100644 react-modal/react-modal.d.ts diff --git a/react-modal/react-modal-tests.tsx b/react-modal/react-modal-tests.tsx new file mode 100644 index 0000000000..9a9814930d --- /dev/null +++ b/react-modal/react-modal-tests.tsx @@ -0,0 +1,49 @@ +/// +/// + +import * as React from "react"; +import ReactModal from 'react-modal'; + +class ExampleOfUsingReactModal extends React.Component<{}, {}> { + render() { + var onAfterOpenFn = () => { } + var onRequestCloseFn = () => { } + var customStyle = { + overlay: { + position: 'fixed', + top: 0, + left: 0, + right: 0, + bottom: 0, + backgroundColor: 'rgba(255, 255, 255, 0.75)' + }, + content: { + position: 'absolute', + top: '40px', + left: '40px', + right: '40px', + bottom: '40px', + border: '1px solid #ccc', + background: '#fff', + overflow: 'auto', + WebkitOverflowScrolling: 'touch', + borderRadius: '4px', + outline: 'none', + padding: '20px' + + } + } + return ( + +

Modal Content

+

Etc.

+
+ ); + } +}; \ No newline at end of file diff --git a/react-modal/react-modal.d.ts b/react-modal/react-modal.d.ts new file mode 100644 index 0000000000..2f2d0403d2 --- /dev/null +++ b/react-modal/react-modal.d.ts @@ -0,0 +1,28 @@ +// Type definitions for react-modal v1.3.0 +// Project: https://github.com/reactjs/react-modal +// Definitions by: Rajab Shakirov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "react-modal" { + interface ReactModal { + isOpen: boolean; + style?: { + content: { + [key: string]: any; + }, + overlay: { + [key: string]: any; + } + }, + appElement?: HTMLElement | {}, + onAfterOpen?: Function, + onRequestClose?: Function, + closeTimeoutMS?: number, + ariaHideApp?: boolean, + shouldCloseOnOverlayClick?: boolean + } + let ReactModal: __React.ClassicComponentClass; + export default ReactModal; +} From f1184e2e62085a204f85994128044500654af904 Mon Sep 17 00:00:00 2001 From: cbauerme Date: Thu, 2 Jun 2016 07:00:54 -0700 Subject: [PATCH 163/402] Added Sequelize Model.addScope method. (#9459) --- sequelize/sequelize-tests.ts | 4 ++++ sequelize/sequelize.d.ts | 24 ++++++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/sequelize/sequelize-tests.ts b/sequelize/sequelize-tests.ts index 6e62606e19..0f274e20a9 100644 --- a/sequelize/sequelize-tests.ts +++ b/sequelize/sequelize-tests.ts @@ -841,6 +841,10 @@ User.schema( 'special' ).create( { age : 3 }, { logging : function( ) {} } ); User.getTableName(); +User.addScope('lowAccess', { where : { parent_id : 2 } }); +User.addScope('lowAccess', function() { } ); +User.addScope('lowAccess', { where : { parent_id : 2 } }, { override: true }); + User.scope( 'lowAccess' ).count(); User.scope( { where : { parent_id : 2 } } ); diff --git a/sequelize/sequelize.d.ts b/sequelize/sequelize.d.ts index 81c7f4a165..8d058efdb2 100644 --- a/sequelize/sequelize.d.ts +++ b/sequelize/sequelize.d.ts @@ -2948,6 +2948,18 @@ declare module "sequelize" { } + /** + * AddScope Options for Model.addScope + */ + interface AddScopeOptions { + + /** + * If a scope of the same name already exists, should it be overwritten? + */ + override: boolean; + + } + /** * Scope Options for Model.scope */ @@ -3640,6 +3652,18 @@ declare module "sequelize" { */ getTableName( options? : { logging : Function } ) : string | Object; + /** + * Add a new scope to the model. This is especially useful for adding scopes with includes, when the model you want to include is not available at the time this model is defined. + * + * By default this will throw an error if a scope with that name already exists. Pass `override: true` in the options object to silence this error. + * + * @param {String} name The name of the scope. Use `defaultScope` to override the default scope + * @param {Object|Function} scope + * @param {Object} [options] + * @param {Boolean} [options.override=false] + */ + addScope( name : string, scope : FindOptions | Function, options? : AddScopeOptions ): void; + /** * Apply a scope created in `define` to the model. First let's look at how to create scopes: * ```js From 79aa209309897673e291696b52c833cc71457895 Mon Sep 17 00:00:00 2001 From: Jerome David Yackley Date: Thu, 2 Jun 2016 09:01:19 -0500 Subject: [PATCH 164/402] angular-ui-bootstrap - Added windowTopClass (#9458) Added the options parameter windowTopClass to IModalSettings. Here is the definition: https://github.com/angular-ui/bootstrap/blob/dd091488937060a8e4511fdfd6e1bbbf5d5403b7/src/modal/docs/readme.md. --- angular-ui-bootstrap/angular-ui-bootstrap.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts index 0a7b54775e..38a1c321bd 100644 --- a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts +++ b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts @@ -387,6 +387,12 @@ declare namespace angular.ui.bootstrap { * @default 'model-open' */ openedClass?: string; + + /** + * CSS class(es) to be added to the top modal window. + */ + + windowTopClass?: string; } interface IModalStackService { From a0d42d933647e096fe3d14db2fc75b6718cb9089 Mon Sep 17 00:00:00 2001 From: Nathan Brown Date: Thu, 2 Jun 2016 07:02:14 -0700 Subject: [PATCH 165/402] material-ui: Update material-ui to v0.15.0 (#9462) --- .../legacy/material-ui-0.14.4-tests.tsx | 2302 +++++ .../material-ui-0.14.4-tests.tsx.tscparams | 1 + material-ui/legacy/material-ui-0.14.4.d.ts | 8246 +++++++++++++++++ material-ui/material-ui-tests.tsx | 7159 +++++++++----- material-ui/material-ui.d.ts | 5768 ++++++------ 5 files changed, 18401 insertions(+), 5075 deletions(-) create mode 100644 material-ui/legacy/material-ui-0.14.4-tests.tsx create mode 100644 material-ui/legacy/material-ui-0.14.4-tests.tsx.tscparams create mode 100644 material-ui/legacy/material-ui-0.14.4.d.ts diff --git a/material-ui/legacy/material-ui-0.14.4-tests.tsx b/material-ui/legacy/material-ui-0.14.4-tests.tsx new file mode 100644 index 0000000000..0d112fcaa8 --- /dev/null +++ b/material-ui/legacy/material-ui-0.14.4-tests.tsx @@ -0,0 +1,2302 @@ +/// +/// +/// + +import * as React from "react"; +import * as LinkedStateMixin from "react-addons-linked-state-mixin"; +import * as MaterialUi from "material-ui"; +import ActionGrade from "material-ui/lib/svg-icons/action/grade"; +import AppBar from "material-ui/lib/app-bar"; +import ArrowDropRight from "material-ui/lib/svg-icons/navigation-arrow-drop-right"; +import AutoComplete from 'material-ui/lib/auto-complete'; +import Avatar from "material-ui/lib/avatar"; +import Badge from "material-ui/lib/badge"; +import Card from "material-ui/lib/card/card"; +import CardActions from "material-ui/lib/card/card-actions"; +import CardHeader from "material-ui/lib/card/card-header"; +import CardMedia from 'material-ui/lib/card/card-media'; +import CardText from "material-ui/lib/card/card-text"; +import CardTitle from 'material-ui/lib/card/card-title'; +import Checkbox from "material-ui/lib/checkbox"; +import CircularProgress from 'material-ui/lib/circular-progress'; +import ColorManipulator from 'material-ui/lib/utils/color-manipulator'; +import Colors from "material-ui/lib/styles/colors"; +import DatePicker from "material-ui/lib/date-picker/date-picker"; +import Dialog from "material-ui/lib/dialog"; +import Divider from 'material-ui/lib/divider'; +import DropDownMenu from "material-ui/lib/drop-down-menu"; +import FileFolder from "material-ui/lib/svg-icons/file/folder"; +import FlatButton from "material-ui/lib/flat-button"; +import FloatingActionButton from "material-ui/lib/floating-action-button"; +import FontIcon from "material-ui/lib/font-icon"; +import GridList from 'material-ui/lib/grid-list/grid-list'; +import GridTile from 'material-ui/lib/grid-list/grid-tile'; +import IconButton from "material-ui/lib/icon-button"; +import IconMenu from "material-ui/lib/menus/icon-menu"; +import LeftNav from 'material-ui/lib/left-nav'; +import LinearProgress from 'material-ui/lib/linear-progress'; +import List from 'material-ui/lib/lists/list'; +import ListItem from 'material-ui/lib/lists/list-item'; +import Menu from 'material-ui/lib/menus/menu'; +import MenuItem from 'material-ui/lib/menus/menu-item'; +import Paper from 'material-ui/lib/paper'; +import Popover from 'material-ui/lib/popover/popover'; +import PopoverAnimationFromTop from 'material-ui/lib/popover/popover-animation-from-top'; +import RadioButton from "material-ui/lib/radio-button"; +import RadioButtonGroup from "material-ui/lib/radio-button-group"; +import RaisedButton from "material-ui/lib/raised-button"; +import RefreshIndicator from 'material-ui/lib/refresh-indicator'; +import SelectField from "material-ui/lib/select-field"; +import Slider from 'material-ui/lib/slider'; +import Snackbar from 'material-ui/lib/snackbar'; +import Spacing from "material-ui/lib/styles/spacing"; +import Styles from 'material-ui/lib/styles'; +import SvgIcon from 'material-ui/lib/svg-icon'; +import Tab from 'material-ui/lib/tabs/tab'; +import Table from 'material-ui/lib/table/table'; +import TableBody from 'material-ui/lib/table/table-body'; +import TableFooter from 'material-ui/lib/table/table-footer'; +import TableHeader from 'material-ui/lib/table/table-header'; +import TableHeaderColumn from 'material-ui/lib/table/table-header-column'; +import TableRow from 'material-ui/lib/table/table-row'; +import TableRowColumn from 'material-ui/lib/table/table-row-column'; +import Tabs from 'material-ui/lib/tabs/tabs'; +import TextField from "material-ui/lib/text-field"; +import ThemeDecorator from 'material-ui/lib/styles/theme-decorator'; +import ThemeManager from 'material-ui/lib/styles/theme-manager'; +import TimePicker from "material-ui/lib/time-picker"; +import Toggle from "material-ui/lib/toggle"; +import ToggleStar from "material-ui/lib/svg-icons/toggle/star"; +import ToggleStarBorder from "material-ui/lib/svg-icons/toggle/star-border"; +import Toolbar from 'material-ui/lib/toolbar/toolbar'; +import ToolbarGroup from 'material-ui/lib/toolbar/toolbar-group'; +import ToolbarSeparator from 'material-ui/lib/toolbar/toolbar-separator'; +import ToolbarTitle from 'material-ui/lib/toolbar/toolbar-title'; +import Typography from "material-ui/lib/styles/typography"; +import zIndex from 'material-ui/lib/styles/zIndex'; + +import {SelectableContainerEnhance} from 'material-ui/lib/hoc/selectable-enhance'; + +import * as Icons from "material-ui/lib/svg-icons"; +import ActionAndroid from 'material-ui/lib/svg-icons/action/android'; +import ActionFavorite from 'material-ui/lib/svg-icons/action/favorite'; +import ActionFavoriteBorder from 'material-ui/lib/svg-icons/action/favorite-border'; +import ActionFlightTakeoff from 'material-ui/lib/svg-icons/action/flight-takeoff'; +import ActionHome from 'material-ui/lib/svg-icons/action/home'; +import ActionInfo from 'material-ui/lib/svg-icons/action/info'; +import CommunicationChatBubble from 'material-ui/lib/svg-icons/communication/chat-bubble'; +import ContentAdd from 'material-ui/lib/svg-icons/content/add'; +import ContentCopy from 'material-ui/lib/svg-icons/content/content-copy'; +import ContentDrafts from 'material-ui/lib/svg-icons/content/drafts'; +import ContentFilter from 'material-ui/lib/svg-icons/content/filter-list'; +import ContentInbox from 'material-ui/lib/svg-icons/content/inbox'; +import ContentLink from 'material-ui/lib/svg-icons/content/link'; +import ContentSend from 'material-ui/lib/svg-icons/content/send'; +import Delete from 'material-ui/lib/svg-icons/action/delete'; +import Download from 'material-ui/lib/svg-icons/file/file-download'; +import FileCloudDownload from 'material-ui/lib/svg-icons/file/cloud-download'; +import FolderIcon from 'material-ui/lib/svg-icons/file/folder-open'; +import HardwareVideogameAsset from 'material-ui/lib/svg-icons/hardware/videogame-asset'; +import MapsPlace from 'material-ui/lib/svg-icons/maps/place'; +import MoreVertIcon from 'material-ui/lib/svg-icons/navigation/more-vert'; +import NavigationClose from "material-ui/lib/svg-icons/navigation/close"; +import NavigationExpandMoreIcon from 'material-ui/lib/svg-icons/navigation/expand-more'; +import NotificationsIcon from 'material-ui/lib/svg-icons/social/notifications'; +import PersonAdd from 'material-ui/lib/svg-icons/social/person-add'; +import RemoveRedEye from 'material-ui/lib/svg-icons/image/remove-red-eye'; +import StarBorder from 'material-ui/lib/svg-icons/toggle/star-border'; +import UploadIcon from 'material-ui/lib/svg-icons/file/cloud-upload'; + + +type CheckboxProps = __MaterialUI.CheckboxProps; +type MuiTheme = __MaterialUI.Styles.MuiTheme; +type TouchTapEvent = __MaterialUI.TouchTapEvent; + +interface MaterialUiTestsState { + showDialogStandardActions: boolean; + showDialogCustomActions: boolean; + showDialogScrollable: boolean; + value: number; + dataSource: [string]; + minDate: Date; + maxDate: Date; + autoOk: boolean; + disableYearSelection: boolean; + open: boolean; + valueSingle: string; + valueMultiple: string[]; + anchorEl: Element; + completed: number; + message: string; + autoHideDuration: number; + fixedHeader: boolean; + fixedFooter: boolean; + stripedRows: boolean; + showRowHover: boolean; + selectable: boolean; + multiSelectable: boolean; + enableSelectAll: boolean; + deselectOnClickaway: boolean; + height: string; +} + +// "http://www.material-ui.com/#/customization/themes" +let muiTheme: MuiTheme = ThemeManager.getMuiTheme({ + spacing: Spacing, + zIndex: zIndex, + fontFamily: 'Roboto, sans-serif', + palette: { + primary1Color: Colors.cyan500, + primary2Color: Colors.cyan700, + primary3Color: Colors.lightBlack, + accent1Color: Colors.pinkA200, + accent2Color: Colors.grey100, + accent3Color: Colors.grey500, + textColor: Colors.darkBlack, + alternateTextColor: Colors.white, + canvasColor: Colors.white, + borderColor: Colors.grey300, + disabledColor: ColorManipulator.fade(Colors.darkBlack, 0.3), + pickerHeaderColor: Colors.cyan500, + } +}); + +let SelectableList = SelectableContainerEnhance(List); + +@ThemeDecorator(muiTheme) +class MaterialUiTests extends React.Component<{}, MaterialUiTestsState> implements React.LinkedStateMixin { + + // injected with mixin + linkState: (key: string) => React.ReactLink; + + private picker12hr: TimePicker; + private picker24hr: TimePicker; + + private touchTapEventHandler(e: TouchTapEvent) { + console.info("Received touch tap", e); + } + private formEventHandler(e: React.FormEvent) { + } + private selectFieldChangeHandler(e: TouchTapEvent, si: number, mi: any) { + } + private handleRequestClose(buttonClicked: boolean) { + } + private handleRequestCloseReason(reason: string) { + } + private handleToggle() { + this.setState(Object.assign({}, this.state, { open: !this.state.open })); + } + private handleClose() { + this.setState(Object.assign({}, this.state, { open: false })); + } + private handleChangeSingle(event: React.MouseEvent, value: string){ + } + private handleChangeMultiple(event: React.MouseEvent, value: string[]) { + } + + private handleChange = (e: TouchTapEvent, index: number, value: number) => this.setState(Object.assign({}, this.state, { value })); + + private handleUpdateInput(t: string) { + this.setState(Object.assign({}, this.state, { + dataSource: [t, t + t, t + t + t], + })); + } + private handleTouchTap(e: TouchTapEvent) { + alert('onTouchTap triggered on the title component'); + } + private handleActionTouchTap() { + this.setState(Object.assign({}, this.state, {open: false,})); + alert('Event removed from your calendar.'); + } + private handleChangeDuration = (event: React.FormEvent) => { + const value = event.target["value"]; + this.setState(Object.assign({}, this.state, { + autoHideDuration: value.length > 0 ? parseInt(value) : 0, + })); + } + private onRowSelection(selectedRows: number[] | string) { + } + private handleActive(tab: Tab) { + alert(`A tab with this route property ${tab.props.value} was activated.`); + } + private handleChangeTabs(value: any, e: React.FormEvent, tab: Tab) { + } + private handleChangeTimePicker12(err, time) { + this.picker12hr.setTime(time); + }; + + private handleChangeTimePicker24(err, time) { + this.picker24hr.setTime(time); + }; + + render() { + + const styles = { + title: { + cursor: 'pointer', + }, + exampleImageInput: { + cursor: 'pointer', + position: 'absolute', + top: 0, + bottom: 0, + right: 0, + left: 0, + width: '100%', + opacity: 0, + }, + button: { + margin: 12, + }, + floatingButton: { + marginRight: 20, + }, + textField: { + marginLeft: 20, + }, + floatLeft: { + float: 'left', + }, + root: { + display: 'flex', + flexWrap: 'wrap', + justifyContent: 'space-around', + }, + gridList: { + width: 500, + height: 400, + overflowY: 'auto', + marginBottom: 24, + }, + icons: { + marginRight: 24, + }, + menu: { + marginRight: 32, + marginBottom: 32, + float: 'left', + position: 'relative', + zIndex: 0, + }, + rightIcon: { + textAlign: 'center', + lineHeight: '24px', + }, + paper: { + height: 100, + width: 100, + margin: 20, + textAlign: 'center', + display: 'inline-block', + }, + popover: { + padding: 20, + }, + container: { + position: 'relative', + }, + refresh: { + display: 'inline-block', + position: 'relative', + }, + block: { + maxWidth: 250, + }, + checkbox: { + marginBottom: 16, + }, + radioButton: { + marginBottom: 16, + }, + toggle: { + marginBottom: 16, + }, + propContainerStyle: { + width: 200, + overflow: 'hidden', + margin: '20px auto 0', + }, + propToggleHeader: { + margin: '20px auto 10px', + }, + headline: { + fontSize: 24, + paddingTop: 16, + marginBottom: 12, + fontWeight: 400, + }, + errorStyle: { + color: Colors.orange500, + }, + underlineStyle: { + borderColor: Colors.orange500, + }, + }; + const colors = Styles.Colors; + + // "http://www.material-ui.com/#/customization/inline-styles" + let element: React.ReactElement; + element = + element = React.createElement(Checkbox, { + id: "checkboxId1", name: "checkboxName1", value: "checkboxValue1", label: "went for a run today", style: { + width: '50%', + margin: '0 auto' + }, iconStyle: { + fill: '#FF4081' + } + }); + + // "http://www.material-ui.com/#/components/app-bar" + const AppBarExampleIcon = () => ( + + ); + + const AppBarExampleIconButton = () => ( + Title} + onTitleTouchTap={this.handleTouchTap} + iconElementLeft={} + iconElementRight={} + /> + ); + const AppBarExampleIconMenu = () => ( + } + iconElementRight={ + + } + targetOrigin={{ horizontal: 'right', vertical: 'top' }} + anchorOrigin={{ horizontal: 'right', vertical: 'top' }} + > + + + + + } + /> + ); + + // "http://www.material-ui.com/#/components/auto-complete" + element = + + const dataSource1 = [ + { + text: 'text-value1', + value: ( + + ), + }, + { + text: 'text-value2', + value: ( + + ), + }, + ]; + + const dataSource2 = ['12345', '23456', '34567']; + + const AutoCompleteExampleNoFilter = () => ( +
+
+ +
+ ); + + const AutoCompleteExampleFilters = () => ( +
+ +
+ +
+ ); + + // "http://www.material-ui.com/#/components/avatar" + const AvatarExampleSimple = () => ( + + + } + > + Image Avatar + + } /> + } + > + FontIcon Avatar + + } + color={colors.blue300} + backgroundColor={colors.indigo900} + /> + } + > + FontIcon Avatar with custom colors + + } /> + } + > + SvgIcon Avatar + + } + color={colors.orange200} + backgroundColor={colors.pink400} + /> + } + > + SvgIcon Avatar with custom colors + + A} + > + Letter Avatar + + + A + + } + > + Letter Avatar with custom colors + + + ); + + //image avatar + element = ; + //SvgIcon avatar + element = } />; + //SvgIcon avatar with custom colors + element = } + color={Colors.orange200} + backgroundColor={Colors.pink400} />; + //FontIcon avatar + element = + } />; + //FontIcon avatar with custom colors + element = } + color={Colors.blue300} + backgroundColor={Colors.indigo900} />; + //Letter avatar + element = A; + //Letter avatar with custom colors + element = + + + // "http://www.material-ui.com/#/components/badge" + const BadgeExampleSimple = () => ( +
+ + + + + + + + +
+ ); + const BadgeExampleContent = () => ( +
+ } + > + + + + Company Name + +
+ ); + + // "http://www.material-ui.com/#/components/flat-button" + const FlatButtonExampleSimple = () => ( +
+ + + + +
+ ); + const FlatButtonExampleComplex = () => ( +
+ + + + + } + /> + + } + /> + +
+ ); + + // "http://www.material-ui.com/#/components/raised-button" + const RaisedButtonExampleSimple = () => ( +
+ + + + +
+ ); + const RaisedButtonExampleComplex = () => ( +
+ + + + } + style={styles.button} + /> + } + /> +
+ ); + + // "http://www.material-ui.com/#/components/floating-action-button" + const FloatingActionButtonExampleSimple = () => ( +
+ + + + + + + + + + + + + + + + + + + + + + + +
+ ); + + // "http://www.material-ui.com/#/components/icon-button" + const IconButtonExampleSimple = () => ( +
+ + +
+ ); + const IconButtonExampleComplex = () => ( +
+ + + + + + + + + + home + +
+ ); + const IconButtonExampleTooltip = () => ( +
+ + + + + + +
+ ); + const IconButtonExampleTouch = () => ( +
+ + + + + + + + + + + + + + + + + + +
+ ); + //Method 1: muidocs-icon-github is defined in a style sheet. + element = ; + //Method 2: ActionGrade is a component created using mui.SvgIcon. + element = + + ; + //Method 3: Manually creating a mui.FontIcon component within IconButton + element = + + ; + //Method 4: Using Google material-icons + element = settings_system_daydream; + + + // "http://www.material-ui.com/#/components/card" + const CardExampleWithAvatar = () => ( + + + } + > + + + + + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + Donec mattis pretium massa.Aliquam erat volutpat.Nulla facilisi. + Donec vulputate interdum sollicitudin.Nunc lacinia auctor quam sed pellentesque. + Aliquam dui mauris, mattis quis lacus id, pellentesque lobortis odio. + + + + + + + ); + const CardExampleWithoutAvatar = () => ( + + + + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + Donec mattis pretium massa.Aliquam erat volutpat.Nulla facilisi. + Donec vulputate interdum sollicitudin.Nunc lacinia auctor quam sed pellentesque. + Aliquam dui mauris, mattis quis lacus id, pellentesque lobortis odio. + + + + + + + ); + + // "http://www.material-ui.com/#/components/date-picker" + const DatePickerExampleSimple = () => ( +
+ + + +
+ ); + const DatePickerExampleInline = () => ( +
+ + +
+ ); + element = ( +
+ +
+ ); + element = ; + element = ; + element = ; + + // "http://material-ui.com/#/components/dialog" + let standardActions = [ + { text: 'Cancel' }, + { text: 'Submit', onTouchTap: this.touchTapEventHandler, ref: 'submit' } + ]; + + element = + The actions in this window are created from the json that's passed in. + ; + + //Custom Actions + let customActions = [ + , + + ]; + + element = + The actions in this window were passed in as an array of react objects. + ; + + element = +
+ Really long content +
+
; + + // "http://www.material-ui.com/#/components/divider" + const DividerExampleForm = () => ( + + + + + + + + + + + ); + const DividerExampleList = () => ( +
+ + + + + + + + + +
+ ); + const DividerExampleMenu = () => ( + + + + + + + ); + + + // "http://www.material-ui.com/#/components/grid-list" + const tilesData = [ + { + img: 'images/grid-list/00-52-29-429_640.jpg', + title: 'Breakfast', + author: 'jill111', + featured: false, + }]; + const GridListExampleSimple = () => ( +
+ + {tilesData.map(tile => ( + by {tile.author}} + actionIcon={} + > + + + )) } + +
+ ); + const GridListExampleComplex = () => ( +
+ + {tilesData.map(tile => ( + } + actionPosition="left" + titlePosition="top" + titleBackground="linear-gradient(to bottom, rgba(0,0,0,0.7) 0%,rgba(0,0,0,0.3) 70%,rgba(0,0,0,0) 100%)" + cols={tile.featured ? 2 : 1} + rows={tile.featured ? 2 : 1} + > + + + )) } + +
+ ); + + + element = ; + + element = GridTile} + actionPosition="left" + titlePosition="top" + titleBackground="rgba(0, 0, 0, 0.4)" + cols={2} + rows={1} + style={{ color: 'red' }}> +

Children are Required!

+
; + + + // "http://www.material-ui.com/#/components/font-icon" + const FontIconExampleSimple = () => ( +
+ + + + + +
+ ); + + const FontIconExampleIcons = () => ( +
+ home + flight_takeoff + cloud_download + videogame_asset +
+ ); + + + // "http://www.material-ui.com/#/components/svg-icon" + const HomeIcon = (props) => ( + + + + ); + + const SvgIconExampleSimple = () => ( +
+ + + +
+ ); + const SvgIconExampleIcons = () => ( +
+ + + + +
+ ); + element = ; + element = ; + element = home; + + + // "http://www.material-ui.com/#/components/left-nav" + element = ( +
+ + + Menu Item + Menu Item 2 + +
+ ); + element = ( +
+ + this.setState(Object.assign({}, this.state, { open })) } + > + Menu Item + Menu Item 2 + +
+ ); + element = ( +
+ + + + +
+ ); + + + // "http://material-ui.com/#/components/lists" + const ListExampleSimple = () => ( +
+ + } /> + } /> + } /> + } /> + } /> + + + + } /> + } /> + } /> + } /> + +
+ ); + const ListExampleChat = () => ( +
+ + } + rightIcon={} + /> + } + rightIcon={} + /> + } + rightIcon={} + /> + } + rightIcon={} + /> + } + rightIcon={} + /> + + + + } + /> + } + /> + +
+ ); + const ListExampleNested = () => ( +
+ + } /> + } /> + } + initiallyOpen={true} + primaryTogglesNestedList={true} + nestedItems={[ + } + />, + } + disabled={true} + nestedItems={[ + } />, + ]} + />, + ]} + /> + +
+ ); + const iconButtonElement = ( + + + + ); + const rightIconMenu = ( + + Reply + Forward + Delete + + ); + const ListExampleMessages = () => ( +
+ + } + rightIconButton={rightIconMenu} + primaryText="Brendan Lim" + secondaryText={ +

+ Brunch this weekend?
+ I' ll be in your neighborhood doing errands this weekend.Do you want to grab brunch? +

+ } + secondaryTextLines={2} + /> +
+
+ ); + const ListExampleSelectable = () => ( +
+ + } + nestedItems={[ + } + />, + ]} + /> + } + /> + } + /> + } + /> + +
+ ); + + + // "http://www.material-ui.com/#/components/menu" + const MenuExampleSimple = () => ( +
+ + + + + + + + + + + + +
+ ); + const MenuExampleDisable = () => ( +
+ + + + + + + + + + + + + + + + +
+ ); + const MenuExampleIcons = () => ( +
+ + } /> + } /> + } /> + + } /> + } /> + + } /> + + + + } /> + settings}/> + settings + } + /> + ¶} /> + §} /> + +
+ ); + const MenuExampleSecondary = () => ( +
+ + + + + + + + + } /> + } /> + } /> + } /> + } /> + + + + + + + + + + + + + +
+ ); + const MenuExampleNested = () => ( +
+ + + + + } + menuItems={[ + } + menuItems={[ + , + , + , + , + ]} + />, + , + , + , + ]} + /> + + + + + + +
+ ); + + + // "http://www.material-ui.com/#/components/icon-menu" + const IconMenuExampleSimple = () => ( +
+ } + anchorOrigin={{ horizontal: 'left', vertical: 'top' }} + targetOrigin={{ horizontal: 'left', vertical: 'top' }} + > + + + + + + + } + anchorOrigin={{ horizontal: 'left', vertical: 'bottom' }} + targetOrigin={{ horizontal: 'left', vertical: 'bottom' }} + > + + + + + + + } + anchorOrigin={{ horizontal: 'right', vertical: 'bottom' }} + targetOrigin={{ horizontal: 'right', vertical: 'bottom' }} + > + + + + + + + } + anchorOrigin={{ horizontal: 'right', vertical: 'top' }} + targetOrigin={{ horizontal: 'right', vertical: 'top' }} + > + + + + + + +
+ ); + element = ( +
+ } + onChange={this.handleChangeSingle} + value={this.state.valueSingle} + > + + + + + + + } + onChange={this.handleChangeMultiple} + value={this.state.valueMultiple} + multiple={true} + > + + + + + + + +
+ ); + const IconMenuExampleScrollable = () => ( +
} + anchorOrigin={{ horizontal: 'left', vertical: 'top' }} + targetOrigin={{ horizontal: 'left', vertical: 'top' }} + maxHeight={272} + > + + + + ); + + + // "http://www.material-ui.com/#/components/dropdown-menu" + element = + + + + + + ; + const menuItems = []; + element = ( + + {menuItems} + + ); + element = ( + + + + + + + ); + + // "http://material-ui.com/#/components/paper" + const PaperExampleSimple = () => ( +
+ + + + + +
+ ); + const PaperExampleRounded = () => ( +
+ + + + + +
+ ); + const PaperExampleCircle = () => ( +
+ + + + + +
+ ); + + + // "http://www.material-ui.com/#/components/popover" + element = ( +
+ + +
+ +
+
+
+ ); + element = ( +
+ + +
+ +
+
+
+ ); + + + // "http://www.material-ui.com/#/components/circular-progress" + const CircularProgressExampleSimple = () => ( +
+ + + +
+ ); + element = ( +
+ + + +
+ ); + + + // "http://www.material-ui.com/#/components/linear-progress" + const LinearProgressExampleSimple = () => ( + + ); + element = ( + + ); + + + // "http://www.material-ui.com/#/components/refresh-indicator" + const RefreshIndicatorExampleSimple = () => ( +
+ + + + +
+ ); + const RefreshIndicatorExampleLoading = () => ( +
+ + +
+ ); + + + // "http://www.material-ui.com/#/components/select-field" + element = ( +
+ + + + + + + +
+ + + + +
+ ); + element = ( + + {menuItems} + + ); + element = ( + + + + + + + ); + element = ( +
+ + {menuItems} + +
+ + {menuItems} + +
+ ); + const {value} = this.state; + const night = value === 2 || value === 3; + element = ( +
+ + {menuItems} + +
+ + {menuItems} + +
+ ); + + + // "http://www.material-ui.com/#/components/slider" + const SliderExampleSimple = () => ( +
+ + + +
+ ); + const SliderExampleDisabled = () => ( +
+ + + +
+ ); + const SliderExampleStep = () => ( + + ); + + + // "http://www.material-ui.com/#/components/checkbox" + const CheckboxExampleSimple = () => ( +
+ + + + } + unCheckedIcon={} + label="Custom icon" + style={styles.checkbox} + /> + +
+ ); + + + // "http://www.material-ui.com/#/components/radio-button" + const RadioButtonExampleSimple = () => ( +
+ + + + + + + + + +
+ ); + + + // "http://www.material-ui.com/#/components/toggle" + const ToggleExampleSimple = () => ( +
+ + + + +
+ ); + + + // "http://material-ui.com/#/components/snackbar" + element = ( +
+ + +
+ ); + element = ( +
+ +
+ + +
+ ); + + // "http://www.material-ui.com/#/components/table" + element = ( + + + + ID + Name + Status + + + + + 1 + John Smith + Employed + + + 2 + Randal White + Unemployed + + + 3 + Stephanie Sanders + Employed + + + 4 + Steve Brown + Employed + + +
+ ); + const tableData = [ + { + name: 'John Smith', + status: 'Employed', + selected: true, + }, + ]; + element = ( +
+ + + + + Super Header + + + + ID + Name + Status + + + + {tableData.map( (row, index) => ( + + {index} + {row.name} + {row.status} + + ))} + + + + ID + Name + Status + + + + Super Footer + + + +
+ +
+

Table Properties

+ + + + + + +

TableBody Properties

+ + + +
+
+ ); + + // "http://www.material-ui.com/#/components/tabs" + const TabsExampleSimple = () => ( + + +
+

Tab One

+

+ This is an example tab. +

+

+ You can put any sort of HTML or react component in here. It even keeps the component state! +

+ +
+
+ +
+

Tab Two

+

+ This is another example tab. +

+
+
+ +
+

Tab Three

+

+ This is a third example tab. +

+
+
+
+ ); + element = ( + + +
+

Controllable Tab A

+

+ Tabs are also controllable if you want to programmatically pass them their values. + This allows for more functionality in Tabs such as not + having any Tab selected or assigning them different values. +

+
+
+ +
+

Controllable Tab B

+

+ This is another example of a controllable tab. Remember, if you + use controllable Tabs, you need to give all of your tabs values or else + you wont be able to select them. +

+
+
+
+ ); + const TabsExampleIcon = () => ( + + } /> + } /> + favorite} /> + + ); + + // "http://www.material-ui.com/#/components/text-field" + const TextFieldExampleSimple = () => ( +
+
+
+
+
+
+
+
+ +
+ ); + const TextFieldExampleError = () => ( +
+
+
+
+
+
+ ); + const TextFieldExampleCustomize = () => ( +
+
+
+
+ +
+ ); + const TextFieldExampleDisabled = () => ( +
+
+
+
+ +
+ ); + element = ; + + + // "http://www.material-ui.com/#/components/time-picker" + const TimePickerExampleSimple = () => ( +
+ + +
+ ); + element = ( +
+ this.picker12hr = t} + format="ampm" + hintText="12hr Format" + onChange={this.handleChangeTimePicker12} + /> + this.picker24hr = t} + format="24hr" + hintText="24hr Format" + onChange={this.handleChangeTimePicker24} + /> +
+ ); + + // "http://www.material-ui.com/#/components/toolbar" + const ToolbarExamplesSimple = () => ( + + + + + + + + + + + + + + + + + + + } + > + + + + + + + + ); + + return element; + } +} diff --git a/material-ui/legacy/material-ui-0.14.4-tests.tsx.tscparams b/material-ui/legacy/material-ui-0.14.4-tests.tsx.tscparams new file mode 100644 index 0000000000..855355b85f --- /dev/null +++ b/material-ui/legacy/material-ui-0.14.4-tests.tsx.tscparams @@ -0,0 +1 @@ +--experimentalDecorators \ No newline at end of file diff --git a/material-ui/legacy/material-ui-0.14.4.d.ts b/material-ui/legacy/material-ui-0.14.4.d.ts new file mode 100644 index 0000000000..29eeb225bd --- /dev/null +++ b/material-ui/legacy/material-ui-0.14.4.d.ts @@ -0,0 +1,8246 @@ +// Type definitions for material-ui v0.14.4 +// Project: https://github.com/callemall/material-ui +// Definitions by: Nathan Brown , Oliver Herrmann +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "material-ui" { + export import AppBar = __MaterialUI.AppBar; // require('material-ui/lib/app-bar'); + export import AppCanvas = __MaterialUI.AppCanvas; // require('material-ui/lib/app-canvas'); + export import AutoComplete = __MaterialUI.AutoComplete; // require('material-ui/lib/auto-complete'); + export import Avatar = __MaterialUI.Avatar; // require('material-ui/lib/avatar'); + export import Badge = __MaterialUI.Badge; // require('material-ui/lib/badge'); + export import BeforeAfterWrapper = __MaterialUI.BeforeAfterWrapper; // require('material-ui/lib/before-after-wrapper'); + export import Card = __MaterialUI.Card.Card; // require('material-ui/lib/card/card'); + export import CardActions = __MaterialUI.Card.CardActions; // require('material-ui/lib/card/card-actions'); + export import CardExpandable = __MaterialUI.Card.CardExpandable; // require('material-ui/lib/card/card-expandable'); + export import CardHeader = __MaterialUI.Card.CardHeader; // require('material-ui/lib/card/card-header'); + export import CardMedia = __MaterialUI.Card.CardMedia; // require('material-ui/lib/card/card-media'); + export import CardText = __MaterialUI.Card.CardText; // require('material-ui/lib/card/card-text'); + export import CardTitle = __MaterialUI.Card.CardTitle; // require('material-ui/lib/card/card-title'); + export import Checkbox = __MaterialUI.Checkbox; // require('material-ui/lib/checkbox'); + export import CircularProgress = __MaterialUI.CircularProgress; // require('material-ui/lib/circular-progress'); + export import ClearFix = __MaterialUI.ClearFix; // require('material-ui/lib/clearfix'); + export import DatePicker = __MaterialUI.DatePicker.DatePicker; // require('material-ui/lib/date-picker/date-picker'); + export import DatePickerDialog = __MaterialUI.DatePicker.DatePickerDialog; // require('material-ui/lib/date-picker/date-picker-dialog'); + export import Dialog = __MaterialUI.Dialog // require('material-ui/lib/dialog'); + export import Divider = __MaterialUI.Divider // require('material-ui/lib/divider'); + export import DropDownMenu = __MaterialUI.Menus.DropDownMenu; // require('material-ui/lib/DropDownMenu/DropDownMenu'); + export import EnhancedButton = __MaterialUI.EnhancedButton; // require('material-ui/lib/enhanced-button'); + export import FlatButton = __MaterialUI.FlatButton; // require('material-ui/lib/flat-button'); + export import FloatingActionButton = __MaterialUI.FloatingActionButton; // require('material-ui/lib/floating-action-button'); + export import FontIcon = __MaterialUI.FontIcon; // require('material-ui/lib/font-icon'); + export import GridList = __MaterialUI.GridList.GridList; // require('material-ui/lib/gridlist/grid-list'); + export import GridTile = __MaterialUI.GridList.GridTile; // require('material-ui/lib/gridlist/grid-tile'); + export import IconButton = __MaterialUI.IconButton; // require('material-ui/lib/icon-button'); + export import IconMenu = __MaterialUI.Menus.IconMenu; // require('material-ui/lib/menus/icon-menu'); + export import LeftNav = __MaterialUI.LeftNav; // require('material-ui/lib/left-nav'); + export import LinearProgress = __MaterialUI.LinearProgress; // require('material-ui/lib/linear-progress'); + export import List = __MaterialUI.Lists.List; // require('material-ui/lib/lists/list'); + export import ListDivider = __MaterialUI.Lists.ListDivider; // require('material-ui/lib/lists/list-divider'); + export import ListItem = __MaterialUI.Lists.ListItem; // require('material-ui/lib/lists/list-item'); + export import Menu = __MaterialUI.Menus.Menu; // require('material-ui/lib/menus/menu'); + export import MenuItem = __MaterialUI.Menus.MenuItem; // require('material-ui/lib/menus/menu-item'); + export import Mixins = __MaterialUI.Mixins; // require('material-ui/lib/mixins'); + export import Overlay = __MaterialUI.Overlay; // require('material-ui/lib/overlay'); + export import Paper = __MaterialUI.Paper; // require('material-ui/lib/paper'); + export import Popover = __MaterialUI.Popover.Popover; // require('material-ui/lib/popover/popover'); + export import RadioButton = __MaterialUI.RadioButton; // require('material-ui/lib/radio-button'); + export import RadioButtonGroup = __MaterialUI.RadioButtonGroup; // require('material-ui/lib/radio-button-group'); + export import RaisedButton = __MaterialUI.RaisedButton; // require('material-ui/lib/raised-button'); + export import RefreshIndicator = __MaterialUI.RefreshIndicator; // require('material-ui/lib/refresh-indicator'); + export import Ripples = __MaterialUI.Ripples; // require('material-ui/lib/ripples'); + export import SelectField = __MaterialUI.SelectField; // require('material-ui/lib/select-field'); + export import SelectableContainerEnhance = __MaterialUI.Hoc.SelectableContainerEnhance; // require('material-ui/lib/hoc/selectable-enhance'); + export import Slider = __MaterialUI.Slider; // require('material-ui/lib/slider'); + export import SvgIcon = __MaterialUI.SvgIcon; // require('material-ui/lib/svg-icon'); + export import Styles = __MaterialUI.Styles; // require('material-ui/lib/styles'); + export import Snackbar = __MaterialUI.Snackbar; // require('material-ui/lib/snackbar'); + export import Tab = __MaterialUI.Tabs.Tab; // require('material-ui/lib/tabs/tab'); + export import Tabs = __MaterialUI.Tabs.Tabs; // require('material-ui/lib/tabs/tabs'); + export import Table = __MaterialUI.Table.Table; // require('material-ui/lib/table/table'); + export import TableBody = __MaterialUI.Table.TableBody; // require('material-ui/lib/table/table-body'); + export import TableFooter = __MaterialUI.Table.TableFooter; // require('material-ui/lib/table/table-footer'); + export import TableHeader = __MaterialUI.Table.TableHeader; // require('material-ui/lib/table/table-header'); + export import TableHeaderColumn = __MaterialUI.Table.TableHeaderColumn; // require('material-ui/lib/table/table-header-column'); + export import TableRow = __MaterialUI.Table.TableRow; // require('material-ui/lib/table/table-row'); + export import TableRowColumn = __MaterialUI.Table.TableRowColumn; // require('material-ui/lib/table/table-row-column'); + export import Toggle = __MaterialUI.Toggle; // require('material-ui/lib/toggle'); + export import ThemeWrapper = __MaterialUI.ThemeWrapper; // require('material-ui/lib/theme-wrapper'); + export import TimePicker = __MaterialUI.TimePicker; // require('material-ui/lib/time-picker'); + export import TextField = __MaterialUI.TextField; // require('material-ui/lib/text-field'); + export import Toolbar = __MaterialUI.Toolbar.Toolbar; // require('material-ui/lib/toolbar/toolbar'); + export import ToolbarGroup = __MaterialUI.Toolbar.ToolbarGroup; // require('material-ui/lib/toolbar/toolbar-group'); + export import ToolbarSeparator = __MaterialUI.Toolbar.ToolbarSeparator; // require('material-ui/lib/toolbar/toolbar-separator'); + export import ToolbarTitle = __MaterialUI.Toolbar.ToolbarTitle; // require('material-ui/lib/toolbar/toolbar-title'); + export import Tooltip = __MaterialUI.Tooltip; // require('material-ui/lib/tooltip'); + export import Utils = __MaterialUI.Utils; // require('material-ui/lib/utils'); + + // svg icons + import NavigationMenu = __MaterialUI.SvgIcon; // require('material-ui/lib/svg-icon/navigation/menu'); + import NavigationChevronLeft = __MaterialUI.SvgIcon; // require('material-ui/lib/svg-icon/navigation/chevron-left'); + import NavigationChevronRight = __MaterialUI.SvgIcon; // require('material-ui/lib/svg-icon/navigation/chevron-right'); + + export const Icons: { + NavigationMenu: NavigationMenu, + NavigationChevronLeft: NavigationChevronLeft, + NavigationChevronRight: NavigationChevronRight, + }; + + // export type definitions + export type TouchTapEvent = __MaterialUI.TouchTapEvent; + export type TouchTapEventHandler = __MaterialUI.TouchTapEventHandler; + export type DialogAction = __MaterialUI.DialogAction; +} + +declare namespace __MaterialUI { + export import React = __React; + + // ReactLink is from "react/addons" + interface ReactLink { + value: T; + requestChange(newValue: T): void; + } + + // What's common between React.TouchEvent and React.MouseEvent + interface TouchTapEvent extends React.SyntheticEvent { + altKey: boolean; + ctrlKey: boolean; + getModifierState(key: string): boolean; + metaKey: boolean; + shiftKey: boolean; + } + + // What's common between React.TouchEventHandler and React.MouseEventHandler + interface TouchTapEventHandler extends React.EventHandler { } + + interface ThemeWrapperProps extends React.Props { + theme: Styles.MuiTheme; + } + export class ThemeWrapper extends React.Component { + } + + export namespace Styles { + interface AutoPrefix { + all(styles: React.CSSProperties): React.CSSProperties; + set(style: React.CSSProperties, key: string, value: string | number): void; + single(key: string): string; + singleHyphened(key: string): string; + } + export var AutoPrefix: AutoPrefix; + + interface Spacing { + iconSize?: number; + + desktopGutter?: number; + desktopGutterMore?: number; + desktopGutterLess?: number; + desktopGutterMini?: number; + desktopKeylineIncrement?: number; + desktopDropDownMenuItemHeight?: number; + desktopDropDownMenuFontSize?: number; + desktopLeftNavMenuItemHeight?: number; + desktopSubheaderHeight?: number; + desktopToolbarHeight?: number; + } + export var Spacing: Spacing; + + interface ThemePalette { + primary1Color?: string; + primary2Color?: string; + primary3Color?: string; + accent1Color?: string; + accent2Color?: string; + accent3Color?: string; + textColor?: string; + alternateTextColor?: string; + canvasColor?: string; + borderColor?: string; + disabledColor?: string; + pickerHeaderColor?: string; + clockCircleColor?: string; + shadowColor?: string; + } + interface MuiTheme { + isRtl?: boolean; + userAgent?: any; + zIndex?: zIndex; + baseTheme?: RawTheme; + rawTheme?: RawTheme; + appBar?: { + color?: string, + textColor?: string, + height?: number, + }; + avatar?: { + borderColor?: string, + } + badge?: { + color?: string, + textColor?: string, + primaryColor?: string, + primaryTextColor?: string, + secondaryColor?: string, + secondaryTextColor?: string, + }, + button?: { + height?: number, + minWidth?: number, + iconButtonSize?: number, + }, + cardText?: { + textColor?: string, + }, + checkbox?: { + boxColor?: string, + checkedColor?: string, + requiredColor?: string, + disabledColor?: string, + labelColor?: string, + labelDisabledColor?: string, + }, + datePicker?: { + color?: string, + textColor?: string, + calendarTextColor?: string, + selectColor?: string, + selectTextColor?: string, + }, + dropDownMenu?: { + accentColor?: string, + }, + flatButton?: { + color?: string, + buttonFilterColor?: string, + disabledColor?: string, + textColor?: string, + primaryTextColor?: string, + secondaryTextColor?: string, + }, + floatingActionButton?: { + buttonSize?: number, + miniSize?: number, + color?: string, + iconColor?: string, + secondaryColor?: string, + secondaryIconColor?: string, + disabledColor?: string, + disabledTextColor?: string, + }, + gridTile?: { + textColor?: string, + }, + inkBar?: { + backgroundColor?: string, + }, + leftNav?: { + width?: number, + color?: string, + }, + listItem?: { + nestedLevelDepth?: number, + }, + menu?: { + backgroundColor?: string, + containerBackgroundColor?: string, + }, + menuItem?: { + dataHeight?: number, + height?: number, + hoverColor?: string, + padding?: number, + selectedTextColor?: string, + }, + menuSubheader?: { + padding?: number, + borderColor?: string, + textColor?: string, + }, + paper?: { + backgroundColor?: string, + zDepthShadows?: string[], + }, + radioButton?: { + borderColor?: string, + backgroundColor?: string, + checkedColor?: string, + requiredColor?: string, + disabledColor?: string, + size?: number, + labelColor?: string, + labelDisabledColor?: string, + }, + raisedButton?: { + color?: string, + textColor?: string, + primaryColor?: string, + primaryTextColor?: string, + secondaryColor?: string, + secondaryTextColor?: string, + disabledColor?: string, + disabledTextColor?: string, + }, + refreshIndicator?: { + strokeColor?: string, + loadingStrokeColor?: string, + }; + slider?: { + trackSize?: number, + trackColor?: string, + trackColorSelected?: string, + handleSize?: number, + handleSizeDisabled?: number, + handleSizeActive?: number, + handleColorZero?: string, + handleFillColor?: string, + selectionColor?: string, + rippleColor?: string, + }, + snackbar?: { + textColor?: string, + backgroundColor?: string, + actionColor?: string, + }, + table?: { + backgroundColor?: string; + }; + tableHeader?: { + borderColor?: string; + }; + tableHeaderColumn?: { + textColor?: string; + height?: number; + spacing?: number; + }; + tableFooter?: { + borderColor?: string; + textColor?: string; + }; + tableRow?: { + hoverColor?: string; + stripeColor?: string; + selectedColor?: string; + textColor?: string; + borderColor?: string; + height?: number; + }; + tableRowColumn?: { + height?: number; + spacing?: number; + }; + timePicker?: { + color?: string; + textColor?: string; + accentColor?: string; + clockColor?: string; + clockCircleColor?: string; + headerColor?: string; + selectColor?: string; + selectTextColor?: string; + }; + toggle?: { + thumbOnColor?: string, + thumbOffColor?: string, + thumbDisabledColor?: string, + thumbRequiredColor?: string, + trackOnColor?: string, + trackOffColor?: string, + trackDisabledColor?: string, + labelColor?: string, + labelDisabledColor?: string + trackRequiredColor?: string, + }, + toolbar?: { + backgroundColor?: string, + height?: number, + titleFontSize?: number, + iconColor?: string, + separatorColor?: string, + menuHoverColor?: string, + }; + tabs?: { + backgroundColor?: string, + textColor?: string, + selectedTextColor?: string, + }; + textField?: { + textColor?: string; + hintColor?: string; + floatingLabelColor?: string; + disabledTextColor?: string; + errorColor?: string; + focusColor?: string; + backgroundColor?: string; + borderColor?: string; + }; + } + + interface zIndex { + menu: number; + appBar: number; + leftNavOverlay: number; + leftNav: number; + dialogOverlay: number; + dialog: number; + layer: number; + popover: number; + snackbar: number; + tooltip: number; + } + export var zIndex: zIndex; + + interface RawTheme { + spacing?: Spacing; + fontFamily?: string; + palette?: ThemePalette; + zIndex?: zIndex; + } + var lightBaseTheme: RawTheme; + var darkBaseTheme: RawTheme; + + export function ThemeDecorator(muiTheme: Styles.MuiTheme): (Component: TFunction) => TFunction; + + export function getMuiTheme(baseTheme: RawTheme, muiTheme ?: MuiTheme): MuiTheme; + + interface ThemeManager { + getMuiTheme(baseTheme: RawTheme, muiTheme?: MuiTheme): MuiTheme; + modifyRawThemeSpacing(muiTheme: MuiTheme, newSpacing: Spacing): MuiTheme; + modifyRawThemePalette(muiTheme: MuiTheme, newPaletteKeys: ThemePalette): MuiTheme; + modifyRawThemeFontFamily(muiTheme: MuiTheme, newFontFamily: string): MuiTheme; + } + export var ThemeManager: ThemeManager; + + interface Transitions { + easeOut(duration?: string, property?: string | string[], delay?: string, easeFunction?: string): string; + create(duration?: string, property?: string, delay?: string, easeFunction?: string): string; + easeOutFunction: string; + easeInOutFunction: string; + } + export var Transitions: Transitions; + + interface Typography { + textFullBlack: string; + textDarkBlack: string; + textLightBlack: string; + textMinBlack: string; + textFullWhite: string; + textDarkWhite: string; + textLightWhite: string; + + // font weight + fontWeightLight: number; + fontWeightNormal: number; + fontWeightMedium: number; + + fontStyleButtonFontSize: number; + } + export var Typography: Typography; + + export var DarkRawTheme: RawTheme; + export var LightRawTheme: RawTheme; + } + + interface AppBarProps extends React.Props { + className?: string; + iconClassNameLeft?: string; + iconClassNameRight?: string; + iconElementLeft?: React.ReactElement; + iconElementRight?: React.ReactElement; + iconStyleRight?: string; + onLeftIconButtonTouchTap?: TouchTapEventHandler; + onRightIconButtonTouchTap?: TouchTapEventHandler; + onTitleTouchTap?: TouchTapEventHandler; + showMenuIconButton?: boolean; + style?: React.CSSProperties; + title?: React.ReactNode; + titleStyle?: React.CSSProperties; + zDepth?: number; + } + export class AppBar extends React.Component{ + } + + interface AppCanvasProps extends React.Props { + } + export class AppCanvas extends React.Component { + } + + interface Origin { + horizontal: string; // oneOf(['left', 'middle', 'right']) + vertical: string; // oneOf(['top', 'center', 'bottom']) + } + + type AutoCompleteDataItem = { text: string, value: React.ReactNode } | string; + type AutoCompleteDataSource = { text: string, value: React.ReactNode }[] | string[]; + interface AutoCompleteProps extends React.Props { + anchorOrigin?: Origin; + animated?: boolean; + dataSource?: AutoCompleteDataSource; + disableFocusRipple?: boolean; + errorStyle?: React.CSSProperties; + errorText?: string; + filter?: (searchText: string, key: string, item: AutoCompleteDataItem) => boolean; + floatingLabelText?: string; + fullWidth?: boolean; + hintText?: string; + listStyle?: React.CSSProperties; + menuCloseDelay?: number; + menuProps?: any; + menuStyle?: React.CSSProperties; + onNewRequest?: (chosenRequest: string, index: number) => void; + onUpdateInput?: (searchText: string, dataSource: AutoCompleteDataSource) => void; + open?: boolean; + searchText?: string; + /** @deprecated use noFilter instead */ + showAllItems?: boolean; + style?: React.CSSProperties; + targetOrigin?: Origin; + touchTapCloseDelay?: number; + triggerUpdateOnFocus?: boolean; + /** @deprecated updateWhenFocused has been renamed to triggerUpdateOnFocus */ + updateWhenFocused?: boolean; + } + export class AutoComplete extends React.Component { + static noFilter: () => boolean; + static defaultFilter: (searchText: string, key: string) => boolean; + static caseSensitiveFilter: (searchText: string, key: string) => boolean; + static caseInsensitiveFilter: (searchText: string, key: string) => boolean; + static levenshteinDistanceFilter(distanceLessThan: number): (searchText: string, key: string) => boolean; + static fuzzyFilter: (searchText: string, key: string) => boolean; + static Item: Menus.MenuItem; + static Divider: Divider; + } + + interface AvatarProps extends React.Props { + backgroundColor?: string; + className?: string; + color?: string; + icon?: React.ReactElement; + size?: number; + src?: string; + style?: React.CSSProperties; + } + export class Avatar extends React.Component { + } + + interface BadgeProps extends React.Props { + badgeContent: React.ReactNode; + badgeStyle?: React.CSSProperties; + className?: string; + primary?: boolean; + secondary?: boolean; + style?: React.CSSProperties; + } + export class Badge extends React.Component { + } + + interface BeforeAfterWrapperProps extends React.Props { + afterElementType?: string; + afterStyle?: React.CSSProperties; + beforeElementType?: string; + beforeStyle?: React.CSSProperties; + elementType?: string; + style?: React.CSSProperties; + } + export class BeforeAfterWrapper extends React.Component { + } + + // non generally overridden elements of EnhancedButton + interface SharedEnhancedButtonProps extends React.Props { + centerRipple?: boolean; + disableFocusRipple?: boolean; + disableKeyboardFocus?: boolean; + disableTouchRipple?: boolean; + focusRippleColor?: string; + focusRippleOpacity?: number; + keyboardFocused?: boolean; + linkButton?: boolean; + onBlur?: React.FocusEventHandler; + onFocus?: React.FocusEventHandler; + onKeyboardFocus?: (e: React.FocusEvent, isKeyboardFocused: boolean) => void; + onKeyDown?: React.KeyboardEventHandler; + onKeyUp?: React.KeyboardEventHandler; + onTouchTap?: TouchTapEventHandler; + style?: React.CSSProperties; + tabIndex?: number; + touchRippleColor?: string; + touchRippleOpacity?: number; + type?: string; + } + + interface EnhancedButtonProps extends React.HTMLAttributes, SharedEnhancedButtonProps { + // container element,