From 5ce0dfb57be2b3ceaec695003bfd4aa5ab0f6981 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81kos=20Luk=C3=A1cs?= Date: Tue, 23 Jun 2015 11:07:10 +0200 Subject: [PATCH 001/345] definitions for angular-gettext v2.1.0 https://angular-gettext.rocketeer.be/ --- angular-gettext/angular-gettext-tests.ts | 55 +++++++++++++++++++ angular-gettext/angular-gettext.d.ts | 68 ++++++++++++++++++++++++ 2 files changed, 123 insertions(+) create mode 100644 angular-gettext/angular-gettext-tests.ts create mode 100644 angular-gettext/angular-gettext.d.ts diff --git a/angular-gettext/angular-gettext-tests.ts b/angular-gettext/angular-gettext-tests.ts new file mode 100644 index 000000000..5500d914e --- /dev/null +++ b/angular-gettext/angular-gettext-tests.ts @@ -0,0 +1,55 @@ +/// + +module angular_gettext_tests { + var gettextCatalog: angular_gettext.gettextCatalog; + + + // Configuring angular-gettext + // https://angular-gettext.rocketeer.be/dev-guide/configure/ + //Setting the language + gettextCatalog.setCurrentLanguage('nl'); + + //Highlighting untranslated strings + gettextCatalog.debug = true; + + + + // Marking strings in JavaScript code as translatable. + // https://angular-gettext.rocketeer.be/dev-guide/annotate-js/ + var gettext = angular_gettext.gettext; + var myString = gettext("Hello"); + + //Translating directly in JavaScript. + angular.module("myApp").controller("helloController", function (gettextCatalog) { + var translated: string = gettextCatalog.getString("Hello"); + }); + + angular.module("myApp").controller("helloController", function (gettextCatalog) { + var myString2: string = gettextCatalog.getPlural(3, "Bird", "Birds"); + }); + + var translated: string = gettextCatalog.getString("Hello {{name}}", { name: "Ruben" }); + + + // Setting strings manually + // https://angular-gettext.rocketeer.be/dev-guide/manual-setstrings/ + + angular.module("myApp").run(function (gettextCatalog: angular_gettext.gettextCatalog) { + // Load the strings automatically during initialization. + gettextCatalog.setStrings("nl", { + "Hello": "Hallo", + "One boat": ["Een boot", "{{$count}} boats"] + }); + }); + + + // Lazy-loading languages + // https://angular-gettext.rocketeer.be/dev-guide/lazy-loading/ + angular.module("myApp").controller("helloController", function ($scope, gettextCatalog: angular_gettext.gettextCatalog) { + $scope.switchLanguage = function (lang: string) { + gettextCatalog.setCurrentLanguage(lang); + gettextCatalog.loadRemote("/languages/" + lang + ".json"); + }; + }); + +} \ No newline at end of file diff --git a/angular-gettext/angular-gettext.d.ts b/angular-gettext/angular-gettext.d.ts new file mode 100644 index 000000000..01e4b070e --- /dev/null +++ b/angular-gettext/angular-gettext.d.ts @@ -0,0 +1,68 @@ +// Type definitions for angular-gettext v2.1.0 +// Project: https://angular-gettext.rocketeer.be/ +// Definitions by: Ákos Lukács https://github.com/AkosLukacs +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module angular_gettext { + interface gettextCatalog { + + ////////////// + /// Fields /// + ////////////// + + /** (default: false): Whether or not to prefix untranslated strings with [MISSING]: or a custom prefix. */ + debug: boolean; + /** (default: [MISSING]:): Custom prefix for untranslated strings. */ + debugPrefix: string; + /** (default: false): Whether or not to wrap all processed text with markers.Example output: [Welcome] */ + showTranslatedMarkers: boolean; + /** (default: [): Custom prefix to mark strings that have been run through angular-gettext. */ + translatedMarkerPrefix: string; + /** (default: ]): Custom suffix to mark strings that have been run through angular-gettext. */ + translatedMarkerSuffix: string; + /** An object of loaded translation strings.Shouldn't be used directly. */ + strings: {}; + /** The default language, in which you're application is written. This defaults to English and it's generally a bad idea to use anything else: if your language has different pluralization rules you'll end up with incorrect translations. Deprecated */ + baseLanguage: string; + + + /////////////// + /// Methods /// + /////////////// + + /** Sets the current language and makes sure that all translations get updated correctly. */ + setCurrentLanguage(lang: string); + + /** Returns the current language. */ + getCurrentLanguage(): string; + + /** Processes an object of string definitions. More details https://angular-gettext.rocketeer.be/dev-guide/manual-setstrings/ + @param language A language code. + @param strings A dictionary of strings. The format of this dictionary is: + - Keys: Singular English strings (as defined in the source files) + - Values: Either a single string for signular-only strings or an array of plural forms. */ + setStrings(language: string, strings: { [key: string]: string|string[] }); + + /** Get the correct pluralized (but untranslated) string for the value of n. */ + getStringForm(string: string, n: number): string; + + /** Translate a string with the given context. Uses Angular.JS interpolation, so something like this will do what you expect: + * var hello = gettextCatalog.getString("Hello {{name}}!", { name: "Ruben" }); + * // var hello will be "Hallo Ruben!" in Dutch. + * The context parameter is optional: pass null (or don't pass anything) if you're not using it: this skips interpolation and is a lot faster. + */ + getString(string: string, context?: any): string; + + /** Translate a plural string with the given context. */ + getPlural(n: number, string: string, stringPlural: string, context?: any): string; + + /** Load a set of translation strings from a given URL.This should be a JSON catalog generated with grunt-angular-gettext. More details https://angular-gettext.rocketeer.be/dev-guide/lazy-loading/ */ + loadRemote(url: string); + } + + /** If you have text that should be translated in your JavaScript code, wrap it with a call to a function named gettext. This module provides an injectable function to do so */ + function gettext(dummyString: string): string; +} + From 7a37cdbfbcb3576021f7e19385a93a17a3ed2ef7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81kos=20Luk=C3=A1cs?= Date: Tue, 23 Jun 2015 11:23:50 +0200 Subject: [PATCH 002/345] more type arguments + header format fix --- angular-gettext/angular-gettext-tests.ts | 13 +++++++------ angular-gettext/angular-gettext.d.ts | 12 +++++++----- 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/angular-gettext/angular-gettext-tests.ts b/angular-gettext/angular-gettext-tests.ts index 5500d914e..706fb67fe 100644 --- a/angular-gettext/angular-gettext-tests.ts +++ b/angular-gettext/angular-gettext-tests.ts @@ -12,19 +12,18 @@ module angular_gettext_tests { //Highlighting untranslated strings gettextCatalog.debug = true; - - + // Marking strings in JavaScript code as translatable. // https://angular-gettext.rocketeer.be/dev-guide/annotate-js/ var gettext = angular_gettext.gettext; var myString = gettext("Hello"); //Translating directly in JavaScript. - angular.module("myApp").controller("helloController", function (gettextCatalog) { + angular.module("myApp").controller("helloController", function (gettextCatalog: angular_gettext.gettextCatalog) { var translated: string = gettextCatalog.getString("Hello"); }); - angular.module("myApp").controller("helloController", function (gettextCatalog) { + angular.module("myApp").controller("helloController", function (gettextCatalog: angular_gettext.gettextCatalog) { var myString2: string = gettextCatalog.getPlural(3, "Bird", "Birds"); }); @@ -43,13 +42,15 @@ module angular_gettext_tests { }); + interface helloControllerScope extends ng.IScope { + switchLanguage: (lang: string) => void; + } // Lazy-loading languages // https://angular-gettext.rocketeer.be/dev-guide/lazy-loading/ - angular.module("myApp").controller("helloController", function ($scope, gettextCatalog: angular_gettext.gettextCatalog) { + angular.module("myApp").controller("helloController", function ($scope: helloControllerScope, gettextCatalog: angular_gettext.gettextCatalog) { $scope.switchLanguage = function (lang: string) { gettextCatalog.setCurrentLanguage(lang); gettextCatalog.loadRemote("/languages/" + lang + ".json"); }; }); - } \ No newline at end of file diff --git a/angular-gettext/angular-gettext.d.ts b/angular-gettext/angular-gettext.d.ts index 01e4b070e..d226801dc 100644 --- a/angular-gettext/angular-gettext.d.ts +++ b/angular-gettext/angular-gettext.d.ts @@ -1,6 +1,6 @@ // Type definitions for angular-gettext v2.1.0 // Project: https://angular-gettext.rocketeer.be/ -// Definitions by: Ákos Lukács https://github.com/AkosLukacs +// Definitions by: Ákos Lukács // Definitions: https://github.com/borisyankov/DefinitelyTyped /// @@ -24,7 +24,9 @@ declare module angular_gettext { translatedMarkerSuffix: string; /** An object of loaded translation strings.Shouldn't be used directly. */ strings: {}; - /** The default language, in which you're application is written. This defaults to English and it's generally a bad idea to use anything else: if your language has different pluralization rules you'll end up with incorrect translations. Deprecated */ + /** The default language, in which you're application is written. This defaults to English and it's generally a bad idea to use anything else: if your language has different pluralization rules you'll end up with incorrect translations. Deprecated + * @deprecreated + */ baseLanguage: string; @@ -33,7 +35,7 @@ declare module angular_gettext { /////////////// /** Sets the current language and makes sure that all translations get updated correctly. */ - setCurrentLanguage(lang: string); + setCurrentLanguage(lang: string): void; /** Returns the current language. */ getCurrentLanguage(): string; @@ -43,7 +45,7 @@ declare module angular_gettext { @param strings A dictionary of strings. The format of this dictionary is: - Keys: Singular English strings (as defined in the source files) - Values: Either a single string for signular-only strings or an array of plural forms. */ - setStrings(language: string, strings: { [key: string]: string|string[] }); + setStrings(language: string, strings: { [key: string]: string|string[] }): void; /** Get the correct pluralized (but untranslated) string for the value of n. */ getStringForm(string: string, n: number): string; @@ -59,7 +61,7 @@ declare module angular_gettext { getPlural(n: number, string: string, stringPlural: string, context?: any): string; /** Load a set of translation strings from a given URL.This should be a JSON catalog generated with grunt-angular-gettext. More details https://angular-gettext.rocketeer.be/dev-guide/lazy-loading/ */ - loadRemote(url: string); + loadRemote(url: string): ng.IHttpPromise; } /** If you have text that should be translated in your JavaScript code, wrap it with a call to a function named gettext. This module provides an injectable function to do so */ From 15c8ddaa001be3234a56f246ca0e2e5edcbf772f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81kos=20Luk=C3=A1cs?= Date: Tue, 23 Jun 2015 16:32:40 +0200 Subject: [PATCH 003/345] rename module from angular_gettext to angular.gettext + some whitespace cleanup --- angular-gettext/angular-gettext-tests.ts | 31 ++++++++++++++---------- angular-gettext/angular-gettext.d.ts | 23 ++++++++++-------- 2 files changed, 31 insertions(+), 23 deletions(-) diff --git a/angular-gettext/angular-gettext-tests.ts b/angular-gettext/angular-gettext-tests.ts index 706fb67fe..9a10f1062 100644 --- a/angular-gettext/angular-gettext-tests.ts +++ b/angular-gettext/angular-gettext-tests.ts @@ -1,39 +1,44 @@ /// module angular_gettext_tests { - var gettextCatalog: angular_gettext.gettextCatalog; - + // Configuring angular-gettext // https://angular-gettext.rocketeer.be/dev-guide/configure/ //Setting the language - gettextCatalog.setCurrentLanguage('nl'); + angular.module('myApp').run(function (gettextCatalog: angular.gettext.gettextCatalog) { + gettextCatalog.setCurrentLanguage('nl'); + }); //Highlighting untranslated strings - gettextCatalog.debug = true; + angular.module('myApp').run(function (gettextCatalog: angular.gettext.gettextCatalog) { + gettextCatalog.debug = true; + }); // Marking strings in JavaScript code as translatable. - // https://angular-gettext.rocketeer.be/dev-guide/annotate-js/ - var gettext = angular_gettext.gettext; - var myString = gettext("Hello"); + // https://angular-gettext.rocketeer.be/dev-guide/annotate-js/ + angular.module("myApp").controller("helloController", function (gettext: angular.gettext.gettextFunction) { + var myString = gettext("Hello"); + }); //Translating directly in JavaScript. - angular.module("myApp").controller("helloController", function (gettextCatalog: angular_gettext.gettextCatalog) { + angular.module("myApp").controller("helloController", function (gettextCatalog: angular.gettext.gettextCatalog) { var translated: string = gettextCatalog.getString("Hello"); }); - angular.module("myApp").controller("helloController", function (gettextCatalog: angular_gettext.gettextCatalog) { + angular.module("myApp").controller("helloController", function (gettextCatalog: angular.gettext.gettextCatalog) { var myString2: string = gettextCatalog.getPlural(3, "Bird", "Birds"); }); - var translated: string = gettextCatalog.getString("Hello {{name}}", { name: "Ruben" }); - + angular.module("myApp").controller("helloController", function (gettextCatalog: angular.gettext.gettextCatalog) { + var translated: string = gettextCatalog.getString("Hello {{name}}", { name: "Ruben" }); + }); // Setting strings manually // https://angular-gettext.rocketeer.be/dev-guide/manual-setstrings/ - angular.module("myApp").run(function (gettextCatalog: angular_gettext.gettextCatalog) { + angular.module("myApp").run(function (gettextCatalog: angular.gettext.gettextCatalog) { // Load the strings automatically during initialization. gettextCatalog.setStrings("nl", { "Hello": "Hallo", @@ -47,7 +52,7 @@ module angular_gettext_tests { } // Lazy-loading languages // https://angular-gettext.rocketeer.be/dev-guide/lazy-loading/ - angular.module("myApp").controller("helloController", function ($scope: helloControllerScope, gettextCatalog: angular_gettext.gettextCatalog) { + angular.module("myApp").controller("helloController", function ($scope: helloControllerScope, gettextCatalog: angular.gettext.gettextCatalog) { $scope.switchLanguage = function (lang: string) { gettextCatalog.setCurrentLanguage(lang); gettextCatalog.loadRemote("/languages/" + lang + ".json"); diff --git a/angular-gettext/angular-gettext.d.ts b/angular-gettext/angular-gettext.d.ts index d226801dc..1a88ef164 100644 --- a/angular-gettext/angular-gettext.d.ts +++ b/angular-gettext/angular-gettext.d.ts @@ -5,13 +5,13 @@ /// -declare module angular_gettext { +declare module angular.gettext { interface gettextCatalog { - + ////////////// /// Fields /// ////////////// - + /** (default: false): Whether or not to prefix untranslated strings with [MISSING]: or a custom prefix. */ debug: boolean; /** (default: [MISSING]:): Custom prefix for untranslated strings. */ @@ -33,7 +33,7 @@ declare module angular_gettext { /////////////// /// Methods /// /////////////// - + /** Sets the current language and makes sure that all translations get updated correctly. */ setCurrentLanguage(lang: string): void; @@ -41,10 +41,11 @@ declare module angular_gettext { getCurrentLanguage(): string; /** Processes an object of string definitions. More details https://angular-gettext.rocketeer.be/dev-guide/manual-setstrings/ - @param language A language code. - @param strings A dictionary of strings. The format of this dictionary is: - - Keys: Singular English strings (as defined in the source files) - - Values: Either a single string for signular-only strings or an array of plural forms. */ + * @param language A language code. + * @param strings A dictionary of strings. The format of this dictionary is: + * - Keys: Singular English strings (as defined in the source files) + * - Values: Either a single string for signular-only strings or an array of plural forms. + */ setStrings(language: string, strings: { [key: string]: string|string[] }): void; /** Get the correct pluralized (but untranslated) string for the value of n. */ @@ -56,7 +57,7 @@ declare module angular_gettext { * The context parameter is optional: pass null (or don't pass anything) if you're not using it: this skips interpolation and is a lot faster. */ getString(string: string, context?: any): string; - + /** Translate a plural string with the given context. */ getPlural(n: number, string: string, stringPlural: string, context?: any): string; @@ -65,6 +66,8 @@ declare module angular_gettext { } /** If you have text that should be translated in your JavaScript code, wrap it with a call to a function named gettext. This module provides an injectable function to do so */ - function gettext(dummyString: string): string; + interface gettextFunction { + (dummyString: string): string; + } } From 3ea7cf7889743b5633df96508fa38189361b466c Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Wed, 8 Jul 2015 19:22:36 +0900 Subject: [PATCH 004/345] Add missing selmicolons --- selenium-webdriver/selenium-webdriver.d.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index c4af933c9..bb7fefb3d 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -608,7 +608,7 @@ declare module webdriver { UNKNOWN_COMMAND: string; UNKNOWN_ERROR: string; UNSUPPORTED_OPERATION: string; - } + }; //endregion @@ -1464,7 +1464,7 @@ declare module webdriver { PENDING: number; REJECTED: number; RESOLVED: number; - } + }; //region Properties @@ -2030,7 +2030,7 @@ declare module webdriver { RIGHT: number; } - var Button: IButton + var Button: IButton; /** * Representations of pressable keys that aren't text. These are stored in @@ -2418,7 +2418,7 @@ declare module webdriver { HTMLUNIT: string; } - var Browser: IBrowser + var Browser: IBrowser; interface ProxyConfig { proxyType: string; @@ -4170,7 +4170,7 @@ declare module webdriver { * WebDriver wire protocol. * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol */ - getId(): webdriver.promise.Promise + getId(): webdriver.promise.Promise; /** * Schedules a command to retrieve the inner HTML of this element. From 33ae3d2f7b0dbb48b0a6366a4a0cdb7904ad684f Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Thu, 9 Jul 2015 19:08:44 +0900 Subject: [PATCH 005/345] Update WebDriver#isElementPresent, #findElement and #findElements Related: https://github.com/SeleniumHQ/selenium.git dc974c4a760176d015a96196072b6fb728100903 TODO: Add webdriver.By.Hash --- .../selenium-webdriver-tests.ts | 12 +++--- selenium-webdriver/selenium-webdriver.d.ts | 40 ++++++++----------- 2 files changed, 23 insertions(+), 29 deletions(-) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index 73ea8561e..62ef0812a 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -676,14 +676,14 @@ function TestWebDriver() { var element: webdriver.WebElement; element = driver.findElement(webdriver.By.id('ABC')); element = driver.findElement({id: 'ABC'}); - element = driver.findElement(webdriver.By.js('function(){}'), 1, 2, 3); - element = driver.findElement({js: 'function(){}'}, 1, 2, 3); + element = driver.findElement(webdriver.By.js('function(){}')); + element = driver.findElement({js: 'function(){}'}); // findElements driver.findElements(webdriver.By.className('ABC')).then(function (elements: webdriver.WebElement[]) { }); driver.findElements({ className: 'ABC' }).then(function (elements: webdriver.WebElement[]) { }); - driver.findElements(webdriver.By.js('function(){}'), 1, 2, 3).then(function (elements: webdriver.WebElement[]) { }); - driver.findElements({ js: 'function(){}' }, 1, 2, 3).then(function (elements: webdriver.WebElement[]) { }); + driver.findElements(webdriver.By.js('function(){}')).then(function (elements: webdriver.WebElement[]) { }); + driver.findElements({ js: 'function(){}' }).then(function (elements: webdriver.WebElement[]) { }); voidPromise = driver.get('http://www.google.com'); driver.getAllWindowHandles().then(function (handles: string[]) { }); @@ -696,8 +696,8 @@ function TestWebDriver() { booleanPromise = driver.isElementPresent(webdriver.By.className('ABC')); booleanPromise = driver.isElementPresent({className: 'ABC'}); - booleanPromise = driver.isElementPresent(webdriver.By.js('function(){}'), 1, 2, 3); - booleanPromise = driver.isElementPresent({js: 'function(){}'}, 1, 2, 3); + booleanPromise = driver.isElementPresent(webdriver.By.js('function(){}')); + booleanPromise = driver.isElementPresent({js: 'function(){}'}); var options: webdriver.WebDriverOptions = driver.manage(); var navigation: webdriver.WebDriverNavigation = driver.navigate(); diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index bb7fefb3d..84bbdf507 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -3867,6 +3867,7 @@ declare module webdriver { * {@code webdriver.Locator} object, or a simple JSON object whose sole key * is one of the accepted locator strategies, as defined by * {@code webdriver.Locator.Strategy}. For example, the following two statements + * The search criteria for an element may be defined using one of the * are equivalent: *
          * var e1 = driver.findElement(By.id('foo'));
@@ -3882,48 +3883,41 @@ declare module webdriver {
          * one this instance is currently focused on), a
          * {@link bot.ErrorCode.NO_SUCH_ELEMENT} error will be returned.
          *
-         * @param {!(webdriver.Locator|Object.|Element)} locatorOrElement The
-         *     locator strategy to use when searching for the element, or the actual
-         *     DOM element to be located by the server.
-         * @param {...} var_args Arguments to pass to {@code #executeScript} if using a
-         *     JavaScript locator.  Otherwise ignored.
+         * @param {!(webdriver.Locator|webdriver.By.Hash|Element|Function)} locator The
+         *     locator to use.
          * @return {!webdriver.WebElement} A WebElement that can be used to issue
          *     commands against the located element. If the element is not found, the
          *     element will be invalidated and all scheduled commands aborted.
          */
-        findElement(locatorOrElement: Locator, ...var_args: any[]): WebElementPromise;
-        findElement(locatorOrElement: any, ...var_args: any[]): WebElementPromise;
+        findElement(locatorOrElement: Locator): WebElementPromise;
+        findElement(locatorOrElement: any): WebElementPromise;
 
         /**
          * Schedules a command to test if an element is present on the page.
          *
-         * 

If given a DOM element, this function will check if it belongs to the + * If given a DOM element, this function will check if it belongs to the * document the driver is currently focused on. Otherwise, the function will * test if at least one element can be found with the given search criteria. * - * @param {!(webdriver.Locator|Object.|Element)} locatorOrElement The - * locator strategy to use when searching for the element, or the actual + * @param {!(webdriver.Locator|webdriver.By.Hash|Element| + * Function)} locatorOrElement The locator to use, or the actual * DOM element to be located by the server. - * @param {...} var_args Arguments to pass to {@code #executeScript} if using a - * JavaScript locator. Otherwise ignored. - * @return {!webdriver.promise.Promise} A promise that will resolve to whether - * the element is present on the page. + * @return {!webdriver.promise.Promise.} A promise that will resolve + * with whether the element is present on the page. */ - isElementPresent(locatorOrElement: Locator, ...var_args: any[]): webdriver.promise.Promise; - isElementPresent(locatorOrElement: any, ...var_args: any[]): webdriver.promise.Promise; + isElementPresent(locatorOrElement: Locator): webdriver.promise.Promise; + isElementPresent(locatorOrElement: any): webdriver.promise.Promise; /** * Schedule a command to search for multiple elements on the page. * - * @param {webdriver.Locator|Object.} locator The locator + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator * strategy to use when searching for the element. - * @param {...} var_args Arguments to pass to {@code #executeScript} if using a - * JavaScript locator. Otherwise ignored. - * @return {!webdriver.promise.Promise} A promise that will be resolved to an - * array of the located {@link webdriver.WebElement}s. + * @return {!webdriver.promise.Promise.>} A + * promise that will resolve to an array of WebElements. */ - findElements(locator: Locator, ...var_args: any[]): webdriver.promise.Promise; - findElements(locator: any, ...var_args: any[]): webdriver.promise.Promise; + findElements(locator: Locator): webdriver.promise.Promise; + findElements(locator: any): webdriver.promise.Promise; /** * Schedule a command to take a screenshot. The driver makes a best effort to From fa27980695ec1c948cc5fb3a79bbc98800a5f73c Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Thu, 9 Jul 2015 19:15:16 +0900 Subject: [PATCH 006/345] Add docs to webdriver.By.* (without Hash) --- selenium-webdriver/selenium-webdriver.d.ts | 87 +++++++++++++++++++++- 1 file changed, 86 insertions(+), 1 deletion(-) diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index 84bbdf507..47c27f8bd 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -4685,14 +4685,99 @@ declare module webdriver { } interface ILocatorStrategy { + /** + * Locates elements that have a specific class name. The returned locator + * is equivalent to searching for elements with the CSS selector ".clazz". + * + * @param {string} className The class name to search for. + * @return {!webdriver.Locator} The new locator. + * @see http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#classes + * @see http://www.w3.org/TR/CSS2/selector.html#class-html + */ className(value: string): Locator; + + /** + * Locates elements using a CSS selector. For browsers that do not support + * CSS selectors, WebDriver implementations may return an + * {@linkplain bot.Error.State.INVALID_SELECTOR invalid selector} error. An + * implementation may, however, emulate the CSS selector API. + * + * @param {string} selector The CSS selector to use. + * @return {!webdriver.Locator} The new locator. + * @see http://www.w3.org/TR/CSS2/selector.html + */ css(value: string): Locator; + + /** + * Locates an element by its ID. + * + * @param {string} id The ID to search for. + * @return {!webdriver.Locator} The new locator. + */ id(value: string): Locator; - js(script: any, ...var_args: any[]): (WebDriver: webdriver.WebDriver) => webdriver.promise.Promise; + + /** + * Locates link elements whose {@linkplain webdriver.WebElement#getText visible + * text} matches the given string. + * + * @param {string} text The link text to search for. + * @return {!webdriver.Locator} The new locator. + */ linkText(value: string): Locator; + + /** + * Locates an elements by evaluating a + * {@linkplain webdriver.WebDriver#executeScript JavaScript expression}. + * The result of this expression must be an element or list of elements. + * + * @param {!(string|Function)} script The script to execute. + * @param {...*} var_args The arguments to pass to the script. + * @return {function(!webdriver.WebDriver): !webdriver.promise.Promise} A new, + * JavaScript-based locator function. + */ + js(script: any, ...var_args: any[]): (WebDriver: webdriver.WebDriver) => webdriver.promise.Promise; + + /** + * Locates elements whose {@code name} attribute has the given value. + * + * @param {string} name The name attribute to search for. + * @return {!webdriver.Locator} The new locator. + */ name(value: string): Locator; + + /** + * Locates link elements whose {@linkplain webdriver.WebElement#getText visible + * text} contains the given substring. + * + * @param {string} text The substring to check for in a link's visible text. + * @return {!webdriver.Locator} The new locator. + */ partialLinkText(value: string): Locator; + + /** + * Locates elements with a given tag name. The returned locator is + * equivalent to using the + * [getElementsByTagName](https://developer.mozilla.org/en-US/docs/Web/API/Element.getElementsByTagName) + * DOM function. + * + * @param {string} text The substring to check for in a link's visible text. + * @return {!webdriver.Locator} The new locator. + * @see http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html + */ tagName(value: string): Locator; + + /** + * Locates elements matching a XPath selector. Care should be taken when + * using an XPath selector with a {@link webdriver.WebElement} as WebDriver + * will respect the context in the specified in the selector. For example, + * given the selector {@code "//div"}, WebDriver will search from the + * document root regardless of whether the locator was used with a + * WebElement. + * + * @param {string} xpath The XPath selector to use. + * @return {!webdriver.Locator} The new locator. + * @see http://www.w3.org/TR/xpath/ + */ xpath(value: string): Locator; } From ecd7cc44b78eababef1efb7978c1d92be974310d Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Thu, 9 Jul 2015 20:00:28 +0900 Subject: [PATCH 007/345] Update webdriver.Locator --- .../selenium-webdriver-tests.ts | 20 +++++++-- selenium-webdriver/selenium-webdriver.d.ts | 43 +++++++++++++++---- 2 files changed, 52 insertions(+), 11 deletions(-) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index 62ef0812a..81c9875de 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -497,15 +497,29 @@ function TestLocator() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var locator: webdriver.Locator = webdriver.By.className('class'); + var locator: webdriver.Locator = new webdriver.Locator('class name', 'class'); - var locatorStr: string = locator.toString(); + var locatorOrFn: webdriver.Locator|Function; + + locatorOrFn = webdriver.Locator.Strategy.className; + locatorOrFn = webdriver.Locator.Strategy.css; + locatorOrFn = webdriver.Locator.Strategy.id; + locatorOrFn = webdriver.Locator.Strategy.js; + locatorOrFn = webdriver.Locator.Strategy.linkText; + locatorOrFn = webdriver.Locator.Strategy.name; + locatorOrFn = webdriver.Locator.Strategy.partialLinkText; + locatorOrFn = webdriver.Locator.Strategy.tagName; + locatorOrFn = webdriver.Locator.Strategy.xpath; + + locatorOrFn = webdriver.Locator.checkLocator(locator); + locatorOrFn = webdriver.Locator.checkLocator({ className: 'class' }); + locatorOrFn = webdriver.Locator.checkLocator(Error); var using: string = locator.using; var value: string = locator.value; - var str: string = locator.toString(); + locator = webdriver.By.className('class'); locator = webdriver.By.css('css'); locator = webdriver.By.id('id'); locator = webdriver.By.linkText('link'); diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index 47c27f8bd..e9a854ac6 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -4786,9 +4786,42 @@ declare module webdriver { /** * An element locator. */ - interface Locator { + class Locator { + /** + * An element locator. + * @param {string} using The type of strategy to use for this locator. + * @param {string} value The search target of this locator. + * @constructor + */ + constructor(using: string, value: string); - //region Properties + + /** + * Maps {@link webdriver.By.Hash} keys to the appropriate factory function. + * @type {!Object.} + * @const + */ + static Strategy: { + className: typeof By.className; + css: typeof By.css; + id: typeof By.id; + js: typeof By.js; + linkText: typeof By.linkText; + name: typeof By.name; + partialLinkText: typeof By.partialLinkText; + tagName: typeof By.tagName; + xpath: typeof By.xpath; + }; + + /** + * Verifies that a {@code value} is a valid locator to use for searching for + * elements on the page. + * + * @param {*} value The value to check is a valid locator. + * @return {!(webdriver.Locator|Function)} A valid locator object or function. + * @throws {TypeError} If the given value is an invalid locator. + */ + static checkLocator(value: any): Locator | Function; /** * The search strategy to use when searching for an element. @@ -4802,14 +4835,8 @@ declare module webdriver { */ value: string; - //endregion - - //region Methods - /** @return {string} String representation of this locator. */ toString(): string; - - //endregion } /** From 03d49ee1b990f4321b904845208342794a22a7ca Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Thu, 9 Jul 2015 20:39:37 +0900 Subject: [PATCH 008/345] WIP: Add webdriver.By.Hash `webdriver.By.Hash` is a Closure Llibrary style type alias. If we assign `webdriver.By.Hash`, we get an `undefined`. I think the assignment should have an error, because it have no meanings. --- .../selenium-webdriver-tests.ts | 10 ++++++ selenium-webdriver/selenium-webdriver.d.ts | 34 +++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index 81c9875de..b296b62ee 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -528,6 +528,16 @@ function TestLocator() { locator = webdriver.By.tagName('tag'); locator = webdriver.By.xpath('xpath'); + var locatorHash: webdriver.By.Hash; + locatorHash = { className: 'class' }; + locatorHash = { css: 'css' }; + locatorHash = { id: 'id' }; + locatorHash = { linkText: 'link' }; + locatorHash = { name: 'name' }; + locatorHash = { partialLinkText: 'text' }; + locatorHash = { tagName: 'tag' }; + locatorHash = { xpath: 'xpath' }; + webdriver.By.js('script', 1, 2, 3)(driver).then(function (abc: number) { }); } diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index e9a854ac6..b170d24c5 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -4783,6 +4783,40 @@ declare module webdriver { var By: ILocatorStrategy; + module By { + /** + * Short-hand expressions for the primary element locator strategies. + * For example the following two statements are equivalent: + * + * var e1 = driver.findElement(webdriver.By.id('foo')); + * var e2 = driver.findElement({id: 'foo'}); + * + * Care should be taken when using JavaScript minifiers (such as the + * Closure compiler), as locator hashes will always be parsed using + * the un-obfuscated properties listed. + * + * @typedef {( + * {className: string}| + * {css: string}| + * {id: string}| + * {js: string}| + * {linkText: string}| + * {name: string}| + * {partialLinkText: string}| + * {tagName: string}| + * {xpath: string})} + */ + type Hash = {className: string}| + {css: string}| + {id: string}| + {js: string}| + {linkText: string}| + {name: string}| + {partialLinkText: string}| + {tagName: string}| + {xpath: string}; + } + /** * An element locator. */ From 08b91e601cfe273f8e81d387321a94ce4b8d2452 Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Thu, 9 Jul 2015 20:57:53 +0900 Subject: [PATCH 009/345] Comment out definitnions and tests for webdriver.By.Hash --- .../selenium-webdriver-tests.ts | 18 ++--- selenium-webdriver/selenium-webdriver.d.ts | 66 +++++++++---------- 2 files changed, 42 insertions(+), 42 deletions(-) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index b296b62ee..4b1449bce 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -528,15 +528,15 @@ function TestLocator() { locator = webdriver.By.tagName('tag'); locator = webdriver.By.xpath('xpath'); - var locatorHash: webdriver.By.Hash; - locatorHash = { className: 'class' }; - locatorHash = { css: 'css' }; - locatorHash = { id: 'id' }; - locatorHash = { linkText: 'link' }; - locatorHash = { name: 'name' }; - locatorHash = { partialLinkText: 'text' }; - locatorHash = { tagName: 'tag' }; - locatorHash = { xpath: 'xpath' }; + // var locatorHash: webdriver.By.Hash; + // locatorHash = { className: 'class' }; + // locatorHash = { css: 'css' }; + // locatorHash = { id: 'id' }; + // locatorHash = { linkText: 'link' }; + // locatorHash = { name: 'name' }; + // locatorHash = { partialLinkText: 'text' }; + // locatorHash = { tagName: 'tag' }; + // locatorHash = { xpath: 'xpath' }; webdriver.By.js('script', 1, 2, 3)(driver).then(function (abc: number) { }); } diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index b170d24c5..da1c2ab40 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -4783,39 +4783,39 @@ declare module webdriver { var By: ILocatorStrategy; - module By { - /** - * Short-hand expressions for the primary element locator strategies. - * For example the following two statements are equivalent: - * - * var e1 = driver.findElement(webdriver.By.id('foo')); - * var e2 = driver.findElement({id: 'foo'}); - * - * Care should be taken when using JavaScript minifiers (such as the - * Closure compiler), as locator hashes will always be parsed using - * the un-obfuscated properties listed. - * - * @typedef {( - * {className: string}| - * {css: string}| - * {id: string}| - * {js: string}| - * {linkText: string}| - * {name: string}| - * {partialLinkText: string}| - * {tagName: string}| - * {xpath: string})} - */ - type Hash = {className: string}| - {css: string}| - {id: string}| - {js: string}| - {linkText: string}| - {name: string}| - {partialLinkText: string}| - {tagName: string}| - {xpath: string}; - } + // module By { + // /** + // * Short-hand expressions for the primary element locator strategies. + // * For example the following two statements are equivalent: + // * + // * var e1 = driver.findElement(webdriver.By.id('foo')); + // * var e2 = driver.findElement({id: 'foo'}); + // * + // * Care should be taken when using JavaScript minifiers (such as the + // * Closure compiler), as locator hashes will always be parsed using + // * the un-obfuscated properties listed. + // * + // * @typedef {( + // * {className: string}| + // * {css: string}| + // * {id: string}| + // * {js: string}| + // * {linkText: string}| + // * {name: string}| + // * {partialLinkText: string}| + // * {tagName: string}| + // * {xpath: string})} + // */ + // type Hash = {className: string}| + // {css: string}| + // {id: string}| + // {js: string}| + // {linkText: string}| + // {name: string}| + // {partialLinkText: string}| + // {tagName: string}| + // {xpath: string}; + // } /** * An element locator. From 7c881f2e1a89adf44076b12b2aa630f94163eff9 Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Thu, 9 Jul 2015 21:00:26 +0900 Subject: [PATCH 010/345] Add webdriver.TestTouchSequence --- .../selenium-webdriver-tests.ts | 22 +++ selenium-webdriver/selenium-webdriver.d.ts | 137 ++++++++++++++++++ 2 files changed, 159 insertions(+) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index 4b1449bce..b805a8b5a 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -182,6 +182,28 @@ function TestActionSequence() { sequence.perform().then(function () { }); } +function TestTouchSequence() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + var element: webdriver.WebElement = new webdriver.WebElement(driver, { ELEMENT: 'id' }); + + var sequence: webdriver.TouchSequence = new webdriver.TouchSequence(driver); + + sequence = sequence.tap(element); + sequence = sequence.doubleTap(element); + sequence = sequence.longPress(element); + sequence = sequence.tapAndHold({ x: 100, y: 100 }); + sequence = sequence.move({ x: 100, y: 100 }); + sequence = sequence.release({ x: 100, y: 100 }); + sequence = sequence.scroll({ x: 100, y: 100 }); + sequence = sequence.scrollFromElement(element, { x: 100, y: 100 }); + sequence = sequence.flick({ xspeed: 100, yspeed: 100 }); + sequence = sequence.flickElement(element, { x: 100, y: 100 }, 100); + + sequence.perform().then(function () { }); +} + function TestAlert() { var driver: webdriver.WebDriver = new webdriver.Builder(). withCapabilities(webdriver.Capabilities.chrome()). diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index da1c2ab40..49555eb2a 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -2307,6 +2307,143 @@ declare module webdriver { //endregion } + + /** + * Class for defining sequences of user touch interactions. Each sequence + * will not be executed until {@link #perform} is called. + * + * Example: + * + * new webdriver.TouchSequence(driver). + * tapAndHold({x: 0, y: 0}). + * move({x: 3, y: 4}). + * release({x: 10, y: 10}). + * perform(); + */ + class TouchSequence { + /* + * @param {!webdriver.WebDriver} driver The driver instance to use. + * @constructor + */ + constructor(driver: WebDriver); + + + /** + * Executes this action sequence. + * @return {!webdriver.promise.Promise} A promise that will be resolved once + * this sequence has completed. + */ + perform(): webdriver.promise.Promise; + + + /** + * Taps an element. + * + * @param {!webdriver.WebElement} elem The element to tap. + * @return {!webdriver.TouchSequence} A self reference. + */ + tap(elem: IWebElement): TouchSequence; + + + /** + * Double taps an element. + * + * @param {!webdriver.WebElement} elem The element to double tap. + * @return {!webdriver.TouchSequence} A self reference. + */ + doubleTap(elem: IWebElement): TouchSequence; + + + /** + * Long press on an element. + * + * @param {!webdriver.WebElement} elem The element to long press. + * @return {!webdriver.TouchSequence} A self reference. + */ + longPress(elem: IWebElement): TouchSequence; + + + /** + * Touch down at the given location. + * + * @param {{ x: number, y: number }} location The location to touch down at. + * @return {!webdriver.TouchSequence} A self reference. + */ + tapAndHold(location: ILocation): TouchSequence; + + + /** + * Move a held {@linkplain #tapAndHold touch} to the specified location. + * + * @param {{x: number, y: number}} location The location to move to. + * @return {!webdriver.TouchSequence} A self reference. + */ + move(location: ILocation): TouchSequence; + + + /** + * Release a held {@linkplain #tapAndHold touch} at the specified location. + * + * @param {{x: number, y: number}} location The location to release at. + * @return {!webdriver.TouchSequence} A self reference. + */ + release(location: ILocation): TouchSequence; + + + /** + * Scrolls the touch screen by the given offset. + * + * @param {{x: number, y: number}} offset The offset to scroll to. + * @return {!webdriver.TouchSequence} A self reference. + */ + scroll(offset: IOffset): TouchSequence; + + + /** + * Scrolls the touch screen, starting on `elem` and moving by the specified + * offset. + * + * @param {!webdriver.WebElement} elem The element where scroll starts. + * @param {{x: number, y: number}} offset The offset to scroll to. + * @return {!webdriver.TouchSequence} A self reference. + */ + scrollFromElement(elem: IWebElement, offset: IOffset): TouchSequence; + + + /** + * Flick, starting anywhere on the screen, at speed xspeed and yspeed. + * + * @param {{xspeed: number, yspeed: number}} speed The speed to flick in each + direction, in pixels per second. + * @return {!webdriver.TouchSequence} A self reference. + */ + flick(speed: ISpeed): TouchSequence; + + + /** + * Flick starting at elem and moving by x and y at specified speed. + * + * @param {!webdriver.WebElement} elem The element where flick starts. + * @param {{x: number, y: number}} offset The offset to flick to. + * @param {number} speed The speed to flick at in pixels per second. + * @return {!webdriver.TouchSequence} A self reference. + */ + flickElement(elem: IWebElement, offset: IOffset, speed: number): TouchSequence; + } + + + interface IOffset { + x: number; + y: number; + } + + + interface ISpeed { + xspeed: number; + yspeed: number; + } + + /** * Represents a modal dialog such as {@code alert}, {@code confirm}, or * {@code prompt}. Provides functions to retrieve the message displayed with From 1bbf7338c1ad40b04f7e38724bc5542bfc9613c8 Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Thu, 9 Jul 2015 21:17:14 +0900 Subject: [PATCH 011/345] Add webdriver.WebDriver#touchActions --- selenium-webdriver/selenium-webdriver-tests.ts | 1 + selenium-webdriver/selenium-webdriver.d.ts | 16 ++++++++++++++++ 2 files changed, 17 insertions(+) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index b805a8b5a..c93b96c00 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -697,6 +697,7 @@ function TestWebDriver() { var booleanPromise: webdriver.promise.Promise; var actions: webdriver.ActionSequence = driver.actions(); + var touchActions: webdriver.TouchSequence = driver.touchActions(); // call stringPromise = driver.call(function(){}); diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index 49555eb2a..b7afaa081 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -3775,6 +3775,22 @@ declare module webdriver { */ actions(): ActionSequence; + + /** + * Creates a new touch sequence using this driver. The sequence will not be + * scheduled for execution until {@link webdriver.TouchSequence#perform} is + * called. Example: + * + * driver.touchActions(). + * tap(element1). + * doubleTap(element2). + * perform(); + * + * @return {!webdriver.TouchSequence} A new touch sequence for this instance. + */ + touchActions(): TouchSequence; + + /** * Schedules a command to execute JavaScript in the context of the currently * selected frame or window. The script fragment will be executed as the body From f2efb822f5756b4b8f07e83650bc1d6e54b2b19c Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Thu, 9 Jul 2015 21:18:05 +0900 Subject: [PATCH 012/345] Add webdriver.FileDetector --- .../selenium-webdriver-tests.ts | 10 ++++++ selenium-webdriver/selenium-webdriver.d.ts | 35 +++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index c93b96c00..4e5e9766b 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -586,6 +586,16 @@ function TestUnhandledAlertError() { } } +function TestWebDriverFileDetector() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var fileDetector: webdriver.FileDetector = new webdriver.FileDetector(); + + fileDetector.handleFile(driver, 'path/to/file').then(function(path: string) {}); +} + function TestWebDriverLogs() { var driver: webdriver.WebDriver = new webdriver.Builder(). withCapabilities(webdriver.Capabilities.chrome()). diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index b7afaa081..4d4829342 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -3645,6 +3645,41 @@ declare module webdriver { //endregion } + /** + * Used with {@link webdriver.WebElement#sendKeys WebElement#sendKeys} on file + * input elements ({@code }) to detect when the entered key + * sequence defines the path to a file. + * + * By default, {@linkplain webdriver.WebElement WebElement's} will enter all + * key sequences exactly as entered. You may set a + * {@linkplain webdriver.WebDriver#setFileDetector file detector} on the parent + * WebDriver instance to define custom behavior for handling file elements. Of + * particular note is the {@link selenium-webdriver/remote.FileDetector}, which + * should be used when running against a remote + * [Selenium Server](http://docs.seleniumhq.org/download/). + */ + class FileDetector { + /** @constructor */ + constructor(); + + /** + * Handles the file specified by the given path, preparing it for use with + * the current browser. If the path does not refer to a valid file, it will + * be returned unchanged, otherwisee a path suitable for use with the current + * browser will be returned. + * + * This default implementation is a no-op. Subtypes may override this + * function for custom tailored file handling. + * + * @param {!webdriver.WebDriver} driver The driver for the current browser. + * @param {string} path The path to process. + * @return {!webdriver.promise.Promise} A promise for the processed + * file path. + * @package + */ + handleFile(driver: webdriver.WebDriver, path: string): webdriver.promise.Promise; + } + /** * Creates a new WebDriver client, which provides control over a browser. * From d278c4283d910f6a4492ca7413dc025b40586d9b Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Thu, 9 Jul 2015 21:24:30 +0900 Subject: [PATCH 013/345] Add webdriver.WabDriver#setFileDetector --- selenium-webdriver/selenium-webdriver-tests.ts | 3 +++ selenium-webdriver/selenium-webdriver.d.ts | 9 +++++++++ 2 files changed, 12 insertions(+) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index 4e5e9766b..3c663531e 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -760,6 +760,9 @@ function TestWebDriver() { var navigation: webdriver.WebDriverNavigation = driver.navigate(); var locator: webdriver.WebDriverTargetLocator = driver.switchTo(); + var fileDetector: webdriver.FileDetector = new webdriver.FileDetector(); + driver.setFileDetector(fileDetector); + voidPromise = driver.quit(); voidPromise = driver.schedule(new webdriver.Command(webdriver.CommandName.CLICK), 'ABC'); voidPromise = driver.sleep(123); diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index 4d4829342..e99c8d8f6 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -3775,6 +3775,15 @@ declare module webdriver { */ schedule(command: Command, description: string): webdriver.promise.Promise; + + /** + * Sets the {@linkplain webdriver.FileDetector file detector} that should be + * used with this instance. + * @param {webdriver.FileDetector} detector The detector to use or {@code null}. + */ + setFileDetector(detector: FileDetector): void; + + /** * @return {!webdriver.promise.Promise} A promise for this client's session. */ From 453d394a7bb1e7abe4dfeadb522a9ece359a6c83 Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Thu, 9 Jul 2015 21:25:11 +0900 Subject: [PATCH 014/345] Update webdriver.WebDriver annotations --- selenium-webdriver/selenium-webdriver.d.ts | 281 ++++++++++++--------- 1 file changed, 161 insertions(+), 120 deletions(-) diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index e99c8d8f6..8814e194e 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -3251,6 +3251,7 @@ declare module webdriver { //endregion } + /** * Interface for navigating back and forth in the browser history. */ @@ -3270,29 +3271,29 @@ declare module webdriver { /** * Schedules a command to navigate to a new URL. * @param {string} url The URL to navigate to. - * @return {!webdriver.promise.Promise} A promise that will be resolved when the - * URL has been loaded. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the URL has been loaded. */ to(url: string): webdriver.promise.Promise; /** * Schedules a command to move backwards in the browser history. - * @return {!webdriver.promise.Promise} A promise that will be resolved when the - * navigation event has completed. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the navigation event has completed. */ back(): webdriver.promise.Promise; /** * Schedules a command to move forwards in the browser history. - * @return {!webdriver.promise.Promise} A promise that will be resolved when the - * navigation event has completed. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the navigation event has completed. */ forward(): webdriver.promise.Promise; /** * Schedules a command to refresh the current page. - * @return {!webdriver.promise.Promise} A promise that will be resolved when the - * navigation event has completed. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the navigation event has completed. */ refresh(): webdriver.promise.Promise; @@ -3785,22 +3786,25 @@ declare module webdriver { /** - * @return {!webdriver.promise.Promise} A promise for this client's session. + * @return {!webdriver.promise.Promise.} A promise for this + * client's session. */ getSession(): webdriver.promise.Promise; + /** - * @return {!webdriver.promise.Promise} A promise that will resolve with the - * this instance's capabilities. + * @return {!webdriver.promise.Promise.} A promise + * that will resolve with the this instance's capabilities. */ getCapabilities(): webdriver.promise.Promise; + /** * Schedules a command to quit the current session. After calling quit, this * instance will be invalidated and may no longer be used to issue commands * against the browser. - * @return {!webdriver.promise.Promise} A promise that will be resolved when - * the command has completed. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the command has completed. */ quit(): webdriver.promise.Promise; @@ -3857,20 +3861,20 @@ declare module webdriver { * If the script has a return value (i.e. if the script contains a return * statement), then the following steps will be taken for resolving this * functions return value: - *

    - *
  • For a HTML element, the value will resolve to a - * {@code webdriver.WebElement}
  • - *
  • Null and undefined return values will resolve to null
  • - *
  • Booleans, numbers, and strings will resolve as is
  • - *
  • Functions will resolve to their string representation
  • - *
  • For arrays and objects, each member item will be converted according to - * the rules above
  • - *
+ * + * - For a HTML element, the value will resolve to a + * {@link webdriver.WebElement} + * - Null and undefined return values will resolve to null + * - Booleans, numbers, and strings will resolve as is + * - Functions will resolve to their string representation + * - For arrays and objects, each member item will be converted according to + * the rules above * * @param {!(string|Function)} script The script to execute. * @param {...*} var_args The arguments to pass to the script. - * @return {!webdriver.promise.Promise} A promise that will resolve to the + * @return {!webdriver.promise.Promise.} A promise that will resolve to the * scripts return value. + * @template T */ executeScript(script: string, ...var_args: any[]): webdriver.promise.Promise; executeScript(script: Function, ...var_args: any[]): webdriver.promise.Promise; @@ -3888,102 +3892,126 @@ declare module webdriver { * Arrays and objects may also be used as script arguments as long as each item * adheres to the types previously mentioned. * - * Unlike executing synchronous JavaScript with - * {@code webdriver.WebDriver.prototype.executeScript}, scripts executed with - * this function must explicitly signal they are finished by invoking the - * provided callback. This callback will always be injected into the - * executed function as the last argument, and thus may be referenced with - * {@code arguments[arguments.length - 1]}. The following steps will be taken - * for resolving this functions return value against the first argument to the - * script's callback function: - *
    - *
  • For a HTML element, the value will resolve to a - * {@code webdriver.WebElement}
  • - *
  • Null and undefined return values will resolve to null
  • - *
  • Booleans, numbers, and strings will resolve as is
  • - *
  • Functions will resolve to their string representation
  • - *
  • For arrays and objects, each member item will be converted according to - * the rules above
  • - *
+ * Unlike executing synchronous JavaScript with {@link #executeScript}, + * scripts executed with this function must explicitly signal they are finished + * by invoking the provided callback. This callback will always be injected + * into the executed function as the last argument, and thus may be referenced + * with {@code arguments[arguments.length - 1]}. The following steps will be + * taken for resolving this functions return value against the first argument + * to the script's callback function: * - * Example #1: Performing a sleep that is synchronized with the currently + * - For a HTML element, the value will resolve to a + * {@link webdriver.WebElement} + * - Null and undefined return values will resolve to null + * - Booleans, numbers, and strings will resolve as is + * - Functions will resolve to their string representation + * - For arrays and objects, each member item will be converted according to + * the rules above + * + * __Example #1:__ Performing a sleep that is synchronized with the currently * selected window: - *
-         * var start = new Date().getTime();
-         * driver.executeAsyncScript(
-         *     'window.setTimeout(arguments[arguments.length - 1], 500);').
-         *     then(function() {
-         *       console.log('Elapsed time: ' + (new Date().getTime() - start) + ' ms');
-         *     });
-         * 
* - * Example #2: Synchronizing a test with an AJAX application: - *
-         * var button = driver.findElement(By.id('compose-button'));
-         * button.click();
-         * driver.executeAsyncScript(
-         *     'var callback = arguments[arguments.length - 1];' +
-         *     'mailClient.getComposeWindowWidget().onload(callback);');
-         * driver.switchTo().frame('composeWidget');
-         * driver.findElement(By.id('to')).sendKEys('dog@example.com');
-         * 
+ * var start = new Date().getTime(); + * driver.executeAsyncScript( + * 'window.setTimeout(arguments[arguments.length - 1], 500);'). + * then(function() { + * console.log( + * 'Elapsed time: ' + (new Date().getTime() - start) + ' ms'); + * }); * - * Example #3: Injecting a XMLHttpRequest and waiting for the result. In this - * example, the inject script is specified with a function literal. When using - * this format, the function is converted to a string for injection, so it + * __Example #2:__ Synchronizing a test with an AJAX application: + * + * var button = driver.findElement(By.id('compose-button')); + * button.click(); + * driver.executeAsyncScript( + * 'var callback = arguments[arguments.length - 1];' + + * 'mailClient.getComposeWindowWidget().onload(callback);'); + * driver.switchTo().frame('composeWidget'); + * driver.findElement(By.id('to')).sendKeys('dog@example.com'); + * + * __Example #3:__ Injecting a XMLHttpRequest and waiting for the result. In + * this example, the inject script is specified with a function literal. When + * using this format, the function is converted to a string for injection, so it * should not reference any symbols not defined in the scope of the page under * test. - *
-         * driver.executeAsyncScript(function() {
-         *   var callback = arguments[arguments.length - 1];
-         *   var xhr = new XMLHttpRequest();
-         *   xhr.open("GET", "/resource/data.json", true);
-         *   xhr.onreadystatechange = function() {
-         *     if (xhr.readyState == 4) {
-         *       callback(xhr.resposneText);
-         *     }
-         *   }
-         *   xhr.send('');
-         * }).then(function(str) {
-         *   console.log(JSON.parse(str)['food']);
-         * });
-         * 
+ * + * driver.executeAsyncScript(function() { + * var callback = arguments[arguments.length - 1]; + * var xhr = new XMLHttpRequest(); + * xhr.open("GET", "/resource/data.json", true); + * xhr.onreadystatechange = function() { + * if (xhr.readyState == 4) { + * callback(xhr.responseText); + * } + * } + * xhr.send(''); + * }).then(function(str) { + * console.log(JSON.parse(str)['food']); + * }); * * @param {!(string|Function)} script The script to execute. * @param {...*} var_args The arguments to pass to the script. - * @return {!webdriver.promise.Promise} A promise that will resolve to the + * @return {!webdriver.promise.Promise.} A promise that will resolve to the * scripts return value. + * @template T */ executeAsyncScript(script: string, ...var_args: any[]): webdriver.promise.Promise; executeAsyncScript(script: Function, ...var_args: any[]): webdriver.promise.Promise; /** * Schedules a command to execute a custom function. - * @param {!Function} fn The function to execute. + * @param {function(...): (T|webdriver.promise.Promise.)} fn The function to + * execute. * @param {Object=} opt_scope The object in whose scope to execute the function. * @param {...*} var_args Any arguments to pass to the function. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * function's result. + * @return {!webdriver.promise.Promise.} A promise that will be resolved' + * with the function's result. + * @template T */ call(fn: Function, opt_scope?: any, ...var_args: any[]): webdriver.promise.Promise; /** - * Schedules a command to wait for a condition to hold, as defined by some - * user supplied function. If any errors occur while evaluating the wait, they - * will be allowed to propagate. + * Schedules a command to wait for a condition to hold. The condition may be + * specified by a {@link webdriver.until.Condition}, as a custom function, or + * as a {@link webdriver.promise.Promise}. * - *

In the event a condition returns a {@link webdriver.promise.Promise}, the + * For a {@link webdriver.until.Condition} or function, the wait will repeatedly + * evaluate the condition until it returns a truthy value. If any errors occur + * while evaluating the condition, they will be allowed to propagate. In the + * event a condition returns a {@link webdriver.promise.Promise promise}, the * polling loop will wait for it to be resolved and use the resolved value for - * evaluating whether the condition has been satisfied. The resolution time for + * whether the condition has been satisified. Note the resolution time for * a promise is factored into whether a wait has timed out. * - * @param {!(webdriver.until.Condition.| - * function(!webdriver.WebDriver): T)} condition Either a condition - * object, or a function to evaluate as a condition. - * @param {number} timeout How long to wait for the condition to be true. + * *Example:* waiting up to 10 seconds for an element to be present and visible + * on the page. + * + * var button = driver.wait(until.elementLocated(By.id('foo'), 10000); + * button.click(); + * + * This function may also be used to block the command flow on the resolution + * of a {@link webdriver.promise.Promise promise}. When given a promise, the + * command will simply wait for its resolution before completing. A timeout may + * be provided to fail the command if the promise does not resolve before the + * timeout expires. + * + * *Example:* Suppose you have a function, `startTestServer`, that returns a + * promise for when a server is ready for requests. You can block a `WebDriver` + * client on this promise with: + * + * var started = startTestServer(); + * driver.wait(started, 5 * 1000, 'Server should start within 5 seconds'); + * driver.get(getServerUrl()); + * + * @param {!(webdriver.promise.Promise| + * webdriver.until.Condition| + * function(!webdriver.WebDriver): T)} condition The condition to + * wait on, defined as a promise, condition object, or a function to + * evaluate as a condition. + * @param {number=} opt_timeout How long to wait for the condition to be true. * @param {string=} opt_message An optional message to use if the wait times * out. - * @return {!webdriver.promise.Promise.} A promise that will be fulfilled + * @return {!webdriver.promise.Promise} A promise that will be fulfilled * with the first truthy value returned by the condition function, or * rejected if the condition times out. * @template T @@ -3994,22 +4022,22 @@ declare module webdriver { /** * Schedules a command to make the driver sleep for the given amount of time. * @param {number} ms The amount of time, in milliseconds, to sleep. - * @return {!webdriver.promise.Promise} A promise that will be resolved when the - * sleep has finished. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the sleep has finished. */ sleep(ms: number): webdriver.promise.Promise; /** * Schedules a command to retrieve they current window handle. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * current window handle. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the current window handle. */ getWindowHandle(): webdriver.promise.Promise; /** * Schedules a command to retrieve the current list of available window handles. - * @return {!webdriver.promise.Promise} A promise that will be resolved with an - * array of window handles. + * @return {!webdriver.promise.Promise.>} A promise that will + * be resolved with an array of window handles. */ getAllWindowHandles(): webdriver.promise.Promise; @@ -4018,60 +4046,73 @@ declare module webdriver { * returned is a representation of the underlying DOM: do not expect it to be * formatted or escaped in the same way as the response sent from the web * server. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * current page source. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the current page source. */ getPageSource(): webdriver.promise.Promise; /** * Schedules a command to close the current window. - * @return {!webdriver.promise.Promise} A promise that will be resolved when - * this command has completed. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when this command has completed. */ close(): webdriver.promise.Promise; /** * Schedules a command to navigate to the given URL. * @param {string} url The fully qualified URL to open. - * @return {!webdriver.promise.Promise} A promise that will be resolved when the - * document has finished loading. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the document has finished loading. */ get(url: string): webdriver.promise.Promise; /** * Schedules a command to retrieve the URL of the current page. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * current URL. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the current URL. */ getCurrentUrl(): webdriver.promise.Promise; /** * Schedules a command to retrieve the current page's title. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * current page's title. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the current page's title. */ getTitle(): webdriver.promise.Promise; /** * Schedule a command to find an element on the page. If the element cannot be - * found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will be returned + * found, a {@link bot.ErrorCode.NO_SUCH_ELEMENT} result will be returned * by the driver. Unlike other commands, this error cannot be suppressed. In * other words, scheduling a command to find an element doubles as an assert * that the element is present on the page. To test whether an element is - * present on the page, use {@code #isElementPresent} instead. + * present on the page, use {@link #isElementPresent} instead. * - *

The search criteria for find an element may either be a - * {@code webdriver.Locator} object, or a simple JSON object whose sole key - * is one of the accepted locator strategies, as defined by - * {@code webdriver.Locator.Strategy}. For example, the following two statements * The search criteria for an element may be defined using one of the + * factories in the {@link webdriver.By} namespace, or as a short-hand + * {@link webdriver.By.Hash} object. For example, the following two statements * are equivalent: - *

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

When running in the browser, a WebDriver cannot manipulate DOM elements + * var e1 = driver.findElement(By.id('foo')); + * var e2 = driver.findElement({id:'foo'}); + * + * You may also provide a custom locator function, which takes as input + * this WebDriver instance and returns a {@link webdriver.WebElement}, or a + * promise that will resolve to a WebElement. For example, to find the first + * visible link on a page, you could write: + * + * var link = driver.findElement(firstVisibleLink); + * + * function firstVisibleLink(driver) { + * var links = driver.findElements(By.tagName('a')); + * return webdriver.promise.filter(links, function(link) { + * return links.isDisplayed(); + * }).then(function(visibleLinks) { + * return visibleLinks[0]; + * }); + * } + * + * When running in the browser, a WebDriver cannot manipulate DOM elements * directly; it may do so only through a {@link webdriver.WebElement} reference. * This function may be used to generate a WebElement from a DOM element. A * reference to the DOM element will be stored in a known location and this @@ -4126,8 +4167,8 @@ declare module webdriver { *

  • The screenshot of the entire display containing the browser * * - * @return {!webdriver.promise.Promise} A promise that will be resolved to the - * screenshot as a base-64 encoded PNG. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved to the screenshot as a base-64 encoded PNG. */ takeScreenshot(): webdriver.promise.Promise; From 22c0bb370f3aa34209a9760cee79ec6e9a89bfd8 Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Thu, 9 Jul 2015 23:14:12 +0900 Subject: [PATCH 015/345] Remove deprecated methods Link: https://github.com/SeleniumHQ/selenium/commit/e7b442e01370178ca9fd64ed73cf39e2dc76b519#diff-b1976f46bdbb6d0d51ba6baa46156d61 --- .../selenium-webdriver-tests.ts | 8 ------ selenium-webdriver/selenium-webdriver.d.ts | 28 ------------------- 2 files changed, 36 deletions(-) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index 3c663531e..55890964f 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -1035,19 +1035,11 @@ function TestControlFlow() { eventType = webdriver.promise.ControlFlow.EventType.SCHEDULE_TASK; eventType = webdriver.promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION; - var e: any = flow.annotateError(new Error('Error')); - var stringPromise: webdriver.promise.Promise; - stringPromise = flow.await(stringPromise); - - flow.clearHistory(); - stringPromise = flow.execute(function() { return stringPromise; }); stringPromise = flow.execute(function() { return stringPromise; }, 'Description'); - var history: string[] = flow.getHistory(); - var schedule: string = flow.getSchedule(); flow.reset(); diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index 8814e194e..6ce13dfa9 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -1611,26 +1611,7 @@ declare module webdriver { reset(): void; /** - * Returns a summary of the recent task activity for this instance. This - * includes the most recently completed task, as well as any parent tasks. In - * the returned summary, the task at index N is considered a sub-task of the - * task at index N+1. - * @return {!Array.} A summary of this instance's recent task - * activity. */ - getHistory(): string[]; - - /** Clears this instance's task history. */ - clearHistory(): void; - - /** - * Appends a summary of this instance's recent task history to the given - * error's stack trace. This function will also ensure the error's stack trace - * is in canonical form. - * @param {!(Error|goog.testing.JsUnitException)} e The error to annotate. - * @return {!(Error|goog.testing.JsUnitException)} The annotated error. - */ - annotateError(e: any): any; /** * @return {string} The scheduled tasks still pending with this instance. @@ -1687,15 +1668,6 @@ declare module webdriver { */ wait(condition: Function, timeout: number, opt_message?: string): Promise; - /** - * Schedules a task that will wait for another promise to resolve. The resolved - * promise's value will be returned as the task result. - * @param {!webdriver.promise.Promise} promise The promise to wait on. - * @return {!webdriver.promise.Promise} A promise that will resolve when the - * task has completed. - */ - await(promise: Promise): Promise; - //endregion } } From 69164fec6e1f2b7efcd8a0d7138d34dc9f5c9edf Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Thu, 9 Jul 2015 23:19:36 +0900 Subject: [PATCH 016/345] Remove timers Link: https://github.com/SeleniumHQ/selenium/commit/43c1701222bf0314567e554c7a1dd1ad903bfa4f#diff-b1976f46bdbb6d0d51ba6baa46156d61 --- .../selenium-webdriver-tests.ts | 13 +--- selenium-webdriver/selenium-webdriver.d.ts | 76 +++++++------------ 2 files changed, 30 insertions(+), 59 deletions(-) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index 55890964f..07eb632c5 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -1021,10 +1021,6 @@ function TestUntilModule() { function TestControlFlow() { var flow: webdriver.promise.ControlFlow; flow = new webdriver.promise.ControlFlow(); - flow = new webdriver.promise.ControlFlow({clearInterval: function(a: number) {}, - clearTimeout: function(a: number) {}, - setInterval: function(a: () => void, b: number) { return 2; }, - setTimeout: function(a: () => void, b: number) { return 2; }}); var emitter: webdriver.EventEmitter = flow; @@ -1036,11 +1032,13 @@ function TestControlFlow() { eventType = webdriver.promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION; var stringPromise: webdriver.promise.Promise; - stringPromise = flow.execute(function() { return stringPromise; }); stringPromise = flow.execute(function() { return stringPromise; }, 'Description'); - var schedule: string = flow.getSchedule(); + var schedule: string; + schedule = flow.toString(); + schedule = flow.getSchedule(); + schedule = flow.getSchedule(true); flow.reset(); @@ -1051,10 +1049,7 @@ function TestControlFlow() { voidPromise = flow.wait(function() { return true; }, 123, 'Timeout Message'); voidPromise = flow.wait(function() { return stringPromise; }, 123, 'Timeout Message'); - var timer: webdriver.promise.IControlFlowTimer = flow.timer; - timer = webdriver.promise.ControlFlow.defaultTimer; - var loopFrequency: number = webdriver.promise.ControlFlow.EVENT_LOOP_FREQUENCY; } function TestDeferred() { diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index 6ce13dfa9..9b371b4d0 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -1518,58 +1518,34 @@ declare module webdriver { * the ordered scheduled, starting each task only once those before it have * completed. * - *

    Each task scheduled within this flow may return a + * Each task scheduled within this flow may return a * {@link webdriver.promise.Promise} to indicate it is an asynchronous * operation. The ControlFlow will wait for such promises to be resolved before * marking the task as completed. * - *

    Tasks and each callback registered on a {@link webdriver.promise.Deferred} + * Tasks and each callback registered on a {@link webdriver.promise.Promise} * will be run in their own ControlFlow frame. Any tasks scheduled within a - * frame will have priority over previously scheduled tasks. Furthermore, if - * any of the tasks in the frame fails, the remainder of the tasks in that frame - * will be discarded and the failure will be propagated to the user through the + * frame will take priority over previously scheduled tasks. Furthermore, if any + * of the tasks in the frame fail, the remainder of the tasks in that frame will + * be discarded and the failure will be propagated to the user through the * callback/task's promised result. * - *

    Each time a ControlFlow empties its task queue, it will fire an - * {@link webdriver.promise.ControlFlow.EventType.IDLE} event. Conversely, + * Each time a ControlFlow empties its task queue, it will fire an + * {@link webdriver.promise.ControlFlow.EventType.IDLE IDLE} event. Conversely, * whenever the flow terminates due to an unhandled error, it will remove all * remaining tasks in its queue and fire an - * {@link webdriver.promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION} event. If - * there are no listeners registered with the flow, the error will be - * rethrown to the global error handler. + * {@link webdriver.promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION + * UNCAUGHT_EXCEPTION} event. If there are no listeners registered with the + * flow, the error will be rethrown to the global error handler. * - * @extends {webdriver.EventEmitter} + * @extends {EventEmitter} + * @final */ class ControlFlow extends EventEmitter { - - //region Constructors - /** - * @param {webdriver.promise.ControlFlow.Timer=} opt_timer The timer object - * to use. Should only be set for testing. * @constructor */ - constructor(opt_timer?: IControlFlowTimer); - - //endregion - - //region Properties - - /** - * The timer used by this instance. - * @type {webdriver.promise.ControlFlow.Timer} - */ - timer: IControlFlowTimer; - - //endregion - - //region Static Properties - - /** - * The default timer object, which uses the global timer functions. - * @type {webdriver.promise.ControlFlow.Timer} - */ - static defaultTimer: IControlFlowTimer; + constructor(); /** * Events that may be emitted by an {@link webdriver.promise.ControlFlow}. @@ -1595,15 +1571,12 @@ declare module webdriver { }; /** - * How often, in milliseconds, the event loop should run. - * @type {number} - * @const + * Returns a string representation of this control flow, which is its current + * {@link #getSchedule() schedule}, sans task stack traces. + * @return {string} The string representation of this contorl flow. + * @override */ - static EVENT_LOOP_FREQUENCY: number; - - //endregion - - //region Methods + toString(): string; /** * Resets this instance, clearing its queue and removing all event listeners. @@ -1611,12 +1584,15 @@ declare module webdriver { reset(): void; /** + * Generates an annotated string describing the internal state of this control + * flow, including the currently executing as well as pending tasks. If + * {@code opt_includeStackTraces === true}, the string will include the + * stack trace from when each task was scheduled. + * @param {string=} opt_includeStackTraces Whether to include the stack traces + * from when each task was scheduled. Defaults to false. + * @return {string} String representation of this flow's internal state. */ - - /** - * @return {string} The scheduled tasks still pending with this instance. - */ - getSchedule(): string; + getSchedule(opt_includeStackTraces?: boolean): string; /** * Schedules a task for execution. If there is nothing currently in the From 65ced8681c78c395802a199379fd9f5ac29934f7 Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Thu, 9 Jul 2015 23:21:13 +0900 Subject: [PATCH 017/345] Update webdriver.promise.ControlFlow#wait Link: https://github.com/SeleniumHQ/selenium/commit/f473be4a45751948e8e36344f83d6ffccc5574ef#diff-b1976f46bdbb6d0d51ba6baa46156d61 --- .../selenium-webdriver-tests.ts | 8 ++--- selenium-webdriver/selenium-webdriver.d.ts | 34 ++++++++++++------- 2 files changed, 26 insertions(+), 16 deletions(-) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index 07eb632c5..ca729eba5 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -1045,11 +1045,11 @@ function TestControlFlow() { var voidPromise: webdriver.promise.Promise = flow.timeout(123); voidPromise = flow.timeout(123, 'Description'); - voidPromise = flow.wait(function() { return true; }, 123); - voidPromise = flow.wait(function() { return true; }, 123, 'Timeout Message'); - voidPromise = flow.wait(function() { return stringPromise; }, 123, 'Timeout Message'); - + stringPromise = flow.wait(stringPromise); + voidPromise = flow.wait(function() { return true; }); + voidPromise = flow.wait(function() { return true; }, 123); + voidPromise = flow.wait(function() { return stringPromise; }, 123, 'Timeout Message'); } function TestDeferred() { diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index 9b371b4d0..9b065ff80 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -1622,29 +1622,39 @@ declare module webdriver { * Schedules a task that shall wait for a condition to hold. Each condition * function may return any value, but it will always be evaluated as a boolean. * - *

    Condition functions may schedule sub-tasks with this instance, however, + * Condition functions may schedule sub-tasks with this instance, however, * their execution time will be factored into whether a wait has timed out. * - *

    In the event a condition returns a Promise, the polling loop will wait for + * In the event a condition returns a Promise, the polling loop will wait for * it to be resolved before evaluating whether the condition has been satisfied. * The resolution time for a promise is factored into whether a wait has timed * out. * - *

    If the condition function throws, or returns a rejected promise, the + * If the condition function throws, or returns a rejected promise, the * wait task will fail. * - * @param {!Function} condition The condition function to poll. - * @param {number} timeout How long to wait, in milliseconds, for the condition - * to hold before timing out. + * If the condition is defined as a promise, the flow will wait for it to + * settle. If the timeout expires before the promise settles, the promise + * returned by this function will be rejected. + * + * If this function is invoked with `timeout === 0`, or the timeout is omitted, + * the flow will wait indefinitely for the condition to be satisfied. + * + * @param {(!promise.Promise|function())} condition The condition to poll, + * or a promise to wait on. + * @param {number=} opt_timeout How long to wait, in milliseconds, for the + * condition to hold before timing out. If omitted, the flow will wait + * indefinitely. * @param {string=} opt_message An optional error message to include if the * wait times out; defaults to the empty string. - * @return {!webdriver.promise.Promise} A promise that will be resolved when the - * condition has been satisified. The promise shall be rejected if the wait - * times out waiting for the condition. + * @return {!promise.Promise} A promise that will be fulfilled + * when the condition has been satisified. The promise shall be rejected if + * the wait times out waiting for the condition. + * @throws {TypeError} If condition is not a function or promise or if timeout + * is not a number >= 0. + * @template T */ - wait(condition: Function, timeout: number, opt_message?: string): Promise; - - //endregion + wait(condition: Promise|Function, opt_timeout?: number, opt_message?: string): Promise; } } From e9ca2ce12a18b1aaa6ed494a9939323b2227a160 Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Thu, 9 Jul 2015 23:23:05 +0900 Subject: [PATCH 018/345] Update webdriver.promise.ControlFlow#execute Link: https://github.com/SeleniumHQ/selenium/commit/7268c783d3c42abac34f6006f2f3ef9cd3daf58b --- selenium-webdriver/selenium-webdriver-tests.ts | 1 + selenium-webdriver/selenium-webdriver.d.ts | 18 +++++++++++------- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index ca729eba5..c887cb2ed 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -1032,6 +1032,7 @@ function TestControlFlow() { eventType = webdriver.promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION; var stringPromise: webdriver.promise.Promise; + stringPromise = flow.execute(function() { return 'value'; }); stringPromise = flow.execute(function() { return stringPromise; }); stringPromise = flow.execute(function() { return stringPromise; }, 'Description'); diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index 9b065ff80..d9fe8cc4b 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -1596,16 +1596,20 @@ declare module webdriver { /** * Schedules a task for execution. If there is nothing currently in the - * queue, the task will be executed in the next turn of the event loop. + * queue, the task will be executed in the next turn of the event loop. If + * the task function is a generator, the task will be executed using + * {@link webdriver.promise.consume}. * - * @param {!Function} fn The function to call to start the task. If the - * function returns a {@link webdriver.promise.Promise}, this instance - * will wait for it to be resolved before starting the next task. + * @param {function(): (T|promise.Promise)} fn The function to + * call to start the task. If the function returns a + * {@link webdriver.promise.Promise}, this instance will wait for it to be + * resolved before starting the next task. * @param {string=} opt_description A description of the task. - * @return {!webdriver.promise.Promise} A promise that will be resolved with - * the result of the action. + * @return {!promise.Promise} A promise that will be resolved + * with the result of the action. + * @template T */ - execute(fn: Function, opt_description?: string): Promise; + execute(fn: ()=>(T|Promise), opt_description?: string): Promise; /** * Inserts a {@code setTimeout} into the command queue. This is equivalent to From 47f874f4ff35d5c8456c35474285a9c8e54cdb91 Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Thu, 9 Jul 2015 23:55:51 +0900 Subject: [PATCH 019/345] Update webdriver.promise.Promise Link: https://github.com/SeleniumHQ/selenium/commit/762a18540c7a78ca15599dedf4af3145ed7dd3fb --- .../selenium-webdriver-tests.ts | 24 +++++++++--- selenium-webdriver/selenium-webdriver.d.ts | 39 ++++++++++++------- 2 files changed, 43 insertions(+), 20 deletions(-) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index c887cb2ed..adf42a2cc 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -100,7 +100,8 @@ function TestFirefoxProfile() { function TestExecutors() { var exec: webdriver.CommandExecutor = executors.createExecutor("url"); - exec = executors.createExecutor(new webdriver.promise.Promise()); + var promise: webdriver.promise.Promise; + exec = executors.createExecutor(promise); } function TestBuilder() { @@ -694,7 +695,7 @@ function TestWebDriverWindow() { function TestWebDriver() { var session: webdriver.Session = new webdriver.Session('ABC', webdriver.Capabilities.android()); - var sessionPromise: webdriver.promise.Promise = new webdriver.promise.Promise(); + var sessionPromise: webdriver.promise.Promise; var executor: webdriver.CommandExecutor = executors.createExecutor("http://someserver"); var flow: webdriver.promise.ControlFlow = new webdriver.promise.ControlFlow(); var driver: webdriver.WebDriver = new webdriver.WebDriver(session, executor); @@ -780,10 +781,11 @@ function TestWebElement() { withCapabilities(webdriver.Capabilities.chrome()). build(); + var promise: webdriver.promise.Promise; var element: webdriver.WebElement; element = new webdriver.WebElement(driver, { ELEMENT: 'ID' }); - element = new webdriver.WebElement(driver, new webdriver.promise.Promise()); + element = new webdriver.WebElement(driver, promise); var voidPromise: webdriver.promise.Promise; var stringPromise: webdriver.promise.Promise; @@ -896,12 +898,12 @@ function TestPromiseModule() { var str: string = cancellationError.message; str = cancellationError.name; - var stringPromise: webdriver.promise.Promise = new webdriver.promise.Promise(); + var stringPromise: webdriver.promise.Promise; var numberPromise: webdriver.promise.Promise; var booleanPromise: webdriver.promise.Promise; var voidPromise: webdriver.promise.Promise; - webdriver.promise.all([new webdriver.promise.Promise()]).then(function (values: string[]) { }); + webdriver.promise.all([stringPromise]).then(function (values: string[]) { }); webdriver.promise.asap('abc', function(value: any){ return true; }); webdriver.promise.asap('abc', function(value: any){}, function(err: any) { return 'ABC'; }); @@ -1070,7 +1072,17 @@ function TestDeferred() { } function TestPromiseClass() { - var promise: webdriver.promise.Promise = new webdriver.promise.Promise(); + var controlFlow: webdriver.promise.ControlFlow; + var promise: webdriver.promise.Promise; + promise = new webdriver.promise.Promise(function( + onFulfilled: (value: string)=>void, + onRejected: ()=>void) { }); + promise = new webdriver.promise.Promise(function( + onFulfilled: (value: webdriver.promise.Promise)=>void, + onRejected: ()=>void) { }); + promise = new webdriver.promise.Promise(function( + onFulfilled: (value: string)=>void, + onRejected: ()=>void) { }, controlFlow); promise.cancel('Abort'); diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index d9fe8cc4b..871c39d8a 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -1289,28 +1289,39 @@ declare module webdriver { static isImplementation(object: any): boolean; } + interface IFulfilledCallback { + (value: T|IThenable|Thenable|void): void; + } + + interface IRejectedCallback { + (reason: any): void; + } + /** * Represents the eventual value of a completed operation. Each promise may be - * in one of three states: pending, resolved, or rejected. Each promise starts + * in one of three states: pending, fulfilled, or rejected. Each promise starts * in the pending state and may make a single transition to either a - * fulfilled or failed state. + * fulfilled or rejected state, at which point the promise is considered + * resolved. * - *

    This class is based on the Promise/A proposal from CommonJS. Additional - * functions are provided for API compatibility with Dojo Deferred objects. - * - * @see http://wiki.commonjs.org/wiki/Promises/A + * @implements {promise.Thenable} + * @template T + * @see http://promises-aplus.github.io/promises-spec/ */ class Promise implements IThenable { - - //region Constructors - /** - * @constructor - * @see http://wiki.commonjs.org/wiki/Promises/A + * @param {function( + * function((T|IThenable|Thenable)=), + * function(*=))} resolver + * Function that is invoked immediately to begin computation of this + * promise's value. The function should accept a pair of callback functions, + * one for fulfilling the promise and another for rejecting it. + * @param {promise.ControlFlow=} opt_flow The control flow + * this instance was created under. Defaults to the currently active flow. + * @constructor */ - constructor(); - - //endregion + constructor(resolver: (onFulfilled: IFulfilledCallback, onRejected: IRejectedCallback)=>void, opt_flow?: ControlFlow); + constructor(); // For angular-protractor/angular-protractor-tests.ts //region Methods From 4aaf75d9f2f61d96153499b4c67c85cef8483f62 Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Fri, 10 Jul 2015 12:20:56 +0900 Subject: [PATCH 020/345] Add webdriver.By.Hash as a type alias Limitation: We can not assign webdriver.By to any variables --- .../selenium-webdriver-tests.ts | 18 +-- selenium-webdriver/selenium-webdriver.d.ts | 116 ++++++++++-------- 2 files changed, 72 insertions(+), 62 deletions(-) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index adf42a2cc..5deb02f35 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -551,15 +551,15 @@ function TestLocator() { locator = webdriver.By.tagName('tag'); locator = webdriver.By.xpath('xpath'); - // var locatorHash: webdriver.By.Hash; - // locatorHash = { className: 'class' }; - // locatorHash = { css: 'css' }; - // locatorHash = { id: 'id' }; - // locatorHash = { linkText: 'link' }; - // locatorHash = { name: 'name' }; - // locatorHash = { partialLinkText: 'text' }; - // locatorHash = { tagName: 'tag' }; - // locatorHash = { xpath: 'xpath' }; + var locatorHash: webdriver.By.Hash; + locatorHash = { className: 'class' }; + locatorHash = { css: 'css' }; + locatorHash = { id: 'id' }; + locatorHash = { linkText: 'link' }; + locatorHash = { name: 'name' }; + locatorHash = { partialLinkText: 'text' }; + locatorHash = { tagName: 'tag' }; + locatorHash = { xpath: 'xpath' }; webdriver.By.js('script', 1, 2, 3)(driver).then(function (abc: number) { }); } diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index 871c39d8a..a5f6d87d2 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -4895,7 +4895,7 @@ declare module webdriver { thenFinally(callback: () => any): webdriver.promise.Promise; } - interface ILocatorStrategy { + module By { /** * Locates elements that have a specific class name. The returned locator * is equivalent to searching for elements with the CSS selector ".clazz". @@ -4905,7 +4905,7 @@ declare module webdriver { * @see http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#classes * @see http://www.w3.org/TR/CSS2/selector.html#class-html */ - className(value: string): Locator; + function className(value: string): Locator; /** * Locates elements using a CSS selector. For browsers that do not support @@ -4917,7 +4917,7 @@ declare module webdriver { * @return {!webdriver.Locator} The new locator. * @see http://www.w3.org/TR/CSS2/selector.html */ - css(value: string): Locator; + function css(value: string): Locator; /** * Locates an element by its ID. @@ -4925,7 +4925,7 @@ declare module webdriver { * @param {string} id The ID to search for. * @return {!webdriver.Locator} The new locator. */ - id(value: string): Locator; + function id(value: string): Locator; /** * Locates link elements whose {@linkplain webdriver.WebElement#getText visible @@ -4934,7 +4934,7 @@ declare module webdriver { * @param {string} text The link text to search for. * @return {!webdriver.Locator} The new locator. */ - linkText(value: string): Locator; + function linkText(value: string): Locator; /** * Locates an elements by evaluating a @@ -4946,7 +4946,7 @@ declare module webdriver { * @return {function(!webdriver.WebDriver): !webdriver.promise.Promise} A new, * JavaScript-based locator function. */ - js(script: any, ...var_args: any[]): (WebDriver: webdriver.WebDriver) => webdriver.promise.Promise; + function js(script: any, ...var_args: any[]): (WebDriver: webdriver.WebDriver) => webdriver.promise.Promise; /** * Locates elements whose {@code name} attribute has the given value. @@ -4954,7 +4954,7 @@ declare module webdriver { * @param {string} name The name attribute to search for. * @return {!webdriver.Locator} The new locator. */ - name(value: string): Locator; + function name(value: string): Locator; /** * Locates link elements whose {@linkplain webdriver.WebElement#getText visible @@ -4963,7 +4963,7 @@ declare module webdriver { * @param {string} text The substring to check for in a link's visible text. * @return {!webdriver.Locator} The new locator. */ - partialLinkText(value: string): Locator; + function partialLinkText(value: string): Locator; /** * Locates elements with a given tag name. The returned locator is @@ -4975,7 +4975,7 @@ declare module webdriver { * @return {!webdriver.Locator} The new locator. * @see http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html */ - tagName(value: string): Locator; + function tagName(value: string): Locator; /** * Locates elements matching a XPath selector. Care should be taken when @@ -4989,44 +4989,54 @@ declare module webdriver { * @return {!webdriver.Locator} The new locator. * @see http://www.w3.org/TR/xpath/ */ + function xpath(value: string): Locator; + + /** + * Short-hand expressions for the primary element locator strategies. + * For example the following two statements are equivalent: + * + * var e1 = driver.findElement(webdriver.By.id('foo')); + * var e2 = driver.findElement({id: 'foo'}); + * + * Care should be taken when using JavaScript minifiers (such as the + * Closure compiler), as locator hashes will always be parsed using + * the un-obfuscated properties listed. + * + * @typedef {( + * {className: string}| + * {css: string}| + * {id: string}| + * {js: string}| + * {linkText: string}| + * {name: string}| + * {partialLinkText: string}| + * {tagName: string}| + * {xpath: string})} + */ + type Hash = {className: string}| + {css: string}| + {id: string}| + {js: string}| + {linkText: string}| + {name: string}| + {partialLinkText: string}| + {tagName: string}| + {xpath: string}; + } + + // For angular-protractor/angular-protractor-tests.ts + interface ILocatorStrategy { + className(value: string): Locator; + css(value: string): Locator; + id(value: string): Locator; + linkText(value: string): Locator; + js(script: any, ...var_args: any[]): (WebDriver: webdriver.WebDriver) => webdriver.promise.Promise; + name(value: string): Locator; + partialLinkText(value: string): Locator; + tagName(value: string): Locator; xpath(value: string): Locator; } - var By: ILocatorStrategy; - - // module By { - // /** - // * Short-hand expressions for the primary element locator strategies. - // * For example the following two statements are equivalent: - // * - // * var e1 = driver.findElement(webdriver.By.id('foo')); - // * var e2 = driver.findElement({id: 'foo'}); - // * - // * Care should be taken when using JavaScript minifiers (such as the - // * Closure compiler), as locator hashes will always be parsed using - // * the un-obfuscated properties listed. - // * - // * @typedef {( - // * {className: string}| - // * {css: string}| - // * {id: string}| - // * {js: string}| - // * {linkText: string}| - // * {name: string}| - // * {partialLinkText: string}| - // * {tagName: string}| - // * {xpath: string})} - // */ - // type Hash = {className: string}| - // {css: string}| - // {id: string}| - // {js: string}| - // {linkText: string}| - // {name: string}| - // {partialLinkText: string}| - // {tagName: string}| - // {xpath: string}; - // } /** * An element locator. @@ -5047,15 +5057,15 @@ declare module webdriver { * @const */ static Strategy: { - className: typeof By.className; - css: typeof By.css; - id: typeof By.id; - js: typeof By.js; - linkText: typeof By.linkText; - name: typeof By.name; - partialLinkText: typeof By.partialLinkText; - tagName: typeof By.tagName; - xpath: typeof By.xpath; + className: typeof webdriver.By.className; + css: typeof webdriver.By.css; + id: typeof webdriver.By.id; + js: typeof webdriver.By.js; + linkText: typeof webdriver.By.linkText; + name: typeof webdriver.By.name; + partialLinkText: typeof webdriver.By.partialLinkText; + tagName: typeof webdriver.By.tagName; + xpath: typeof webdriver.By.xpath; }; /** From 04fd7c612df1b9faf9d4af229edffffffd537a91 Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Fri, 10 Jul 2015 14:59:55 +0900 Subject: [PATCH 021/345] Remove ILocatorStrategy --- angular-protractor/angular-protractor.d.ts | 16 +++++++++++++++- selenium-webdriver/selenium-webdriver-tests.ts | 3 +++ selenium-webdriver/selenium-webdriver.d.ts | 14 -------------- 3 files changed, 18 insertions(+), 15 deletions(-) diff --git a/angular-protractor/angular-protractor.d.ts b/angular-protractor/angular-protractor.d.ts index 76f0b5f10..39cb7a81a 100644 --- a/angular-protractor/angular-protractor.d.ts +++ b/angular-protractor/angular-protractor.d.ts @@ -1228,7 +1228,21 @@ declare module protractor { row(index: number): LocatorWithColumn; } - interface IProtractorLocatorStrategy extends webdriver.ILocatorStrategy { + interface IProtractorLocatorStrategy { + /** + * webdriver's By is an enum of locator functions, so we must set it to + * a prototype before inheriting from it. + */ + className: typeof webdriver.By.className; + css: typeof webdriver.By.css; + id: typeof webdriver.By.id; + linkText: typeof webdriver.By.linkText; + js: typeof webdriver.By.js; + name: typeof webdriver.By.name; + partialLinkText: typeof webdriver.By.partialLinkText; + tagName: typeof webdriver.By.tagName; + xpath: typeof webdriver.By.xpath; + /** * Add a locator to this instance of ProtractorBy. This locator can then be * used with element(by.locatorName(args)). diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index 5deb02f35..e69f8e64d 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -551,6 +551,9 @@ function TestLocator() { locator = webdriver.By.tagName('tag'); locator = webdriver.By.xpath('xpath'); + // Can import "By" without import declarations + var By = webdriver.By; + var locatorHash: webdriver.By.Hash; locatorHash = { className: 'class' }; locatorHash = { css: 'css' }; diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index a5f6d87d2..dbe4e1325 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -5024,20 +5024,6 @@ declare module webdriver { {xpath: string}; } - // For angular-protractor/angular-protractor-tests.ts - interface ILocatorStrategy { - className(value: string): Locator; - css(value: string): Locator; - id(value: string): Locator; - linkText(value: string): Locator; - js(script: any, ...var_args: any[]): (WebDriver: webdriver.WebDriver) => webdriver.promise.Promise; - name(value: string): Locator; - partialLinkText(value: string): Locator; - tagName(value: string): Locator; - xpath(value: string): Locator; - } - - /** * An element locator. */ From 2fbe16791b86c48dce2a08b333180ccd212e9696 Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Fri, 10 Jul 2015 15:02:51 +0900 Subject: [PATCH 022/345] Switch to use "webdriver.By.Hash" instead of "any" --- selenium-webdriver/selenium-webdriver.d.ts | 40 +++++++--------------- 1 file changed, 12 insertions(+), 28 deletions(-) diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index dbe4e1325..e1954ca35 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -1816,11 +1816,7 @@ declare module webdriver { * The frame identifier. * @return {!until.Condition.} A new condition. */ - function ableToSwitchToFrame(frame: number): Condition; - function ableToSwitchToFrame(frame: IWebElement): Condition; - function ableToSwitchToFrame(frame: Locator): Condition; - function ableToSwitchToFrame(frame: (webdriver: WebDriver) => IWebElement): Condition; - function ableToSwitchToFrame(frame: any): Condition; + function ableToSwitchToFrame(frame: number|IWebElement|Locator|By.Hash|((webdriver: WebDriver)=>IWebElement)): Condition; /** * Creates a condition that waits for an alert to be opened. Upon success, the @@ -1892,8 +1888,7 @@ declare module webdriver { * to use. * @return {!until.Condition.} The new condition. */ - function elementLocated(locator: Locator): Condition; - function elementLocated(locator: any): Condition; + function elementLocated(locator: Locator|By.Hash|Function): Condition; /** * Creates a condition that will wait for the given element's @@ -1940,8 +1935,7 @@ declare module webdriver { * @return {!until.Condition.>} The new * condition. */ - function elementsLocated(locator: Locator): Condition; - function elementsLocated(locator: any): Condition; + function elementsLocated(locator: Locator|By.Hash|Function): Condition; /** * Creates a condition that will wait for the given element to become stale. An @@ -4100,8 +4094,7 @@ declare module webdriver { * commands against the located element. If the element is not found, the * element will be invalidated and all scheduled commands aborted. */ - findElement(locatorOrElement: Locator): WebElementPromise; - findElement(locatorOrElement: any): WebElementPromise; + findElement(locatorOrElement: Locator|By.Hash|WebElement|Function): WebElementPromise; /** * Schedules a command to test if an element is present on the page. @@ -4116,8 +4109,7 @@ declare module webdriver { * @return {!webdriver.promise.Promise.} A promise that will resolve * with whether the element is present on the page. */ - isElementPresent(locatorOrElement: Locator): webdriver.promise.Promise; - isElementPresent(locatorOrElement: any): webdriver.promise.Promise; + isElementPresent(locatorOrElement: Locator|By.Hash|WebElement|Function): webdriver.promise.Promise; /** * Schedule a command to search for multiple elements on the page. @@ -4127,8 +4119,7 @@ declare module webdriver { * @return {!webdriver.promise.Promise.>} A * promise that will resolve to an array of WebElements. */ - findElements(locator: Locator): webdriver.promise.Promise; - findElements(locator: any): webdriver.promise.Promise; + findElements(locator: Locator|By.Hash|Function): webdriver.promise.Promise; /** * Schedule a command to take a screenshot. The driver makes a best effort to @@ -4193,7 +4184,6 @@ declare module webdriver { * }); *

  • */ - interface IWebElement { //region Methods @@ -4428,8 +4418,7 @@ declare module webdriver { * commands against the located element. If the element is not found, the * element will be invalidated and all scheduled commands aborted. */ - findElement(locator: Locator): WebElementPromise; - findElement(locator: any): WebElementPromise; + findElement(locator: Locator|By.Hash|Function): WebElementPromise; /** * Schedules a command to test if there is at least one descendant of this @@ -4440,8 +4429,7 @@ declare module webdriver { * @return {!webdriver.promise.Promise.} A promise that will be * resolved with whether an element could be located on the page. */ - isElementPresent(locator: Locator): webdriver.promise.Promise; - isElementPresent(locator: any): webdriver.promise.Promise; + isElementPresent(locator: Locator|By.Hash|Function): webdriver.promise.Promise; /** * Schedules a command to find all of the descendants of this element that @@ -4452,8 +4440,7 @@ declare module webdriver { * @return {!webdriver.promise.Promise.>} A * promise that will resolve to an array of WebElements. */ - findElements(locator: Locator): webdriver.promise.Promise; - findElements(locator: any): webdriver.promise.Promise; + findElements(locator: Locator|By.Hash|Function): webdriver.promise.Promise; } class WebElement implements IWebElement, IWebElementFinders { @@ -4531,8 +4518,7 @@ declare module webdriver { * commands against the located element. If the element is not found, the * element will be invalidated and all scheduled commands aborted. */ - findElement(locator: Locator): WebElementPromise; - findElement(locator: any): WebElementPromise; + findElement(locator: Locator|By.Hash|Function): WebElementPromise; /** * Schedules a command to test if there is at least one descendant of this @@ -4543,8 +4529,7 @@ declare module webdriver { * @return {!webdriver.promise.Promise.} A promise that will be * resolved with whether an element could be located on the page. */ - isElementPresent(locator: Locator): webdriver.promise.Promise; - isElementPresent(locator: any): webdriver.promise.Promise; + isElementPresent(locator: Locator|By.Hash|Function): webdriver.promise.Promise; /** * Schedules a command to find all of the descendants of this element that @@ -4555,8 +4540,7 @@ declare module webdriver { * @return {!webdriver.promise.Promise.>} A * promise that will resolve to an array of WebElements. */ - findElements(locator: Locator): webdriver.promise.Promise; - findElements(locator: any): webdriver.promise.Promise; + findElements(locator: Locator|By.Hash|Function): webdriver.promise.Promise; /** * Schedules a command to click on this element. From d019180cb868988184b782ad44bfbabfe1ad6814 Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Fri, 10 Jul 2015 15:06:28 +0900 Subject: [PATCH 023/345] Follow signatures to the recent doc --- selenium-webdriver/selenium-webdriver-tests.ts | 15 ++++++++++----- selenium-webdriver/selenium-webdriver.d.ts | 8 +++----- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index e69f8e64d..5d102b01a 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -714,9 +714,10 @@ function TestWebDriver() { var touchActions: webdriver.TouchSequence = driver.touchActions(); // call - stringPromise = driver.call(function(){}); - stringPromise = driver.call(function(){ var d: any = this;}, driver); - stringPromise = driver.call(function(a: number){}, driver, 1); + stringPromise = driver.call(function(){ return 'value'; }); + stringPromise = driver.call(function(){ return stringPromise; }); + stringPromise = driver.call(function(){ var d: any = this; return 'value'; }, driver); + stringPromise = driver.call(function(a: number){ return 'value'; }, driver, 1); voidPromise = driver.close(); flow = driver.controlFlow(); @@ -772,8 +773,12 @@ function TestWebDriver() { voidPromise = driver.sleep(123); stringPromise = driver.takeScreenshot(); - booleanPromise = driver.wait(function() { return true; }, 123); - booleanPromise = driver.wait(function() { return true; }, 123, 'Message'); + var booleanCondition: webdriver.until.Condition; + booleanPromise = driver.wait(booleanPromise); + booleanPromise = driver.wait(booleanCondition); + booleanPromise = driver.wait(function(driver: webdriver.WebDriver) { return true; }); + booleanPromise = driver.wait(booleanPromise, 123); + booleanPromise = driver.wait(booleanPromise, 123, 'Message'); driver = webdriver.WebDriver.attachToSession(executor, 'ABC'); driver = webdriver.WebDriver.createSession(executor, webdriver.Capabilities.android()); diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index e1954ca35..17a2c1020 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -3922,8 +3922,7 @@ declare module webdriver { * scripts return value. * @template T */ - executeAsyncScript(script: string, ...var_args: any[]): webdriver.promise.Promise; - executeAsyncScript(script: Function, ...var_args: any[]): webdriver.promise.Promise; + executeAsyncScript(script: string|Function, ...var_args: any[]): webdriver.promise.Promise; /** * Schedules a command to execute a custom function. @@ -3935,7 +3934,7 @@ declare module webdriver { * with the function's result. * @template T */ - call(fn: Function, opt_scope?: any, ...var_args: any[]): webdriver.promise.Promise; + call(fn: (...var_args: any[])=>(T|webdriver.promise.Promise), opt_scope?: any, ...var_args: any[]): webdriver.promise.Promise; /** * Schedules a command to wait for a condition to hold. The condition may be @@ -3983,8 +3982,7 @@ declare module webdriver { * rejected if the condition times out. * @template T */ - wait(condition: webdriver.until.Condition, timeout: number, opt_message?: string): webdriver.promise.Promise; - wait(condition: (webdriver: WebDriver) => any, timeout: number, opt_message?: string): webdriver.promise.Promise; + wait(condition: webdriver.promise.Promise|webdriver.until.Condition|((driver: WebDriver)=>T), timeout?: number, opt_message?: string): webdriver.promise.Promise; /** * Schedules a command to make the driver sleep for the given amount of time. From 37a07946a59dd0627fc811f93d4d353d218f9826 Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Fri, 10 Jul 2015 17:33:47 +0900 Subject: [PATCH 024/345] Add webdriver.Serializable Link: https://github.com/SeleniumHQ/selenium/commit/36ae4e02490ea71ab22c4094b46aadd7a5eb42f1#diff-9fd8281e531ca110881ce204a571c9e5 --- selenium-webdriver/selenium-webdriver.d.ts | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index 17a2c1020..205812695 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -4159,6 +4159,26 @@ declare module webdriver { ELEMENT: string; } + /** + * Defines an object that can be asynchronously serialized to its WebDriver + * wire representation. + * + * @constructor + * @template T + */ + interface Serializable { + /** + * Returns either this instance's serialized represention, if immediately + * available, or a promise for its serialized representation. This function is + * conceptually equivalent to objects that have a {@code toJSON()} property, + * except the serialize() result may be a promise or an object containing a + * promise (which are not directly JSON friendly). + * + * @return {!(T|IThenable.)} This instance's serialized wire format. + */ + serialize(): T|webdriver.promise.IThenable; + } + /** * Represents a DOM element. WebElements can be found by searching from the * document root using a {@code webdriver.WebDriver} instance, or by searching From 2381796282a42320ca73bb34082a6e006ebe6a4d Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Fri, 10 Jul 2015 18:11:20 +0900 Subject: [PATCH 025/345] Update webdriver.WebElement --- .../selenium-webdriver-tests.ts | 11 +- selenium-webdriver/selenium-webdriver.d.ts | 272 +++++++++++------- 2 files changed, 177 insertions(+), 106 deletions(-) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index 5d102b01a..664401628 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -784,6 +784,11 @@ function TestWebDriver() { driver = webdriver.WebDriver.createSession(executor, webdriver.Capabilities.android()); } +function TestSerializable() { + var serializable: webdriver.Serializable; + var serial: string|webdriver.promise.Promise = serializable.serialize(); +} + function TestWebElement() { var driver: webdriver.WebDriver = new webdriver.Builder(). withCapabilities(webdriver.Capabilities.chrome()). @@ -824,11 +829,15 @@ function TestWebElement() { booleanPromise = element.isEnabled(); booleanPromise = element.isSelected(); voidPromise = element.sendKeys('A', 'B', 'C'); + voidPromise = element.sendKeys(stringPromise, stringPromise, stringPromise); voidPromise = element.submit(); - element.getId().then(function (id: webdriver.IWebElementId) { }); + element.getId().then(function (id: typeof webdriver.WebElement.Id) { }); + element.getRawId().then(function (id: string) { }); + element.serialize().then(function (id: typeof webdriver.WebElement.Id) { }); booleanPromise = webdriver.WebElement.equals(element, new webdriver.WebElement(driver, { ELEMENT: 'ID2' })); + var id: typeof webdriver.WebElement.Id = webdriver.WebElement.Id; var key: string = webdriver.WebElement.ELEMENT_KEY; } diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index 205812695..6406d16cf 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -4461,9 +4461,52 @@ declare module webdriver { findElements(locator: Locator|By.Hash|Function): webdriver.promise.Promise; } - class WebElement implements IWebElement, IWebElementFinders { - //region Constructors + /** + * Defines an object that can be asynchronously serialized to its WebDriver + * wire representation. + * + * @constructor + * @template T + */ + interface Serializable { + /** + * Returns either this instance's serialized represention, if immediately + * available, or a promise for its serialized representation. This function is + * conceptually equivalent to objects that have a {@code toJSON()} property, + * except the serialize() result may be a promise or an object containing a + * promise (which are not directly JSON friendly). + * + * @return {!(T|IThenable.)} This instance's serialized wire format. + */ + serialize(): T|webdriver.promise.IThenable; + } + + + /** + * Represents a DOM element. WebElements can be found by searching from the + * document root using a {@link webdriver.WebDriver} instance, or by searching + * under another WebElement: + * + * driver.get('http://www.google.com'); + * var searchForm = driver.findElement(By.tagName('form')); + * var searchBox = searchForm.findElement(By.name('q')); + * searchBox.sendKeys('webdriver'); + * + * The WebElement is implemented as a promise for compatibility with the promise + * API. It will always resolve itself when its internal state has been fully + * resolved and commands may be issued against the element. This can be used to + * catch errors when an element cannot be located on the page: + * + * driver.findElement(By.id('not-there')).then(function(element) { + * alert('Found an element that was not expected to be there!'); + * }, function(error) { + * alert('The element was not found, as expected'); + * }); + * + * @extends {webdriver.Serializable.} + */ + class WebElement implements Serializable { /** * @param {!webdriver.WebDriver} driver The parent WebDriver instance for this * element. @@ -4472,12 +4515,14 @@ declare module webdriver { * underlying DOM element. * @constructor */ - constructor(driver: WebDriver, id: webdriver.promise.Promise); - constructor(driver: WebDriver, id: IWebElementId); + constructor(driver: WebDriver, id: webdriver.promise.Promise|IWebElementId); - //endregion - - //region Static Properties + /** + * Wire protocol definition of a WebElement ID. + * @typedef {{ELEMENT: string}} + * @see https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol + */ + static Id: IWebElementId; /** * The property key used in the wire protocol to indicate that a JSON object @@ -4487,9 +4532,6 @@ declare module webdriver { */ static ELEMENT_KEY: string; - //endregion - - //region Methods /** * @return {!webdriver.WebDriver} The parent driver for this instance. @@ -4498,37 +4540,35 @@ declare module webdriver { /** * Schedule a command to find a descendant of this element. If the element - * cannot be found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will + * cannot be found, a {@link bot.ErrorCode.NO_SUCH_ELEMENT} result will * be returned by the driver. Unlike other commands, this error cannot be * suppressed. In other words, scheduling a command to find an element doubles * as an assert that the element is present on the page. To test whether an - * element is present on the page, use {@code #isElementPresent} instead. + * element is present on the page, use {@link #isElementPresent} instead. * - *

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

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

    You may also provide a custom locator function, which takes as input + * var e1 = element.findElement(By.id('foo')); + * var e2 = element.findElement({id:'foo'}); + * + * You may also provide a custom locator function, which takes as input * this WebDriver instance and returns a {@link webdriver.WebElement}, or a * promise that will resolve to a WebElement. For example, to find the first * visible link on a page, you could write: - *

    -         * var link = element.findElement(firstVisibleLink);
              *
    -         * function firstVisibleLink(element) {
    -         *   var links = element.findElements(By.tagName('a'));
    -         *   return webdriver.promise.filter(links, function(link) {
    -         *     return links.isDisplayed();
    -         *   }).then(function(visibleLinks) {
    -         *     return visibleLinks[0];
    -         *   });
    -         * }
    -         * 
    + * var link = element.findElement(firstVisibleLink); + * + * function firstVisibleLink(element) { + * var links = element.findElements(By.tagName('a')); + * return webdriver.promise.filter(links, function(link) { + * return links.isDisplayed(); + * }).then(function(visibleLinks) { + * return visibleLinks[0]; + * }); + * } * * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The * locator strategy to use when searching for the element. @@ -4562,57 +4602,70 @@ declare module webdriver { /** * Schedules a command to click on this element. - * @return {!webdriver.promise.Promise} A promise that will be resolved when - * the click command has completed. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the click command has completed. */ click(): webdriver.promise.Promise; /** * Schedules a command to type a sequence on the DOM element represented by this * instance. - *

    + * * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is * processed in the keysequence, that key state is toggled until one of the * following occurs: - *

      - *
    • The modifier key is encountered again in the sequence. At this point the - * state of the key is toggled (along with the appropriate keyup/down events). - *
    • - *
    • The {@code webdriver.Key.NULL} key is encountered in the sequence. When - * this key is encountered, all modifier keys current in the down state are - * released (with accompanying keyup events). The NULL key can be used to - * simulate common keyboard shortcuts: - * - * element.sendKeys("text was", - * webdriver.Key.CONTROL, "a", webdriver.Key.NULL, - * "now text is"); - * // Alternatively: - * element.sendKeys("text was", - * webdriver.Key.chord(webdriver.Key.CONTROL, "a"), - * "now text is"); - *
    • - *
    • The end of the keysequence is encountered. When there are no more keys - * to type, all depressed modifier keys are released (with accompanying keyup - * events). - *
    • - *
    - * Note: On browsers where native keyboard events are not yet - * supported (e.g. Firefox on OS X), key events will be synthesized. Special + * + * - The modifier key is encountered again in the sequence. At this point the + * state of the key is toggled (along with the appropriate keyup/down events). + * - The {@link webdriver.Key.NULL} key is encountered in the sequence. When + * this key is encountered, all modifier keys current in the down state are + * released (with accompanying keyup events). The NULL key can be used to + * simulate common keyboard shortcuts: + * + * element.sendKeys("text was", + * webdriver.Key.CONTROL, "a", webdriver.Key.NULL, + * "now text is"); + * // Alternatively: + * element.sendKeys("text was", + * webdriver.Key.chord(webdriver.Key.CONTROL, "a"), + * "now text is"); + * + * - The end of the keysequence is encountered. When there are no more keys + * to type, all depressed modifier keys are released (with accompanying keyup + * events). + * + * If this element is a file input ({@code }), the + * specified key sequence should specify the path to the file to attach to + * the element. This is analgous to the user clicking "Browse..." and entering + * the path into the file select dialog. + * + * var form = driver.findElement(By.css('form')); + * var element = form.findElement(By.css('input[type=file]')); + * element.sendKeys('/path/to/file.txt'); + * form.submit(); + * + * For uploads to function correctly, the entered path must reference a file + * on the _browser's_ machine, not the local machine running this script. When + * running against a remote Selenium server, a {@link webdriver.FileDetector} + * may be used to transparently copy files to the remote machine before + * attempting to upload them in the browser. + * + * __Note:__ On browsers where native keyboard events are not supported + * (e.g. Firefox on OS X), key events will be synthesized. Special * punctionation keys will be synthesized according to a standard QWERTY en-us * keyboard layout. * - * @param {...string} var_args The sequence of keys to - * type. All arguments will be joined into a single sequence (var_args is - * permitted for convenience). - * @return {!webdriver.promise.Promise} A promise that will be resolved when all - * keys have been typed. + * @param {...(string|!webdriver.promise.Promise)} var_args The sequence + * of keys to type. All arguments will be joined into a single sequence. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when all keys have been typed. */ - sendKeys(...var_args: string[]): webdriver.promise.Promise; + sendKeys(...var_args: Array>): webdriver.promise.Promise; /** * Schedules a command to query for the tag/node name of this element. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * element's tag name. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the element's tag name. */ getTagName(): webdriver.promise.Promise; @@ -4622,81 +4675,85 @@ declare module webdriver { * its parent, the parent will be queried for its value. Where possible, color * values will be converted to their hex representation (e.g. #00ff00 instead of * rgb(0, 255, 0)). - *

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

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

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

      - *
    • "class" - *
    • "readonly" - *
    + * + * - "class" + * - "readonly" + * * @param {string} attributeName The name of the attribute to query. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * attribute's value. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the attribute's value. The returned value will always be + * either a string or null. */ getAttribute(attributeName: string): webdriver.promise.Promise; /** * Get the visible (i.e. not hidden by CSS) innerText of this element, including * sub-elements, without any leading or trailing whitespace. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * element's visible text. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the element's visible text. */ getText(): webdriver.promise.Promise; /** * Schedules a command to compute the size of this element's bounding box, in * pixels. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * element's size as a {@code {width:number, height:number}} object. + * @return {!webdriver.promise.Promise.<{width: number, height: number}>} A + * promise that will be resolved with the element's size as a + * {@code {width:number, height:number}} object. */ getSize(): webdriver.promise.Promise; /** * Schedules a command to compute the location of this element in page space. - * @return {!webdriver.promise.Promise} A promise that will be resolved to the - * element's location as a {@code {x:number, y:number}} object. + * @return {!webdriver.promise.Promise.<{x: number, y: number}>} A promise that + * will be resolved to the element's location as a + * {@code {x:number, y:number}} object. */ getLocation(): webdriver.promise.Promise; /** * Schedules a command to query whether the DOM element represented by this * instance is enabled, as dicted by the {@code disabled} attribute. - * @return {!webdriver.promise.Promise} A promise that will be resolved with - * whether this element is currently enabled. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with whether this element is currently enabled. */ isEnabled(): webdriver.promise.Promise; /** * Schedules a command to query whether this element is selected. - * @return {!webdriver.promise.Promise} A promise that will be resolved with - * whether this element is currently selected. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with whether this element is currently selected. */ isSelected(): webdriver.promise.Promise; @@ -4704,8 +4761,8 @@ declare module webdriver { * Schedules a command to submit the form containing this element (or this * element if it is a FORM element). This command is a no-op if the element is * not contained in a form. - * @return {!webdriver.promise.Promise} A promise that will be resolved when - * the form has been submitted. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the form has been submitted. */ submit(): webdriver.promise.Promise; @@ -4713,22 +4770,22 @@ declare module webdriver { * Schedules a command to clear the {@code value} of this element. This command * has no effect if the underlying DOM element is neither a text INPUT element * nor a TEXTAREA element. - * @return {!webdriver.promise.Promise} A promise that will be resolved when - * the element has been cleared. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the element has been cleared. */ clear(): webdriver.promise.Promise; /** * Schedules a command to test whether this element is currently displayed. - * @return {!webdriver.promise.Promise} A promise that will be resolved with - * whether this element is currently visible on the page. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with whether this element is currently visible on the page. */ isDisplayed(): webdriver.promise.Promise; /** * Schedules a command to retrieve the outer HTML of this element. - * @return {!webdriver.promise.Promise} A promise that will be resolved with - * the element's outer HTML. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the element's outer HTML. */ getOuterHtml(): webdriver.promise.Promise; @@ -4740,6 +4797,17 @@ declare module webdriver { */ getId(): webdriver.promise.Promise; + /** + * Returns the raw ID string ID for this element. + * @return {!webdriver.promise.Promise} A promise that resolves to this + * element's raw ID as a string value. + * @package + */ + getRawId(): webdriver.promise.Promise; + + /** @override */ + serialize(): webdriver.promise.Promise; + /** * Schedules a command to retrieve the inner HTML of this element. * @return {!webdriver.promise.Promise} A promise that will be resolved with the @@ -4747,10 +4815,6 @@ declare module webdriver { */ getInnerHtml(): webdriver.promise.Promise; - //endregion - - //region Static Methods - /** * Compares to WebElements for equality. * @param {!webdriver.WebElement} a A WebElement. @@ -4759,8 +4823,6 @@ declare module webdriver { * whether the two WebElements are equal. */ static equals(a: WebElement, b: WebElement): webdriver.promise.Promise; - - //endregion } /** From 7997188acd0dfc6b953bef6fa30d60989e1e2e5d Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Fri, 10 Jul 2015 18:40:06 +0900 Subject: [PATCH 026/345] Remove references for IWebElement --- .../selenium-webdriver-tests.ts | 4 +- selenium-webdriver/selenium-webdriver.d.ts | 50 +++++++++---------- 2 files changed, 27 insertions(+), 27 deletions(-) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index 664401628..d8546c6df 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -1013,8 +1013,8 @@ function TestUntilModule() { var conditionB: webdriver.until.Condition = new webdriver.until.Condition('message', function (driver: webdriver.WebDriver) { return true; }); var conditionBBase: webdriver.until.Condition = conditionB; - var conditionWebElement: webdriver.until.Condition; - var conditionWebElements: webdriver.until.Condition; + var conditionWebElement: webdriver.until.Condition; + var conditionWebElements: webdriver.until.Condition; conditionB = webdriver.until.ableToSwitchToFrame(5); var conditionAlert: webdriver.until.Condition = webdriver.until.alertIsPresent(); diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index 6406d16cf..d54ea62fa 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -1816,7 +1816,7 @@ declare module webdriver { * The frame identifier. * @return {!until.Condition.} A new condition. */ - function ableToSwitchToFrame(frame: number|IWebElement|Locator|By.Hash|((webdriver: WebDriver)=>IWebElement)): Condition; + function ableToSwitchToFrame(frame: number|WebElement|Locator|By.Hash|((webdriver: WebDriver)=>WebElement)): Condition; /** * Creates a condition that waits for an alert to be opened. Upon success, the @@ -1833,7 +1833,7 @@ declare module webdriver { * @return {!until.Condition.} The new condition. * @see webdriver.WebDriver#isEnabled */ - function elementIsDisabled(element: IWebElement): Condition; + function elementIsDisabled(element: WebElement): Condition; /** * Creates a condition that will wait for the given element to be enabled. @@ -1842,7 +1842,7 @@ declare module webdriver { * @return {!until.Condition.} The new condition. * @see webdriver.WebDriver#isEnabled */ - function elementIsEnabled(element: IWebElement): Condition; + function elementIsEnabled(element: WebElement): Condition; /** * Creates a condition that will wait for the given element to be deselected. @@ -1851,7 +1851,7 @@ declare module webdriver { * @return {!until.Condition.} The new condition. * @see webdriver.WebDriver#isSelected */ - function elementIsNotSelected(element: IWebElement): Condition; + function elementIsNotSelected(element: WebElement): Condition; /** * Creates a condition that will wait for the given element to be in the DOM, @@ -1861,7 +1861,7 @@ declare module webdriver { * @return {!until.Condition.} The new condition. * @see webdriver.WebDriver#isDisplayed */ - function elementIsNotVisible(element: IWebElement): Condition; + function elementIsNotVisible(element: WebElement): Condition; /** * Creates a condition that will wait for the given element to be selected. @@ -1869,7 +1869,7 @@ declare module webdriver { * @return {!until.Condition.} The new condition. * @see webdriver.WebDriver#isSelected */ - function elementIsSelected(element: IWebElement): Condition; + function elementIsSelected(element: WebElement): Condition; /** * Creates a condition that will wait for the given element to become visible. @@ -1878,7 +1878,7 @@ declare module webdriver { * @return {!until.Condition.} The new condition. * @see webdriver.WebDriver#isDisplayed */ - function elementIsVisible(element: IWebElement): Condition; + function elementIsVisible(element: WebElement): Condition; /** * Creates a condition that will loop until an element is @@ -1888,7 +1888,7 @@ declare module webdriver { * to use. * @return {!until.Condition.} The new condition. */ - function elementLocated(locator: Locator|By.Hash|Function): Condition; + function elementLocated(locator: Locator|By.Hash|Function): Condition; /** * Creates a condition that will wait for the given element's @@ -1900,7 +1900,7 @@ declare module webdriver { * @return {!until.Condition.} The new condition. * @see webdriver.WebDriver#getText */ - function elementTextContains(element: IWebElement, substr: string): Condition; + function elementTextContains(element: WebElement, substr: string): Condition; /** * Creates a condition that will wait for the given element's @@ -1912,7 +1912,7 @@ declare module webdriver { * @return {!until.Condition.} The new condition. * @see webdriver.WebDriver#getText */ - function elementTextIs(element: IWebElement, text: string): Condition; + function elementTextIs(element: WebElement, text: string): Condition; /** * Creates a condition that will wait for the given element's @@ -1924,7 +1924,7 @@ declare module webdriver { * @return {!until.Condition.} The new condition. * @see webdriver.WebDriver#getText */ - function elementTextMatches(element: IWebElement, regex: RegExp): Condition; + function elementTextMatches(element: WebElement, regex: RegExp): Condition; /** * Creates a condition that will loop until at least one element is @@ -1935,7 +1935,7 @@ declare module webdriver { * @return {!until.Condition.>} The new * condition. */ - function elementsLocated(locator: Locator|By.Hash|Function): Condition; + function elementsLocated(locator: Locator|By.Hash|Function): Condition; /** * Creates a condition that will wait for the given element to become stale. An @@ -1945,7 +1945,7 @@ declare module webdriver { * @param {!webdriver.WebElement} element The element that should become stale. * @return {!until.Condition.} The new condition. */ - function stalenessOf(element: IWebElement): Condition; + function stalenessOf(element: WebElement): Condition; /** * Creates a condition that will wait for the current page's title to contain @@ -2135,7 +2135,7 @@ declare module webdriver { * Defaults to (0, 0). * @return {!webdriver.ActionSequence} A self reference. */ - mouseMove(location: IWebElement, opt_offset?: ILocation): ActionSequence; + mouseMove(location: WebElement, opt_offset?: ILocation): ActionSequence; mouseMove(location: ILocation): ActionSequence; /** @@ -2160,7 +2160,7 @@ declare module webdriver { * first argument. * @return {!webdriver.ActionSequence} A self reference. */ - mouseDown(opt_elementOrButton?: IWebElement, opt_button?: number): ActionSequence; + mouseDown(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; mouseDown(opt_elementOrButton?: number): ActionSequence; /** @@ -2183,7 +2183,7 @@ declare module webdriver { * first argument. * @return {!webdriver.ActionSequence} A self reference. */ - mouseUp(opt_elementOrButton?: IWebElement, opt_button?: number): ActionSequence; + mouseUp(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; mouseUp(opt_elementOrButton?: number): ActionSequence; /** @@ -2195,8 +2195,8 @@ declare module webdriver { * location to drag to, either as another WebElement or an offset in pixels. * @return {!webdriver.ActionSequence} A self reference. */ - dragAndDrop(element: IWebElement, location: IWebElement): ActionSequence; - dragAndDrop(element: IWebElement, location: ILocation): ActionSequence; + dragAndDrop(element: WebElement, location: WebElement): ActionSequence; + dragAndDrop(element: WebElement, location: ILocation): ActionSequence; /** * Clicks a mouse button. @@ -2214,7 +2214,7 @@ declare module webdriver { * first argument. * @return {!webdriver.ActionSequence} A self reference. */ - click(opt_elementOrButton?: IWebElement, opt_button?: number): ActionSequence; + click(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; click(opt_elementOrButton?: number): ActionSequence; /** @@ -2236,7 +2236,7 @@ declare module webdriver { * first argument. * @return {!webdriver.ActionSequence} A self reference. */ - doubleClick(opt_elementOrButton?: IWebElement, opt_button?: number): ActionSequence; + doubleClick(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; doubleClick(opt_elementOrButton?: number): ActionSequence; /** @@ -2309,7 +2309,7 @@ declare module webdriver { * @param {!webdriver.WebElement} elem The element to tap. * @return {!webdriver.TouchSequence} A self reference. */ - tap(elem: IWebElement): TouchSequence; + tap(elem: WebElement): TouchSequence; /** @@ -2318,7 +2318,7 @@ declare module webdriver { * @param {!webdriver.WebElement} elem The element to double tap. * @return {!webdriver.TouchSequence} A self reference. */ - doubleTap(elem: IWebElement): TouchSequence; + doubleTap(elem: WebElement): TouchSequence; /** @@ -2327,7 +2327,7 @@ declare module webdriver { * @param {!webdriver.WebElement} elem The element to long press. * @return {!webdriver.TouchSequence} A self reference. */ - longPress(elem: IWebElement): TouchSequence; + longPress(elem: WebElement): TouchSequence; /** @@ -2374,7 +2374,7 @@ declare module webdriver { * @param {{x: number, y: number}} offset The offset to scroll to. * @return {!webdriver.TouchSequence} A self reference. */ - scrollFromElement(elem: IWebElement, offset: IOffset): TouchSequence; + scrollFromElement(elem: WebElement, offset: IOffset): TouchSequence; /** @@ -2395,7 +2395,7 @@ declare module webdriver { * @param {number} speed The speed to flick at in pixels per second. * @return {!webdriver.TouchSequence} A self reference. */ - flickElement(elem: IWebElement, offset: IOffset, speed: number): TouchSequence; + flickElement(elem: WebElement, offset: IOffset, speed: number): TouchSequence; } From be05c35168a93633b9b60ff32811545ced7bad49 Mon Sep 17 00:00:00 2001 From: 13xforever Date: Sat, 11 Jul 2015 20:51:30 +0500 Subject: [PATCH 027/345] Missing options parameters for .map(), .filter(), .promisifyAll(), and .nodeify() --- bluebird/bluebird-tests.ts | 232 +++++++++++++++++++++++++++++++++++-- bluebird/bluebird.d.ts | 57 +++++---- 2 files changed, 260 insertions(+), 29 deletions(-) diff --git a/bluebird/bluebird-tests.ts b/bluebird/bluebird-tests.ts index 7770e7c9b..55ddf7697 100644 --- a/bluebird/bluebird-tests.ts +++ b/bluebird/bluebird-tests.ts @@ -1,4 +1,4 @@ -/// +/// // Tests by: Bart van der Schoor @@ -365,12 +365,12 @@ fooProm = fooProm.timeout(num, str); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - fooProm.nodeify(); -fooProm = fooProm.nodeify((err: any) => { +fooProm = fooProm.nodeify((err: any) => { }); +fooProm = fooProm.nodeify((err: any, foo?: Foo) => { }); -}); -fooProm = fooProm.nodeify((err: any, foo?: Foo) => { - -}); +fooProm.nodeify({ spread: true }); +fooProm = fooProm.nodeify((err: any) => { }, { spread: true }); +fooProm = fooProm.nodeify((err: any, foo?: Foo) => { }, { spread: true }); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -504,6 +504,17 @@ barArrProm = fooProm.map((item: Foo) => { return bar; }); +barArrProm = fooProm.map((item: Foo, index: number, arrayLength: number) => { + return bar; +}, { + concurrency: 1 +}); +barArrProm = fooProm.map((item: Foo) => { + return bar; +}, { + concurrency: 1 +}); + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - barProm = fooProm.reduce((memo: Bar, item: Foo, index: number, arrayLength: number) => { @@ -522,6 +533,17 @@ fooArrProm = fooArrProm.filter((item: Foo) => { return bool; }); +fooArrProm = fooArrProm.filter((item: Foo, index: number, arrayLength: number) => { + return bool; +}, { + concurrency: 1 +}); +fooArrProm = fooArrProm.filter((item: Foo) => { + return bool; +}, { + concurrency: 1 +}); + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -613,12 +635,41 @@ voidProm = Promise.delay(num); func = Promise.promisify(f); func = Promise.promisify(f, obj); -; obj = Promise.promisifyAll(obj); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +declare var util: any; + +function defaultFilter(name, func) { + return util.isIdentifier(name) && + name.charAt(0) !== "_" && + !util.isClass(func); +} + +function DOMPromisifier(originalMethod) { + // return a function + return function promisified() { + var args = [].slice.call(arguments); + // Needed so that the original method can be called with the correct receiver + var self = this; + // which returns a promise + return new Promise(function(resolve, reject) { + args.push(resolve, reject); + originalMethod.apply(self, args); + }); + }; +} + +obj = Promise.promisifyAll(obj, { + suffix: "", + filter: defaultFilter, + promisifier: DOMPromisifier +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + //TODO enable generator /* func = Promise.coroutine(f); @@ -704,6 +755,26 @@ barArrProm = Promise.map(fooThenArrThen, (item: Foo, index: number, arrayLength: return barThen; }); +barArrProm = Promise.map(fooThenArrThen, (item: Foo) => { + return bar; +}, { + concurrency: 1 +}); +barArrProm = Promise.map(fooThenArrThen, (item: Foo) => { + return barThen; +}, { + concurrency: 1 +}); +barArrProm = Promise.map(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => { + return bar; +}, { + concurrency: 1 +}); +barArrProm = Promise.map(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => { + return barThen; +}, { + concurrency: 1 +}); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // fooArrThen @@ -721,6 +792,27 @@ barArrProm = Promise.map(fooArrThen, (item: Foo, index: number, arrayLength: num return barThen; }); +barArrProm = Promise.map(fooArrThen, (item: Foo) => { + return bar; +}, { + concurrency: 1 +}); +barArrProm = Promise.map(fooArrThen, (item: Foo) => { + return barThen; +}, { + concurrency: 1 +}); +barArrProm = Promise.map(fooArrThen, (item: Foo, index: number, arrayLength: number) => { + return bar; +}, { + concurrency: 1 +}); +barArrProm = Promise.map(fooArrThen, (item: Foo, index: number, arrayLength: number) => { + return barThen; +}, { + concurrency: 1 +}); + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // fooThenArr @@ -738,6 +830,27 @@ barArrProm = Promise.map(fooThenArr, (item: Foo, index: number, arrayLength: num return barThen; }); +barArrProm = Promise.map(fooThenArr, (item: Foo) => { + return bar; +}, { + concurrency: 1 +}); +barArrProm = Promise.map(fooThenArr, (item: Foo) => { + return barThen; +}, { + concurrency: 1 +}); +barArrProm = Promise.map(fooThenArr, (item: Foo, index: number, arrayLength: number) => { + return bar; +}, { + concurrency: 1 +}); +barArrProm = Promise.map(fooThenArr, (item: Foo, index: number, arrayLength: number) => { + return barThen; +}, { + concurrency: 1 +}); + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // fooArr @@ -755,6 +868,27 @@ barArrProm = Promise.map(fooArr, (item: Foo, index: number, arrayLength: number) return barThen; }); +barArrProm = Promise.map(fooArr, (item: Foo) => { + return bar; +}, { + concurrency: 1 +}); +barArrProm = Promise.map(fooArr, (item: Foo) => { + return barThen; +}, { + concurrency: 1 +}); +barArrProm = Promise.map(fooArr, (item: Foo, index: number, arrayLength: number) => { + return bar; +}, { + concurrency: 1 +}); +barArrProm = Promise.map(fooArr, (item: Foo, index: number, arrayLength: number) => { + return barThen; +}, { + concurrency: 1 +}); + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // reduce() @@ -848,6 +982,27 @@ fooArrProm = Promise.filter(fooThenArrThen, (item: Foo, index: number, arrayLeng return boolThen; }); +fooArrProm = Promise.filter(fooThenArrThen, (item: Foo) => { + return bool; +}, { + concurrency: 1 +}); +fooArrProm = Promise.filter(fooThenArrThen, (item: Foo) => { + return boolThen; +}, { + concurrency: 1 +}); +fooArrProm = Promise.filter(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => { + return bool; +}, { + concurrency: 1 +}); +fooArrProm = Promise.filter(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => { + return boolThen; +}, { + concurrency: 1 +}); + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // fooArrThen @@ -865,6 +1020,27 @@ fooArrProm = Promise.filter(fooArrThen, (item: Foo, index: number, arrayLength: return boolThen; }); +fooArrProm = Promise.filter(fooArrThen, (item: Foo) => { + return bool; +}, { + concurrency: 1 +}); +fooArrProm = Promise.filter(fooArrThen, (item: Foo) => { + return boolThen; +}, { + concurrency: 1 +}); +fooArrProm = Promise.filter(fooArrThen, (item: Foo, index: number, arrayLength: number) => { + return bool; +}, { + concurrency: 1 +}); +fooArrProm = Promise.filter(fooArrThen, (item: Foo, index: number, arrayLength: number) => { + return boolThen; +}, { + concurrency: 1 +}); + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // fooThenArr @@ -882,6 +1058,27 @@ fooArrProm = Promise.filter(fooThenArr, (item: Foo, index: number, arrayLength: return boolThen; }); +fooArrProm = Promise.filter(fooThenArr, (item: Foo) => { + return bool; +}, { + concurrency: 1 +}); +fooArrProm = Promise.filter(fooThenArr, (item: Foo) => { + return boolThen; +}, { + concurrency: 1 +}); +fooArrProm = Promise.filter(fooThenArr, (item: Foo, index: number, arrayLength: number) => { + return bool; +}, { + concurrency: 1 +}); +fooArrProm = Promise.filter(fooThenArr, (item: Foo, index: number, arrayLength: number) => { + return boolThen; +}, { + concurrency: 1 +}); + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // fooArr @@ -899,4 +1096,25 @@ fooArrProm = Promise.filter(fooArr, (item: Foo, index: number, arrayLength: numb return boolThen; }); +fooArrProm = Promise.filter(fooArr, (item: Foo) => { + return bool; +}, { + concurrency: 1 +}); +fooArrProm = Promise.filter(fooArr, (item: Foo) => { + return boolThen; +}, { + concurrency: 1 +}); +fooArrProm = Promise.filter(fooArr, (item: Foo, index: number, arrayLength: number) => { + return bool; +}, { + concurrency: 1 +}); +fooArrProm = Promise.filter(fooArr, (item: Foo, index: number, arrayLength: number) => { + return boolThen; +}, { + concurrency: 1 +}); + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/bluebird/bluebird.d.ts b/bluebird/bluebird.d.ts index cd21d77e9..a0ccd30ec 100644 --- a/bluebird/bluebird.d.ts +++ b/bluebird/bluebird.d.ts @@ -116,7 +116,7 @@ declare class Promise implements Promise.Thenable, Promise.Inspection { * Register a node-style callback on this promise. When this promise is is either fulfilled or rejected, the node callback will be called back with the node.js convention where error reason is the first argument and success value is the second argument. The error argument will be `null` in case of success. * Returns back this promise instead of creating a new one. If the `callback` argument is not a function, this method does not do anything. */ - nodeify(callback: (err: any, value?: R) => void): Promise; + nodeify(callback: (err: any, value?: R) => void, options?: Promise.SpreadOption): Promise; nodeify(...sink: any[]): void; /** @@ -312,8 +312,8 @@ declare class Promise implements Promise.Thenable, Promise.Inspection { * Same as calling `Promise.map(thisPromise, mapper)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. */ // TODO type inference from array-resolving promise? - map(mapper: (item: Q, index: number, arrayLength: number) => Promise.Thenable): Promise; - map(mapper: (item: Q, index: number, arrayLength: number) => U): Promise; + map(mapper: (item: Q, index: number, arrayLength: number) => Promise.Thenable, options?: Promise.ConcurrencyOption): Promise; + map(mapper: (item: Q, index: number, arrayLength: number) => U, options?: Promise.ConcurrencyOption): Promise; /** * Same as calling `Promise.reduce(thisPromise, Function reducer, initialValue)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. @@ -326,8 +326,8 @@ declare class Promise implements Promise.Thenable, Promise.Inspection { * Same as calling ``Promise.filter(thisPromise, filterer)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. */ // TODO type inference from array-resolving promise? - filter(filterer: (item: U, index: number, arrayLength: number) => Promise.Thenable): Promise; - filter(filterer: (item: U, index: number, arrayLength: number) => boolean): Promise; + filter(filterer: (item: U, index: number, arrayLength: number) => Promise.Thenable, options?: Promise.ConcurrencyOption): Promise; + filter(filterer: (item: U, index: number, arrayLength: number) => boolean, options?: Promise.ConcurrencyOption): Promise; /** * Start the chain of promises with `Promise.try`. Any synchronous exceptions will be turned into rejections on the returned promise. @@ -416,7 +416,7 @@ declare class Promise implements Promise.Thenable, Promise.Inspection { * Note that the original methods on the object are not overwritten but new methods are created with the `Async`-postfix. For example, if you `promisifyAll()` the node.js `fs` object use `fs.statAsync()` to call the promisified `stat` method. */ // TODO how to model promisifyAll? - static promisifyAll(target: Object): Object; + static promisifyAll(target: Object, options?: Promise.PromisifyAllOptions): Object; /** * Returns a function that can use `yield` to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch. @@ -542,20 +542,20 @@ declare class Promise implements Promise.Thenable, Promise.Inspection { * *The original array is not modified.* */ // promise of array with promises of value - static map(values: Promise.Thenable[]>, mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; - static map(values: Promise.Thenable[]>, mapper: (item: R, index: number, arrayLength: number) => U): Promise; + static map(values: Promise.Thenable[]>, mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable, options?: Promise.ConcurrencyOption): Promise; + static map(values: Promise.Thenable[]>, mapper: (item: R, index: number, arrayLength: number) => U, options?: Promise.ConcurrencyOption): Promise; // promise of array with values - static map(values: Promise.Thenable, mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; - static map(values: Promise.Thenable, mapper: (item: R, index: number, arrayLength: number) => U): Promise; + static map(values: Promise.Thenable, mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable, options?: Promise.ConcurrencyOption): Promise; + static map(values: Promise.Thenable, mapper: (item: R, index: number, arrayLength: number) => U, options?: Promise.ConcurrencyOption): Promise; // array with promises of value - static map(values: Promise.Thenable[], mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; - static map(values: Promise.Thenable[], mapper: (item: R, index: number, arrayLength: number) => U): Promise; + static map(values: Promise.Thenable[], mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable, options?: Promise.ConcurrencyOption): Promise; + static map(values: Promise.Thenable[], mapper: (item: R, index: number, arrayLength: number) => U, options?: Promise.ConcurrencyOption): Promise; // array with values - static map(values: R[], mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; - static map(values: R[], mapper: (item: R, index: number, arrayLength: number) => U): Promise; + static map(values: R[], mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable, options?: Promise.ConcurrencyOption): Promise; + static map(values: R[], mapper: (item: R, index: number, arrayLength: number) => U, options?: Promise.ConcurrencyOption): Promise; /** * Reduce an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `reducer` function with the signature `(total, current, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. @@ -588,20 +588,20 @@ declare class Promise implements Promise.Thenable, Promise.Inspection { * *The original array is not modified. */ // promise of array with promises of value - static filter(values: Promise.Thenable[]>, filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; - static filter(values: Promise.Thenable[]>, filterer: (item: R, index: number, arrayLength: number) => boolean): Promise; + static filter(values: Promise.Thenable[]>, filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable, option?: Promise.ConcurrencyOption): Promise; + static filter(values: Promise.Thenable[]>, filterer: (item: R, index: number, arrayLength: number) => boolean, option?: Promise.ConcurrencyOption): Promise; // promise of array with values - static filter(values: Promise.Thenable, filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; - static filter(values: Promise.Thenable, filterer: (item: R, index: number, arrayLength: number) => boolean): Promise; + static filter(values: Promise.Thenable, filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable, option?: Promise.ConcurrencyOption): Promise; + static filter(values: Promise.Thenable, filterer: (item: R, index: number, arrayLength: number) => boolean, option?: Promise.ConcurrencyOption): Promise; // array with promises of value - static filter(values: Promise.Thenable[], filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; - static filter(values: Promise.Thenable[], filterer: (item: R, index: number, arrayLength: number) => boolean): Promise; + static filter(values: Promise.Thenable[], filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable, option?: Promise.ConcurrencyOption): Promise; + static filter(values: Promise.Thenable[], filterer: (item: R, index: number, arrayLength: number) => boolean, option?: Promise.ConcurrencyOption): Promise; // array with values - static filter(values: R[], filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable): Promise; - static filter(values: R[], filterer: (item: R, index: number, arrayLength: number) => boolean): Promise; + static filter(values: R[], filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable, option?: Promise.ConcurrencyOption): Promise; + static filter(values: R[], filterer: (item: R, index: number, arrayLength: number) => boolean, option?: Promise.ConcurrencyOption): Promise; } declare module Promise { @@ -618,6 +618,19 @@ declare module Promise { export interface OperationalError extends Error { } + export interface ConcurrencyOption { + concurrency: number; + } + export interface SpreadOption { + spread: boolean; + } + export interface PromisifyAllOptions { + suffix?: string; + filter?: (name: string, func: Function, target?: any, passesDefaultFilter?: boolean) => boolean; + // The promisifier gets a reference to the original method and should return a function which returns a promise + promisifier?: (originalMethod: Function) => () => Thenable ; + } + // Ideally, we'd define e.g. "export class RangeError extends Error {}", // but as Error is defined as an interface (not a class), TypeScript doesn't // allow extending Error, only implementing it. From a98c5955e885bbef667c2a3aaf35fcc3e913f5c8 Mon Sep 17 00:00:00 2001 From: 13xforever Date: Sat, 11 Jul 2015 20:58:02 +0500 Subject: [PATCH 028/345] explicit typings in tests --- bluebird/bluebird-tests.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bluebird/bluebird-tests.ts b/bluebird/bluebird-tests.ts index 55ddf7697..f338678c7 100644 --- a/bluebird/bluebird-tests.ts +++ b/bluebird/bluebird-tests.ts @@ -642,13 +642,13 @@ obj = Promise.promisifyAll(obj); declare var util: any; -function defaultFilter(name, func) { +function defaultFilter(name: string, func: Function) { return util.isIdentifier(name) && name.charAt(0) !== "_" && !util.isClass(func); } -function DOMPromisifier(originalMethod) { +function DOMPromisifier(originalMethod: Function) { // return a function return function promisified() { var args = [].slice.call(arguments); From 1a46ba29e13e1ac1a872ebdae4f3f4b4fc279a0e Mon Sep 17 00:00:00 2001 From: Sascha Thiel Date: Mon, 13 Jul 2015 10:11:18 +0200 Subject: [PATCH 029/345] fixed the Collection- / Composite child view issue. The child view does not necessarily have the same model as the Collection- / CompositeView --- marionette/marionette.d.ts | 88 +++++++++++++++++++------------------- 1 file changed, 44 insertions(+), 44 deletions(-) diff --git a/marionette/marionette.d.ts b/marionette/marionette.d.ts index 4a2bfac10..258e6b4b4 100644 --- a/marionette/marionette.d.ts +++ b/marionette/marionette.d.ts @@ -9,49 +9,49 @@ declare module Backbone { // Backbone.BabySitter - class ChildViewContainer { + class ChildViewContainer> { constructor(initialViews?: any[]); - add(view: View, customIndex?: number): void; - findByModel(model: TModel): View; - findByModelCid(modelCid: string): View; - findByCustom(index: number): View; - findByIndex(index: number): View; - findByCid(cid: string): View; - remove(view: View): void; + add(view: TView, customIndex?: number): void; + findByModel(model: TModel): TView; + findByModelCid(modelCid: string): TView; + findByCustom(index: number): TView; + findByIndex(index: number): TView; + findByCid(cid: string): TView; + remove(view: TView): void; call(method: any): void; apply(method: any, args?: any[]): void; //mixins from Collection (copied from Backbone's Collection declaration) - all(iterator: (element: View, index: number) => boolean, context?: any): boolean; - any(iterator: (element: View, index: number) => boolean, context?: any): boolean; + all(iterator: (element: TView, index: number) => boolean, context?: any): boolean; + any(iterator: (element: TView, index: number) => boolean, context?: any): boolean; contains(value: any): boolean; detect(iterator: (item: any) => boolean, context?: any): any; - each(iterator: (element: View, index: number, list?: any) => void, context?: any): any; - every(iterator: (element: View, index: number) => boolean, context?: any): boolean; - filter(iterator: (element: View, index: number) => boolean, context?: any): View[]; - find(iterator: (element: View, index: number) => boolean, context?: any): View; - first(): View; - forEach(iterator: (element: View, index: number, list?: any) => void, context?: any): void; + each(iterator: (element: TView, index: number, list?: any) => void, context?: any): any; + every(iterator: (element: TView, index: number) => boolean, context?: any): boolean; + filter(iterator: (element: TView, index: number) => boolean, context?: any): TView[]; + find(iterator: (element: TView, index: number) => boolean, context?: any): TView; + first(): TView; + forEach(iterator: (element: TView, index: number, list?: any) => void, context?: any): void; include(value: any): boolean; - initial(): View; - initial(n: number): View[]; + initial(): TView; + initial(n: number): TView[]; invoke(methodName: string, args?: any[]): any; isEmpty(object: any): boolean; - last(): View; - last(n: number): View[]; - lastIndexOf(element: View, fromIndex?: number): number; - map(iterator: (element: View, index: number, context?: any) => U, context?: any): U[]; + last(): TView; + last(n: number): TView[]; + lastIndexOf(element: TView, fromIndex?: number): number; + map(iterator: (element: TView, index: number, context?: any) => U, context?: any): U[]; pluck(attribute: string): any[]; - reject(iterator: (element: View, index: number) => boolean, context?: any): View[]; - rest(): View; - rest(n: number): View[]; + reject(iterator: (element: TView, index: number) => boolean, context?: any): TView[]; + rest(): TView; + rest(n: number): TView[]; select(iterator: any, context?: any): any[]; - some(iterator: (element: View, index: number) => boolean, context?: any): boolean; + some(iterator: (element: TView, index: number) => boolean, context?: any): boolean; toArray(): any[]; - without(...values: any[]): View[]; + without(...values: any[]): TView[]; } // Backbone.Wreqr @@ -856,7 +856,7 @@ declare module Marionette { * DOM. This behavior can be disabled by specifying {sort: false} on * initialize. */ - class CollectionView extends View { + class CollectionView> extends View { constructor(options?: CollectionViewOptions); /** @@ -864,7 +864,7 @@ declare module Marionette { * Backbone view object definition, not an instance. It can be any * Backbone.View or be derived from Marionette.ItemView */ - childView: any; + childView: new () => TView; /** * There may be scenarios where you need to pass data from your parent @@ -918,14 +918,14 @@ declare module Marionette { * collection view, iterate them, find them by a given indexer such as the * view's model or collection, and more. */ - children: Backbone.ChildViewContainer; + children: Backbone.ChildViewContainer; /** * The render method of the collection view is responsible for rendering the * entire collection. It loops through each of the children in the collection * and renders them individually as an childView. */ - render(): CollectionView; + render(): CollectionView; /** * The addChild method is responsible for rendering the childViews and @@ -933,9 +933,9 @@ declare module Marionette { * responsible for triggering the events per ChildView. In most cases you * should not override this method. */ - addChild(item: any, ChildView: Backbone.View, index: Number): void; + addChild(item: any, ChildView: TView, index: Number): void; - renderChildView(view: Backbone.View, index: Number): void; + renderChildView(view: TView, index: Number): void; /** * When a custom view instance needs to be created for the childView that @@ -943,13 +943,13 @@ declare module Marionette { * takes three parameters and returns a view instance to be used as the * child view. */ - buildChildView(child: any, ItemViewType: any, itemViewOptions: any): View; + buildChildView(child: any, ItemViewType: any, itemViewOptions: any): TView; /** * Remove the child view and destroy it. This function also updates the indices of * later views in the collection in order to keep the children in sync with the collection. */ - removeChildView(view: any): void; + removeChildView(view: TView): void; /** * Determines if the view is empty. If you want to control when the empty @@ -988,14 +988,14 @@ declare module Marionette { * a collection and displaying the sorted list in the correct order on the * screen. */ - attachHtml(collectionView: CollectionView, childView: Backbone.View, index: number): void; + attachHtml(collectionView: CollectionView, childView: TView, index: number): void; /** * The value returned by this method is the ChildView class that will be * instantiated when a Model needs to be initially rendered. This method * also gives you the ability to customize per Model ChildViews. */ - getChildView(item: TModel): any; + getChildView(item: M): new () => TView; /** * If you need the emptyView's class chosen dynamically, specify @@ -1020,27 +1020,27 @@ declare module Marionette { * instance is about to be added to the collection view. It provides * access to the view instance for the child that was added. */ - onBeforeAddChild(view: any): void; + onBeforeAddChild(childView: TView): void; /** * This callback function allows you to know when a child / child view * instance has been added to the collection view. It provides access to * the view instance for the child that was added. */ - onAddChild(childView: any): void; + onAddChild(childView: TView): void; /** * This callback function allows you to know when a childView instance is * about to be removed from the collectionView. It provides access to the * view instance for the child that was removed. */ - onBeforeRemoveChild(childView: any): void; + onBeforeRemoveChild(childView: TView): void; /** * This callback function allows you to know when a child / childView * instance has been deleted or removed from the collection. */ - onRemoveChild(childView: any): void; + onRemoveChild(childView: TView): void; } /** @@ -1049,7 +1049,7 @@ declare module Marionette { * structure, or for scenarios where a collection needs to be rendered within * a wrapper template. */ - class CompositeView extends CollectionView { + class CompositeView> extends CollectionView { constructor(options?: CollectionViewOptions); @@ -1058,7 +1058,7 @@ declare module Marionette { * CompositeView's template is rendered and the childView's templates are * added to this. */ - childView: any; + childView: new () => TView; /** * By default the composite view uses the same attachHtml method that the @@ -1074,7 +1074,7 @@ declare module Marionette { /** * Renders the view. */ - render(): CompositeView; + render(): CompositeView; /** * Invoked before the model has been rendered From 5c5275f57388cf7e2a6bbfc3efc50cf05dbb08ca Mon Sep 17 00:00:00 2001 From: Sascha Thiel Date: Mon, 13 Jul 2015 10:44:07 +0200 Subject: [PATCH 030/345] adjusted the tests. Added the possible arguments to the generic constructor. --- marionette/marionette-tests.ts | 2 +- marionette/marionette.d.ts | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/marionette/marionette-tests.ts b/marionette/marionette-tests.ts index a37eccc9f..7483c7e2f 100644 --- a/marionette/marionette-tests.ts +++ b/marionette/marionette-tests.ts @@ -179,7 +179,7 @@ module Marionette.Tests { } } - class MyCollectionView extends Marionette.CollectionView { + class MyCollectionView extends Marionette.CollectionView { constructor() { this.childView = MyView; this.childEvents = { diff --git a/marionette/marionette.d.ts b/marionette/marionette.d.ts index 258e6b4b4..154b25434 100644 --- a/marionette/marionette.d.ts +++ b/marionette/marionette.d.ts @@ -864,7 +864,7 @@ declare module Marionette { * Backbone view object definition, not an instance. It can be any * Backbone.View or be derived from Marionette.ItemView */ - childView: new () => TView; + childView: new (...args:any[]) => TView; /** * There may be scenarios where you need to pass data from your parent @@ -995,7 +995,7 @@ declare module Marionette { * instantiated when a Model needs to be initially rendered. This method * also gives you the ability to customize per Model ChildViews. */ - getChildView(item: M): new () => TView; + getChildView(item: M): new (...args:any[]) => TView; /** * If you need the emptyView's class chosen dynamically, specify @@ -1058,7 +1058,7 @@ declare module Marionette { * CompositeView's template is rendered and the childView's templates are * added to this. */ - childView: new () => TView; + childView: new (...args:any[]) => TView; /** * By default the composite view uses the same attachHtml method that the From 2d2a7cc0d438625617baec849076035896c7a88f Mon Sep 17 00:00:00 2001 From: Sascha Thiel Date: Mon, 13 Jul 2015 11:07:07 +0200 Subject: [PATCH 031/345] quckfix for the backbone part. To fully support the marionette changes. --- backbone/backbone.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/backbone/backbone.d.ts b/backbone/backbone.d.ts index 9d54361d5..c2b77f506 100644 --- a/backbone/backbone.d.ts +++ b/backbone/backbone.d.ts @@ -311,7 +311,8 @@ declare module Backbone { interface ViewOptions { model?: TModel; - collection?: Backbone.Collection; + // TODO: quickfix, this can't be fixed easy. The collection does not need to have the same model as the parent view. + collection?: Backbone.Collection; el?: any; id?: string; className?: string; From 4d86cc24082d6703ecaee46ecc970bd0ac744236 Mon Sep 17 00:00:00 2001 From: Maciej Kowalski Date: Mon, 20 Jul 2015 15:49:54 +0200 Subject: [PATCH 032/345] bump rx to 2.5.3 --- rx/rx-lite.d.ts | 129 +++++++++++++++++++++++++----------- rx/rx.aggregates.d.ts | 10 +-- rx/rx.async-lite.d.ts | 6 +- rx/rx.async-tests.ts | 2 +- rx/rx.async.d.ts | 2 +- rx/rx.backpressure.d.ts | 2 +- rx/rx.binding-lite.d.ts | 9 +-- rx/rx.binding.d.ts | 2 +- rx/rx.coincidence-lite.d.ts | 18 ++--- rx/rx.coincidence.d.ts | 2 +- rx/rx.d.ts | 4 +- rx/rx.experimental.d.ts | 82 +++++++++++------------ rx/rx.joinpatterns.d.ts | 2 +- rx/rx.lite.d.ts | 2 +- rx/rx.testing.d.ts | 2 +- rx/rx.time-lite.d.ts | 10 +++ rx/rx.time.d.ts | 9 ++- rx/rx.virtualtime.d.ts | 2 +- 18 files changed, 177 insertions(+), 118 deletions(-) diff --git a/rx/rx-lite.d.ts b/rx/rx-lite.d.ts index 3ea8c6ed8..851545fb8 100644 --- a/rx/rx-lite.d.ts +++ b/rx/rx-lite.d.ts @@ -50,7 +50,6 @@ declare module Rx { export module helpers { function noop(): void; function notDefined(value: any): boolean; - function isScheduler(value: any): boolean; function identity(value: T): T; function defaultNow(): number; function defaultComparer(left: any, right: any): boolean; @@ -117,6 +116,7 @@ declare module Rx { export interface IScheduler { now(): number; + isScheduler(value: any): boolean; schedule(action: () => void): IDisposable; scheduleWithState(state: TState, action: (scheduler: IScheduler, state: TState) => IDisposable): IDisposable; @@ -241,6 +241,23 @@ declare module Rx { combineLatest(second: Observable, third: Observable, fourth: Observable, fifth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4, v5: T5) => TResult): Observable; combineLatest(souces: Observable[], resultSelector: (firstValue: T, ...otherValues: TOther[]) => TResult): Observable; combineLatest(souces: IPromise[], resultSelector: (firstValue: T, ...otherValues: TOther[]) => TResult): Observable; + withLatestFrom(second: Observable, resultSelector: (v1: T, v2: T2) => TResult): Observable; + withLatestFrom(second: IPromise, resultSelector: (v1: T, v2: T2) => TResult): Observable; + withLatestFrom(second: Observable, third: Observable, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; + withLatestFrom(second: Observable, third: IPromise, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; + withLatestFrom(second: IPromise, third: Observable, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; + withLatestFrom(second: IPromise, third: IPromise, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; + withLatestFrom(second: Observable, third: Observable, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + withLatestFrom(second: Observable, third: Observable, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + withLatestFrom(second: Observable, third: IPromise, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + withLatestFrom(second: Observable, third: IPromise, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + withLatestFrom(second: IPromise, third: Observable, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + withLatestFrom(second: IPromise, third: Observable, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + withLatestFrom(second: IPromise, third: IPromise, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + withLatestFrom(second: IPromise, third: IPromise, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + withLatestFrom(second: Observable, third: Observable, fourth: Observable, fifth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4, v5: T5) => TResult): Observable; + withLatestFrom(souces: Observable[], resultSelector: (firstValue: T, ...otherValues: TOther[]) => TResult): Observable; + withLatestFrom(souces: IPromise[], resultSelector: (firstValue: T, ...otherValues: TOther[]) => TResult): Observable; concat(...sources: Observable[]): Observable; concat(...sources: IPromise[]): Observable; concat(sources: Observable[]): Observable; @@ -291,7 +308,7 @@ declare module Rx { do(onNext?: (value: T) => void, onError?: (exception: any) => void, onCompleted?: () => void): Observable; doAction(onNext?: (value: T) => void, onError?: (exception: any) => void, onCompleted?: () => void): Observable; // alias for do tap(onNext?: (value: T) => void, onError?: (exception: any) => void, onCompleted?: () => void): Observable; // alias for do - + doOnNext(onNext: (value: T) => void, thisArg?: any): Observable; doOnError(onError: (exception: any) => void, thisArg?: any): Observable; doOnCompleted(onCompleted: () => void, thisArg?: any): Observable; @@ -305,7 +322,7 @@ declare module Rx { materialize(): Observable>; repeat(repeatCount?: number): Observable; retry(retryCount?: number): Observable; - scan(seed: TAcc, accumulator: (acc: TAcc, value: T) => TAcc): Observable; + scan(accumulator: (acc: TAcc, value: T, seed: TAcc) => TAcc): Observable; scan(accumulator: (acc: T, value: T) => T): Observable; skipLast(count: number): Observable; startWith(...values: T[]): Observable; @@ -322,12 +339,34 @@ declare module Rx { selectMany(selector: (value: T) => IPromise): Observable; selectMany(other: Observable): Observable; selectMany(other: IPromise): Observable; + selectMany(selector: (value: T) => TResult[]): Observable; // alias for selectMany flatMap(selector: (value: T) => Observable, resultSelector: (item: T, other: TOther) => TResult): Observable; // alias for selectMany flatMap(selector: (value: T) => IPromise, resultSelector: (item: T, other: TOther) => TResult): Observable; // alias for selectMany flatMap(selector: (value: T) => Observable): Observable; // alias for selectMany flatMap(selector: (value: T) => IPromise): Observable; // alias for selectMany flatMap(other: Observable): Observable; // alias for selectMany flatMap(other: IPromise): Observable; // alias for selectMany + flatMap(selector: (value: T) => TResult[]): Observable; // alias for selectMany + + /** + * Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. + * @param {Function} onError A transform function to apply when an error occurs in the source sequence. + * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. + * @param {Any} [thisArg] An optional "this" to use to invoke each transform. + * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. + */ + selectManyObserver(onNext: (value: T, index: number) => Observable, onError: (exception: any) => Observable, onCompleted: () => Observable, thisArg?: any): Observable; + + /** + * Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. + * @param {Function} onError A transform function to apply when an error occurs in the source sequence. + * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. + * @param {Any} [thisArg] An optional "this" to use to invoke each transform. + * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. + */ + flatMapObserver(onNext: (value: T, index: number) => Observable, onError: (exception: any) => Observable, onCompleted: () => Observable, thisArg?: any): Observable; selectConcat(selector: (value: T, index: number) => Observable, resultSelector: (value1: T, value2: T2, index: number) => R): Observable; selectConcat(selector: (value: T, index: number) => IPromise, resultSelector: (value1: T, value2: T2, index: number) => R): Observable; @@ -336,30 +375,30 @@ declare module Rx { selectConcat(sequence: Observable): Observable; /** - * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then + * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param [thisArg] Object to use as this when executing callback. - * @returns An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences + * @returns An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ selectSwitch(selector: (value: T, index: number, source: Observable) => Observable, thisArg?: any): Observable; /** - * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then + * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param [thisArg] Object to use as this when executing callback. - * @returns An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences + * @returns An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ flatMapLatest(selector: (value: T, index: number, source: Observable) => Observable, thisArg?: any): Observable; // alias for selectSwitch /** - * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then + * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param [thisArg] Object to use as this when executing callback. * @since 2.2.28 - * @returns An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences + * @returns An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ switchMap(selector: (value: T, index: number, source: Observable) => TResult, thisArg?: any): Observable; // alias for selectSwitch @@ -383,7 +422,7 @@ declare module Rx { * Converts an existing observable sequence to an ES6 Compatible Promise * @example * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); - * + * * // With config * Rx.config.Promise = RSVP.Promise; * var promise = Rx.Observable.return(42).toPromise(); @@ -470,36 +509,12 @@ declare module Rx { fromArray(array: T[], scheduler?: IScheduler): Observable; fromArray(array: { length: number;[index: number]: T; }, scheduler?: IScheduler): Observable; - /** - * Converts an iterable into an Observable sequence - * - * @example - * var res = Rx.Observable.fromIterable(new Map()); - * var res = Rx.Observable.fromIterable(function* () { yield 42; }); - * var res = Rx.Observable.fromIterable(new Set(), Rx.Scheduler.timeout); - * @param generator Generator to convert from. - * @param [scheduler] Scheduler to run the enumeration of the input sequence on. - * @returns The observable sequence whose elements are pulled from the given generator sequence. - */ - fromIterable(generator: () => { next(): { done: boolean; value?: T; }; }, scheduler?: IScheduler): Observable; - - /** - * Converts an iterable into an Observable sequence - * - * @example - * var res = Rx.Observable.fromIterable(new Map()); - * var res = Rx.Observable.fromIterable(new Set(), Rx.Scheduler.timeout); - * @param iterable Iterable to convert from. - * @param [scheduler] Scheduler to run the enumeration of the input sequence on. - * @returns The observable sequence whose elements are pulled from the given generator sequence. - */ - fromIterable(iterable: {}, scheduler?: IScheduler): Observable; // todo: can't describe ES6 Iterable via TypeScript type system generate(initialState: TState, condition: (state: TState) => boolean, iterate: (state: TState) => TState, resultSelector: (state: TState) => TResult, scheduler?: IScheduler): Observable; never(): Observable; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. - * + * * @example * var res = Rx.Observable.of(1, 2, 3); * @since 2.2.28 @@ -508,7 +523,7 @@ declare module Rx { of(...values: T[]): Observable; /** - * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. + * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @example * var res = Rx.Observable.ofWithScheduler(Rx.Scheduler.timeout, 1, 2, 3); * @since 2.2.28 @@ -576,6 +591,38 @@ declare module Rx { combineLatest(souces: Observable[], resultSelector: (...otherValues: TOther[]) => TResult): Observable; combineLatest(souces: IPromise[], resultSelector: (...otherValues: TOther[]) => TResult): Observable; + withLatestFrom(first: Observable, second: Observable, resultSelector: (v1: T, v2: T2) => TResult): Observable; + withLatestFrom(first: IPromise, second: Observable, resultSelector: (v1: T, v2: T2) => TResult): Observable; + withLatestFrom(first: Observable, second: IPromise, resultSelector: (v1: T, v2: T2) => TResult): Observable; + withLatestFrom(first: IPromise, second: IPromise, resultSelector: (v1: T, v2: T2) => TResult): Observable; + withLatestFrom(first: Observable, second: Observable, third: Observable, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; + withLatestFrom(first: Observable, second: Observable, third: IPromise, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; + withLatestFrom(first: Observable, second: IPromise, third: Observable, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; + withLatestFrom(first: Observable, second: IPromise, third: IPromise, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; + withLatestFrom(first: IPromise, second: Observable, third: Observable, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; + withLatestFrom(first: IPromise, second: Observable, third: IPromise, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; + withLatestFrom(first: IPromise, second: IPromise, third: Observable, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; + withLatestFrom(first: IPromise, second: IPromise, third: IPromise, resultSelector: (v1: T, v2: T2, v3: T3) => TResult): Observable; + withLatestFrom(first: Observable, second: Observable, third: Observable, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + withLatestFrom(first: Observable, second: Observable, third: Observable, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + withLatestFrom(first: Observable, second: Observable, third: IPromise, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + withLatestFrom(first: Observable, second: Observable, third: IPromise, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + withLatestFrom(first: Observable, second: IPromise, third: Observable, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + withLatestFrom(first: Observable, second: IPromise, third: Observable, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + withLatestFrom(first: Observable, second: IPromise, third: IPromise, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + withLatestFrom(first: Observable, second: IPromise, third: IPromise, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + withLatestFrom(first: IPromise, second: Observable, third: Observable, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + withLatestFrom(first: IPromise, second: Observable, third: Observable, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + withLatestFrom(first: IPromise, second: Observable, third: IPromise, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + withLatestFrom(first: IPromise, second: Observable, third: IPromise, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + withLatestFrom(first: IPromise, second: IPromise, third: Observable, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + withLatestFrom(first: IPromise, second: IPromise, third: Observable, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + withLatestFrom(first: IPromise, second: IPromise, third: IPromise, fourth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + withLatestFrom(first: IPromise, second: IPromise, third: IPromise, fourth: IPromise, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4) => TResult): Observable; + withLatestFrom(first: Observable, second: Observable, third: Observable, fourth: Observable, fifth: Observable, resultSelector: (v1: T, v2: T2, v3: T3, v4: T4, v5: T5) => TResult): Observable; + withLatestFrom(souces: Observable[], resultSelector: (...otherValues: TOther[]) => TResult): Observable; + withLatestFrom(souces: IPromise[], resultSelector: (...otherValues: TOther[]) => TResult): Observable; + concat(...sources: Observable[]): Observable; concat(...sources: IPromise[]): Observable; concat(sources: Observable[]): Observable; @@ -617,6 +664,8 @@ declare module Rx { * @returns An Observable sequence which wraps the existing promise success and failure. */ fromPromise(promise: IPromise): Observable; + + prototype: any; } export var Observable: ObservableStatic; @@ -625,11 +674,11 @@ declare module Rx { hasObservers(): boolean; } - export interface Subject extends ISubject { - } + export interface Subject extends ISubject { + } - interface SubjectStatic { - new (): Subject; + interface SubjectStatic { + new (): Subject; create(observer?: Observer, observable?: Observable): ISubject; } diff --git a/rx/rx.aggregates.d.ts b/rx/rx.aggregates.d.ts index 001d1b993..313cb5591 100644 --- a/rx/rx.aggregates.d.ts +++ b/rx/rx.aggregates.d.ts @@ -40,17 +40,9 @@ declare module Rx { sequenceEqual(second: T[]): Observable; elementAt(index: number): Observable; - elementAtOrDefault(index: number, defaultValue?: T): Observable; - single(predicate?: (value: T, index: number, source: Observable) => boolean, thisArg?: any): Observable; - singleOrDefault(predicate?: (value: T, index: number, source: Observable) => boolean, defaultValue?: T, thisArg?: any): Observable; - first(predicate?: (value: T, index: number, source: Observable) => boolean, thisArg?: any): Observable; - firstOrDefault(predicate?: (value: T, index: number, source: Observable) => boolean, defaultValue?: T, thisArg?: any): Observable; - last(predicate?: (value: T, index: number, source: Observable) => boolean, thisArg?: any): Observable; - lastOrDefault(predicate?: (value: T, index: number, source: Observable) => boolean, defaultValue?: T, thisArg?: any): Observable; - find(predicate: (value: T, index: number, source: Observable) => boolean, thisArg?: any): Observable; findIndex(predicate: (value: T, index: number, source: Observable) => boolean, thisArg?: any): Observable; } @@ -58,4 +50,4 @@ declare module Rx { declare module "rx.aggregates" { export = Rx; -} \ No newline at end of file +} diff --git a/rx/rx.async-lite.d.ts b/rx/rx.async-lite.d.ts index 94eb39800..8a725332f 100644 --- a/rx/rx.async-lite.d.ts +++ b/rx/rx.async-lite.d.ts @@ -65,7 +65,9 @@ declare module Rx { (func: Function, context?: any): (...args: any[]) => Observable; }; - fromEvent(element: any, eventName: string, selector?: (arguments: any[]) => T): Observable; - fromEventPattern(addHandler: (handler: Function) => void, removeHandler: (handler: Function) => void, selector?: (arguments: any[])=>T): Observable; + fromEvent(element: NodeList, eventName: string, selector?: (arguments: any[]) => T): Observable; + fromEvent(element: Node, eventName: string, selector?: (arguments: any[]) => T): Observable; + fromEvent(element: {on: (name: string, cb: (e: any) => any) => void; off: (name: string, cb: (e: any) => any) => void}, eventName: string, selector?: (arguments: any[]) => T): Observable; + fromEventPattern(addHandler: (handler: Function) => void, removeHandler: (handler: Function) => void, selector?: (arguments: any[])=>T): Observable; } } diff --git a/rx/rx.async-tests.ts b/rx/rx.async-tests.ts index 4f8c102c4..6fe10526c 100644 --- a/rx/rx.async-tests.ts +++ b/rx/rx.async-tests.ts @@ -81,4 +81,4 @@ module Rx.Tests.Async { function startAsync() { var o: Rx.Observable = Rx.Observable.startAsync(() => >null); } -} \ No newline at end of file +} diff --git a/rx/rx.async.d.ts b/rx/rx.async.d.ts index 783f31d52..f1af9a600 100644 --- a/rx/rx.async.d.ts +++ b/rx/rx.async.d.ts @@ -40,4 +40,4 @@ declare module Rx { declare module "rx.async" { export = Rx; -} \ No newline at end of file +} diff --git a/rx/rx.backpressure.d.ts b/rx/rx.backpressure.d.ts index 18ab4ddd9..549cd870a 100644 --- a/rx/rx.backpressure.d.ts +++ b/rx/rx.backpressure.d.ts @@ -8,4 +8,4 @@ declare module "rx.backpressure" { export = Rx; -} \ No newline at end of file +} diff --git a/rx/rx.binding-lite.d.ts b/rx/rx.binding-lite.d.ts index f896e260d..86db8922c 100644 --- a/rx/rx.binding-lite.d.ts +++ b/rx/rx.binding-lite.d.ts @@ -7,6 +7,7 @@ declare module Rx { export interface BehaviorSubject extends Subject { + getValue(): T; } interface BehaviorSubjectStatic { @@ -43,10 +44,10 @@ declare module Rx { /** * Returns an observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. - * + * * @example * var res = source.share(); - * + * * @returns An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ share(): Observable; @@ -57,10 +58,10 @@ declare module Rx { /** * Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue. * This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. - * + * * @example * var res = source.shareValue(42); - * + * * @param initialValue Initial value received by observers upon subscription. * @returns An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ diff --git a/rx/rx.binding.d.ts b/rx/rx.binding.d.ts index b93411a52..2bd4c5b01 100644 --- a/rx/rx.binding.d.ts +++ b/rx/rx.binding.d.ts @@ -8,4 +8,4 @@ declare module "rx.binding" { export = Rx; -} \ No newline at end of file +} diff --git a/rx/rx.coincidence-lite.d.ts b/rx/rx.coincidence-lite.d.ts index 801e42168..ca1cc7347 100644 --- a/rx/rx.coincidence-lite.d.ts +++ b/rx/rx.coincidence-lite.d.ts @@ -9,24 +9,24 @@ declare module Rx { interface Observable { /** - * Returns a new observable that triggers on the second and subsequent triggerings of the input observable. - * The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair. + * Returns a new observable that triggers on the second and subsequent triggerings of the input observable. + * The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair. * The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs. * @returns An observable that triggers on successive pairs of observations from the input observable as an array. */ pairwise(): Observable; - /** + /** * Returns two observables which partition the observations of the source by the given function. - * The first will trigger observations for those values for which the predicate returns true. - * The second will trigger observations for those values where the predicate returns false. - * The predicate is executed once for each subscribed observer. - * Both also propagate all error observations arising from the source and each completes + * The first will trigger observations for those values for which the predicate returns true. + * The second will trigger observations for those values where the predicate returns false. + * The predicate is executed once for each subscribed observer. + * Both also propagate all error observations arising from the source and each completes * when the source completes. - * @param predicate + * @param predicate * The function to determine which output Observable will trigger a particular observation. * @returns - * An array of observables. The first triggers when the predicate returns true, + * An array of observables. The first triggers when the predicate returns true, * and the second triggers when the predicate returns false. */ partition(predicate: (value: T, index: number, source: Observable) => boolean, thisArg: any): Observable[]; diff --git a/rx/rx.coincidence.d.ts b/rx/rx.coincidence.d.ts index 87fa6a55b..d06166224 100644 --- a/rx/rx.coincidence.d.ts +++ b/rx/rx.coincidence.d.ts @@ -33,4 +33,4 @@ declare module Rx { declare module "rx.coincidence" { export = Rx; -} \ No newline at end of file +} diff --git a/rx/rx.d.ts b/rx/rx.d.ts index f1dc527d7..9b806119e 100644 --- a/rx/rx.d.ts +++ b/rx/rx.d.ts @@ -1,4 +1,4 @@ -// Type definitions for RxJS v2.2.28 +// Type definitions for RxJS v2.5.3 // Project: http://rx.codeplex.com/ // Definitions by: gsino , Igor Oleinikov // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -39,7 +39,7 @@ declare module Rx { distinct(skipParameter: boolean, valueSerializer: (value: T) => string): Observable; distinct(keySelector?: (value: T) => TKey, keySerializer?: (key: TKey) => string): Observable; groupBy(keySelector: (value: T) => TKey, skipElementSelector?: boolean, keySerializer?: (key: TKey) => string): Observable>; - groupBy(keySelector: (value: T) => TKey, elementSelector: (value: T) => TElement, keySerializer?: (key: TKey) => string): Observable>; + groupBy(keySelector: (value: T) => TKey, elementSelector: (value: T) => TElement, keySerializer?: (key: TKey) => string): Observable>; groupByUntil(keySelector: (value: T) => TKey, skipElementSelector: boolean, durationSelector: (group: GroupedObservable) => Observable, keySerializer?: (key: TKey) => string): Observable>; groupByUntil(keySelector: (value: T) => TKey, elementSelector: (value: T) => TElement, durationSelector: (group: GroupedObservable) => Observable, keySerializer?: (key: TKey) => string): Observable>; } diff --git a/rx/rx.experimental.d.ts b/rx/rx.experimental.d.ts index 60aec86e1..e80ca0329 100644 --- a/rx/rx.experimental.d.ts +++ b/rx/rx.experimental.d.ts @@ -29,13 +29,13 @@ declare module Rx { /** * Repeats source as long as condition holds emulating a do while loop. * @param condition The condition which determines if the source will be repeated. - * @returns An observable sequence which is repeated as long as the condition holds. + * @returns An observable sequence which is repeated as long as the condition holds. */ doWhile(condition: () => boolean): Observable; /** * Expands an observable sequence by recursively invoking selector. - * + * * @param selector Selector function to invoke for each produced element, resulting in another sequence to which the selector will be invoked recursively again. * @param [scheduler] Scheduler on which to perform the expansion. If not provided, this defaults to the current thread scheduler. * @returns An observable sequence containing all the elements produced by the recursive expansion. @@ -64,7 +64,7 @@ declare module Rx { interface ObservableStatic { /** * Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers (sources: T[], resultSelector: (item: T) => Observable): Observable; @@ -132,7 +132,7 @@ declare module Rx { * There is an alias for this method called 'forIn' for browsers (sources: T[], resultSelector: (item: T) => Observable): Observable; @@ -141,7 +141,7 @@ declare module Rx { * There is an alias for this method called 'whileDo' for browsers (condition: () => boolean, source: Observable): Observable; while(condition: () => boolean, source: IPromise): Observable; @@ -151,7 +151,7 @@ declare module Rx { * There is an alias for this method called 'whileDo' for browsers (condition: () => boolean, source: Observable): Observable; whileDo(condition: () => boolean, source: IPromise): Observable; @@ -159,14 +159,14 @@ declare module Rx { /** * Uses selector to determine which source in sources to use. * There is an alias 'switchCase' for browsers (selector: () => string, sources: { [key: string]: Observable; }, elseSource: Observable): Observable; case(selector: () => string, sources: { [key: string]: IPromise; }, elseSource: Observable): Observable; @@ -176,16 +176,16 @@ declare module Rx { /** * Uses selector to determine which source in sources to use. * There is an alias 'switchCase' for browsers (selector: () => string, sources: { [key: string]: Observable; }, scheduler?: IScheduler): Observable; case(selector: () => string, sources: { [key: string]: IPromise; }, scheduler?: IScheduler): Observable; @@ -193,14 +193,14 @@ declare module Rx { /** * Uses selector to determine which source in sources to use. * There is an alias 'switchCase' for browsers (selector: () => number, sources: { [key: number]: Observable; }, elseSource: Observable): Observable; case(selector: () => number, sources: { [key: number]: IPromise; }, elseSource: Observable): Observable; @@ -210,16 +210,16 @@ declare module Rx { /** * Uses selector to determine which source in sources to use. * There is an alias 'switchCase' for browsers (selector: () => number, sources: { [key: number]: Observable; }, scheduler?: IScheduler): Observable; case(selector: () => number, sources: { [key: number]: IPromise; }, scheduler?: IScheduler): Observable; @@ -227,14 +227,14 @@ declare module Rx { /** * Uses selector to determine which source in sources to use. * There is an alias 'switchCase' for browsers (selector: () => string, sources: { [key: string]: Observable; }, elseSource: Observable): Observable; switchCase(selector: () => string, sources: { [key: string]: IPromise; }, elseSource: Observable): Observable; @@ -244,16 +244,16 @@ declare module Rx { /** * Uses selector to determine which source in sources to use. * There is an alias 'switchCase' for browsers (selector: () => string, sources: { [key: string]: Observable; }, scheduler?: IScheduler): Observable; switchCase(selector: () => string, sources: { [key: string]: IPromise; }, scheduler?: IScheduler): Observable; @@ -261,14 +261,14 @@ declare module Rx { /** * Uses selector to determine which source in sources to use. * There is an alias 'switchCase' for browsers (selector: () => number, sources: { [key: number]: Observable; }, elseSource: Observable): Observable; switchCase(selector: () => number, sources: { [key: number]: IPromise; }, elseSource: Observable): Observable; @@ -278,23 +278,23 @@ declare module Rx { /** * Uses selector to determine which source in sources to use. * There is an alias 'switchCase' for browsers (selector: () => number, sources: { [key: number]: Observable; }, scheduler?: IScheduler): Observable; switchCase(selector: () => number, sources: { [key: number]: IPromise; }, scheduler?: IScheduler): Observable; /** * Runs all observable sequences in parallel and collect their last elements. - * + * * @example * res = Rx.Observable.forkJoin([obs1, obs2]); * @param sources Array of source sequences or promises. @@ -305,7 +305,7 @@ declare module Rx { /** * Runs all observable sequences in parallel and collect their last elements. - * + * * @example * res = Rx.Observable.forkJoin(obs1, obs2, ...); * @param args Source sequences or promises. @@ -318,4 +318,4 @@ declare module Rx { declare module "rx.experimental" { export = Rx; -} \ No newline at end of file +} diff --git a/rx/rx.joinpatterns.d.ts b/rx/rx.joinpatterns.d.ts index ce251a2db..fc20f8254 100644 --- a/rx/rx.joinpatterns.d.ts +++ b/rx/rx.joinpatterns.d.ts @@ -57,4 +57,4 @@ declare module Rx { declare module "rx.joinpatterns" { export = Rx; -} \ No newline at end of file +} diff --git a/rx/rx.lite.d.ts b/rx/rx.lite.d.ts index f6785a1a7..66ec67849 100644 --- a/rx/rx.lite.d.ts +++ b/rx/rx.lite.d.ts @@ -12,4 +12,4 @@ declare module "rx.lite" { export = Rx; -} \ No newline at end of file +} diff --git a/rx/rx.testing.d.ts b/rx/rx.testing.d.ts index 466243784..58b074f75 100644 --- a/rx/rx.testing.d.ts +++ b/rx/rx.testing.d.ts @@ -61,4 +61,4 @@ declare module Rx { declare module "rx.testing" { export = Rx; -} \ No newline at end of file +} diff --git a/rx/rx.time-lite.d.ts b/rx/rx.time-lite.d.ts index 3642377f8..f7a902685 100644 --- a/rx/rx.time-lite.d.ts +++ b/rx/rx.time-lite.d.ts @@ -19,11 +19,21 @@ declare module Rx { export interface Observable { delay(dueTime: Date, scheduler?: IScheduler): Observable; delay(dueTime: number, scheduler?: IScheduler): Observable; + + debounce(dueTime: number, scheduler?: IScheduler): Observable; + throttleWithTimeout(dueTime: number, scheduler?: IScheduler): Observable; + /** + * @deprecated use #debounce or #throttleWithTimeout instead. + */ throttle(dueTime: number, scheduler?: IScheduler): Observable; + timeInterval(scheduler?: IScheduler): Observable>; + timestamp(scheduler?: IScheduler): Observable>; + sample(interval: number, scheduler?: IScheduler): Observable; sample(sampler: Observable, scheduler?: IScheduler): Observable; + timeout(dueTime: Date, other?: Observable, scheduler?: IScheduler): Observable; timeout(dueTime: number, other?: Observable, scheduler?: IScheduler): Observable; } diff --git a/rx/rx.time.d.ts b/rx/rx.time.d.ts index 3da66b95c..2e3ea0a09 100644 --- a/rx/rx.time.d.ts +++ b/rx/rx.time.d.ts @@ -13,7 +13,12 @@ declare module Rx { delayWithSelector(subscriptionDelay: number, delayDurationSelector: (item: T) => number): Observable; timeoutWithSelector(firstTimeout: Observable, timeoutdurationSelector?: (item: T) => Observable, other?: Observable): Observable; - throttleWithSelector(throttleDurationSelector: (item: T) => Observable): Observable; + + debounceWithSelector(debounceDurationSelector: (item: T) => Observable): Observable; + /** + * @deprecated use #debounceWithSelector instead. + */ + throttleWithSelector(debounceDurationSelector: (item: T) => Observable): Observable; skipLastWithTime(duration: number, scheduler?: IScheduler): Observable; takeLastWithTime(duration: number, timerScheduler?: IScheduler, loopScheduler?: IScheduler): Observable; @@ -58,4 +63,4 @@ declare module Rx { declare module "rx.time" { export = Rx; -} \ No newline at end of file +} diff --git a/rx/rx.virtualtime.d.ts b/rx/rx.virtualtime.d.ts index 25e894074..bac31a0d3 100644 --- a/rx/rx.virtualtime.d.ts +++ b/rx/rx.virtualtime.d.ts @@ -38,4 +38,4 @@ declare module Rx { declare module "rx.virtualtime" { export = Rx; -} \ No newline at end of file +} From 15520b4269d3b372947c0b0eaa6564cd118b96ed Mon Sep 17 00:00:00 2001 From: Sascha Thiel Date: Tue, 21 Jul 2015 13:52:47 +0200 Subject: [PATCH 033/345] added LayoutViewOption because the Layout can have regions in it. --- marionette/marionette.d.ts | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/marionette/marionette.d.ts b/marionette/marionette.d.ts index be684d9a8..c60965c98 100644 --- a/marionette/marionette.d.ts +++ b/marionette/marionette.d.ts @@ -1097,6 +1097,13 @@ declare module Marionette { onRenderCollection(): void; } + interface LayoutViewOptions extends Backbone.ViewOptions { + /** + * The LayoutView takes an additional parameter where you can pass the regions as option on creation. + */ + regions?:any; + } + /** * A LayoutView is a hybrid of an ItemView and a collection of Region objects. * They are ideal for rendering application layouts with multiple sub-regions @@ -1119,7 +1126,12 @@ declare module Marionette { * A hash that can contain a regions hash that allows you to specify regions per * LayoutView instance. */ - constructor(options?: any); + constructor(options?: LayoutViewOptions); + + /** + * Regions hash or a method returning the regions hash that maps regions/selectors to methods on your View. + **/ + regions():any; /** Adds a region to the layout view. */ addRegion(name: string, definition: any): Region; @@ -1129,7 +1141,7 @@ declare module Marionette { */ addRegions(regions: any): any; - /** Returns a region from the layout view */ + /** Returns a region from the layout view */ getRegion(name: string): Region; /** @@ -1147,7 +1159,7 @@ declare module Marionette { * for customized region interactions and business specific * view logic for better control over single regions. */ - getRegionManager(): any; + getRegionManager(): RegionManager; } interface AppRouterOptions extends Backbone.RouterOptions { From c1b2c0c40d6d0ee60677425996e758fb1274c468 Mon Sep 17 00:00:00 2001 From: Dan Lewi Harkestad Date: Tue, 4 Aug 2015 14:04:32 +0200 Subject: [PATCH 034/345] Missing deferIntercept in angular-ui-router. Added definition for IUrlRouterProvider.deferIntercept in angular-ui-router. Docs: http://angular-ui.github.io/ui-router/site/#/api/ui.router.router.$urlRouterProvider --- angular-ui-router/angular-ui-router.d.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/angular-ui-router/angular-ui-router.d.ts b/angular-ui-router/angular-ui-router.d.ts index 10b92db7d..f4de75663 100644 --- a/angular-ui-router/angular-ui-router.d.ts +++ b/angular-ui-router/angular-ui-router.d.ts @@ -114,6 +114,14 @@ declare module angular.ui { otherwise(path: string): IUrlRouterProvider; rule(handler: Function): IUrlRouterProvider; rule(handler: any[]): IUrlRouterProvider; + /** + * Disables (or enables) deferring location change interception. + * + * If you wish to customize the behavior of syncing the URL (for example, if you wish to defer a transition but maintain the current URL), call this method at configuration time. Then, at run time, call $urlRouter.listen() after you have configured your own $locationChangeSuccess event handler. + * + * @param {boolean} defer Indicates whether to defer location change interception. Passing no parameter is equivalent to true. + */ + deferIntercept(defer?: boolean): void; } interface IStateOptions { From 008b03a4b6499122c507d45f2259d634a21863fe Mon Sep 17 00:00:00 2001 From: Dan Lewi Harkestad Date: Tue, 4 Aug 2015 14:59:51 +0200 Subject: [PATCH 035/345] Missed ability to define url matcher types in angular-ui-router. Added type definitions for defining url matcher types. Docs: http://angular-ui.github.io/ui-router/site/#/api/ui.router.util.type:Type http://angular-ui.github.io/ui-router/site/#/api/ui.router.util.$urlMatcherFactory --- angular-ui-router/angular-ui-router.d.ts | 107 ++++++++++++++++++++++- 1 file changed, 104 insertions(+), 3 deletions(-) diff --git a/angular-ui-router/angular-ui-router.d.ts b/angular-ui-router/angular-ui-router.d.ts index f4de75663..2faed455e 100644 --- a/angular-ui-router/angular-ui-router.d.ts +++ b/angular-ui-router/angular-ui-router.d.ts @@ -91,12 +91,70 @@ declare module angular.ui { } interface IUrlMatcherFactory { + /** + * Creates a UrlMatcher for the specified pattern. + * + * @param pattern {string} The URL pattern. + * + * @returns {IUrlMatcher} The UrlMatcher. + */ compile(pattern: string): IUrlMatcher; + /** + * Returns true if the specified object is a UrlMatcher, or false otherwise. + * + * @param o {any} The object to perform the type check against. + * + * @returns {boolean} Returns true if the object matches the IUrlMatcher interface, by implementing all the same methods. + */ isMatcher(o: any): boolean; - type(name: string, definition: any, definitionFn?: any): any; - caseInsensitive(value: boolean): void; + /** + * Returns a type definition for the specified name + * + * @param name {string} The type definition name + * + * @returns {IType} The type definition + */ + type(name: string): IType; + /** + * Registers a custom Type object that can be used to generate URLs with typed parameters. + * + * @param {IType} definition The type definition. + * @param {any[]} inlineAnnotedDefinitionFn A function that is injected before the app runtime starts. The result of this function is merged into the existing definition. + * + * @returns {IUrlMatcherFactory} Returns $urlMatcherFactoryProvider. + */ + type(name: string, definition: IType, inlineAnnotedDefinitionFn?: any[]): IUrlMatcherFactory; + /** + * Registers a custom Type object that can be used to generate URLs with typed parameters. + * + * @param {IType} definition The type definition. + * @param {any[]} inlineAnnotedDefinitionFn A function that is injected before the app runtime starts. The result of this function is merged into the existing definition. + * + * @returns {IUrlMatcherFactory} Returns $urlMatcherFactoryProvider. + */ + type(name: string, definition: IType, definitionFn?: (...args:any[]) => IType): IUrlMatcherFactory; + /** + * Defines whether URL matching should be case sensitive (the default behavior), or not. + * + * @param value {boolean} false to match URL in a case sensitive manner; otherwise true; + * + * @returns {boolean} the current value of caseInsensitive + */ + caseInsensitive(value?: boolean): boolean; + /** + * Sets the default behavior when generating or matching URLs with default parameter values + * + * @param value {string} A string that defines the default parameter URL squashing behavior. nosquash: When generating an href with a default parameter value, do not squash the parameter value from the URL slash: When generating an href with a default parameter value, squash (remove) the parameter value, and, if the parameter is surrounded by slashes, squash (remove) one slash from the URL any other string, e.g. "~": When generating an href with a default parameter value, squash (remove) the parameter value from the URL and replace it with this string. + */ defaultSquashPolicy(value: string): void; - strictMode(value: boolean): void; + /** + * Defines whether URLs should match trailing slashes, or not (the default behavior). + * + * @param value {boolean} false to match trailing slashes in URLs, otherwise true. + * + * @returns {boolean} the current value of strictMode + */ + strictMode(value?: boolean): boolean; } interface IUrlRouterProvider extends angular.IServiceProvider { @@ -220,4 +278,47 @@ declare module angular.ui { */ useAnchorScroll(): void; } + + interface IType { + /** + * Converts a parameter value (from URL string or transition param) to a custom/native value. + * + * @param val {string} The URL parameter value to decode. + * @param key {string} The name of the parameter in which val is stored. Can be used for meta-programming of Type objects. + * + * @returns {any} Returns a custom representation of the URL parameter value. + */ + decode(val: string, key: string): any; + /** + * Encodes a custom/native type value to a string that can be embedded in a URL. Note that the return value does not need to be URL-safe (i.e. passed through encodeURIComponent()), it only needs to be a representation of val that has been coerced to a string. + * + * @param val {any} The value to encode. + * @param key {string} The name of the parameter in which val is stored. Can be used for meta-programming of Type objects. + * + * @returns {string} Returns a string representation of val that can be encoded in a URL. + */ + encode(val: any, key: string): string; + /** + * Determines whether two decoded values are equivalent. + * + * @param a {any} A value to compare against. + * @param b {any} A value to compare against. + * + * @returns {boolean} Returns true if the values are equivalent/equal, otherwise false. + */ + equals? (a: any, b: any): boolean; + /** + * Detects whether a value is of a particular type. Accepts a native (decoded) value and determines whether it matches the current Type object. + * + * @param val {any} The value to check. + * @param key {any} Optional. If the type check is happening in the context of a specific UrlMatcher object, this is the name of the parameter in which val is stored. Can be used for meta-programming of Type objects. + * + * @returns {boolean} Returns true if the value matches the type, otherwise false. + */ + is(val: any, key: string): boolean; + /** + * The regular expression pattern used to match values of this type when coming from a substring of a URL. + */ + pattern?: RegExp; + } } From 92ba5354f935a9d155d7828887141a54ccb90628 Mon Sep 17 00:00:00 2001 From: Dan Lewi Harkestad Date: Tue, 4 Aug 2015 15:05:31 +0200 Subject: [PATCH 036/345] Added missing listen function in angular-ui-router UrlRouter service has a function listen() that is undocumented in reference, but is mentioned in other parts of the documentation. --- angular-ui-router/angular-ui-router.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/angular-ui-router/angular-ui-router.d.ts b/angular-ui-router/angular-ui-router.d.ts index 2faed455e..febe1c090 100644 --- a/angular-ui-router/angular-ui-router.d.ts +++ b/angular-ui-router/angular-ui-router.d.ts @@ -269,6 +269,7 @@ declare module angular.ui { * */ sync(): void; + listen(): void; } interface IUiViewScrollProvider { From 57866cd6366a73a43087ab72611ce960b09fcfd3 Mon Sep 17 00:00:00 2001 From: tcurtis1 Date: Tue, 4 Aug 2015 12:51:36 -0600 Subject: [PATCH 037/345] Added documentation and updated type definitions for angular mocks httpBackend. --- angularjs/angular-mocks.d.ts | 288 ++++++++++++++++++++++------------- 1 file changed, 181 insertions(+), 107 deletions(-) diff --git a/angularjs/angular-mocks.d.ts b/angularjs/angular-mocks.d.ts index e6b668a7b..f12f2b847 100644 --- a/angularjs/angular-mocks.d.ts +++ b/angularjs/angular-mocks.d.ts @@ -1,6 +1,7 @@ // Type definitions for Angular JS 1.3 (ngMock, ngMockE2E module) // Project: http://angularjs.org // Definitions by: Diego Vilar +// Definitions by: Tony Curtis // Definitions: https://github.com/borisyankov/DefinitelyTyped /// @@ -97,137 +98,210 @@ declare module angular { // see https://docs.angularjs.org/api/ngMock/service/$httpBackend /////////////////////////////////////////////////////////////////////////// interface IHttpBackendService { + /** + * Flushes all pending requests using the trained responses. + * @param count Number of responses to flush (in the order they arrived). If undefined, all pending requests will be flushed. + */ flush(count?: number): void; + + /** + * Resets all request expectations, but preserves all backend definitions. + */ resetExpectations(): void; + + /** + * Verifies that all of the requests defined via the expect api were made. If any of the requests were not made, verifyNoOutstandingExpectation throws an exception. + */ verifyNoOutstandingExpectation(): void; + + /** + * Verifies that there are no outstanding requests that need to be flushed. + */ verifyNoOutstandingRequest(): void; - expect(method: string, url: string, data?: string, headers?: Object): mock.IRequestHandler; - expect(method: string, url: string, data?: string, headers?: (object: Object) => boolean): mock.IRequestHandler; - expect(method: string, url: string, data?: RegExp, headers?: Object): mock.IRequestHandler; - expect(method: string, url: string, data?: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler; - expect(method: string, url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; - expect(method: string, url: string, data?: (data: string) => boolean, headers?: (object: Object) => boolean): mock.IRequestHandler; - expect(method: string, url: string, data?: Object, headers?: Object): mock.IRequestHandler; - expect(method: string, url: string, data?: Object, headers?: (object: Object) => boolean): mock.IRequestHandler; - expect(method: string, url: RegExp, data?: string, headers?: Object): mock.IRequestHandler; - expect(method: string, url: RegExp, data?: string, headers?: (object: Object) => boolean): mock.IRequestHandler; - expect(method: string, url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler; - expect(method: string, url: RegExp, data?: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler; - expect(method: string, url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; - expect(method: string, url: RegExp, data?: (data: string) => boolean, headers?: (object: Object) => boolean): mock.IRequestHandler; - expect(method: string, url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler; - expect(method: string, url: RegExp, data?: Object, headers?: (object: Object) => boolean): mock.IRequestHandler; - expectDELETE(url: string, headers?: Object): mock.IRequestHandler; - expectDELETE(url: RegExp, headers?: Object): mock.IRequestHandler; - expectGET(url: string, headers?: Object): mock.IRequestHandler; - expectGET(url: RegExp, headers?: Object): mock.IRequestHandler; - expectHEAD(url: string, headers?: Object): mock.IRequestHandler; - expectHEAD(url: RegExp, headers?: Object): mock.IRequestHandler; - expectJSONP(url: string): mock.IRequestHandler; - expectJSONP(url: RegExp): mock.IRequestHandler; + /** + * Creates a new request expectation. + * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. + * Returns an object with respond method that controls how a matched request is handled. + * @param method HTTP method. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + */ + expect(method: string, url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)) :mock.IRequestHandler; - expectPATCH(url: string, data?: string, headers?: Object): mock.IRequestHandler; - expectPATCH(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler; - expectPATCH(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; - expectPATCH(url: string, data?: Object, headers?: Object): mock.IRequestHandler; - expectPATCH(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler; - expectPATCH(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler; - expectPATCH(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; - expectPATCH(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler; + /** + * Creates a new request expectation for DELETE requests. + * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url is as expected. + * @param headers HTTP headers object to be compared with the HTTP headers in the request. + */ + expectDELETE(url: string | RegExp | ((url: string) => boolean), headers?: Object): mock.IRequestHandler; - expectPOST(url: string, data?: string, headers?: Object): mock.IRequestHandler; - expectPOST(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler; - expectPOST(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; - expectPOST(url: string, data?: Object, headers?: Object): mock.IRequestHandler; - expectPOST(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler; - expectPOST(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler; - expectPOST(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; - expectPOST(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler; + /** + * Creates a new request expectation for GET requests. + * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param headers HTTP headers object to be compared with the HTTP headers in the request. + */ + expectGET(url: string | RegExp | ((url: string) => boolean), headers?: Object): mock.IRequestHandler; - expectPUT(url: string, data?: string, headers?: Object): mock.IRequestHandler; - expectPUT(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler; - expectPUT(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; - expectPUT(url: string, data?: Object, headers?: Object): mock.IRequestHandler; - expectPUT(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler; - expectPUT(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler; - expectPUT(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; - expectPUT(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler; + /** + * Creates a new request expectation for HEAD requests. + * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param headers HTTP headers object to be compared with the HTTP headers in the request. + */ + expectHEAD(url: string | RegExp | ((url: string) => boolean), headers?: Object): mock.IRequestHandler; + + /** + * Creates a new request expectation for JSONP requests. + * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, or if function returns false. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + */ + expectJSONP(url: string | RegExp | ((url: string) => boolean)): mock.IRequestHandler; - when(method: string, url: string, data?: string, headers?: Object): mock.IRequestHandler; - when(method: string, url: string, data?: string, headers?: (object: Object) => boolean): mock.IRequestHandler; - when(method: string, url: string, data?: RegExp, headers?: Object): mock.IRequestHandler; - when(method: string, url: string, data?: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler; - when(method: string, url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; - when(method: string, url: string, data?: (data: string) => boolean, headers?: (object: Object) => boolean): mock.IRequestHandler; - when(method: string, url: string, data?: Object, headers?: Object): mock.IRequestHandler; - when(method: string, url: string, data?: Object, headers?: (object: Object) => boolean): mock.IRequestHandler; - when(method: string, url: RegExp, data?: string, headers?: Object): mock.IRequestHandler; - when(method: string, url: RegExp, data?: string, headers?: (object: Object) => boolean): mock.IRequestHandler; - when(method: string, url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler; - when(method: string, url: RegExp, data?: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler; - when(method: string, url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; - when(method: string, url: RegExp, data?: (data: string) => boolean, headers?: (object: Object) => boolean): mock.IRequestHandler; - when(method: string, url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler; - when(method: string, url: RegExp, data?: Object, headers?: (object: Object) => boolean): mock.IRequestHandler; + /** + * Creates a new request expectation for PATCH requests. + * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + */ + expectPATCH(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object): mock.IRequestHandler; - whenDELETE(url: string, headers?: Object): mock.IRequestHandler; - whenDELETE(url: string, headers?: (object: Object) => boolean): mock.IRequestHandler; - whenDELETE(url: RegExp, headers?: Object): mock.IRequestHandler; - whenDELETE(url: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler; + /** + * Creates a new request expectation for POST requests. + * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + */ + expectPOST(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object): mock.IRequestHandler; - whenGET(url: string, headers?: Object): mock.IRequestHandler; - whenGET(url: string, headers?: (object: Object) => boolean): mock.IRequestHandler; - whenGET(url: RegExp, headers?: Object): mock.IRequestHandler; - whenGET(url: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler; + /** + * Creates a new request expectation for PUT requests. + * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + */ + expectPUT(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object): mock.IRequestHandler; - whenHEAD(url: string, headers?: Object): mock.IRequestHandler; - whenHEAD(url: string, headers?: (object: Object) => boolean): mock.IRequestHandler; - whenHEAD(url: RegExp, headers?: Object): mock.IRequestHandler; - whenHEAD(url: RegExp, headers?: (object: Object) => boolean): mock.IRequestHandler; + /** + * Creates a new backend definition. + * Returns an object with respond method that controls how a matched request is handled. + * @param method HTTP method. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + */ + when(method: string, url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler; - whenJSONP(url: string): mock.IRequestHandler; - whenJSONP(url: RegExp): mock.IRequestHandler; + /** + * Creates a new backend definition for DELETE requests. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + */ + whenDELETE(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler; - whenPATCH(url: string, data?: string, headers?: Object): mock.IRequestHandler; - whenPATCH(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler; - whenPATCH(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; - whenPATCH(url: string, data?: Object, headers?: Object): mock.IRequestHandler; - whenPATCH(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler; - whenPATCH(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler; - whenPATCH(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; - whenPATCH(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler; + /** + * Creates a new backend definition for GET requests. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + */ + whenGET(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler; - whenPOST(url: string, data?: string, headers?: Object): mock.IRequestHandler; - whenPOST(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler; - whenPOST(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; - whenPOST(url: string, data?: Object, headers?: Object): mock.IRequestHandler; - whenPOST(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler; - whenPOST(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler; - whenPOST(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; - whenPOST(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler; + /** + * Creates a new backend definition for HEAD requests. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + */ + whenHEAD(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler; - whenPUT(url: string, data?: string, headers?: Object): mock.IRequestHandler; - whenPUT(url: string, data?: RegExp, headers?: Object): mock.IRequestHandler; - whenPUT(url: string, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; - whenPUT(url: string, data?: Object, headers?: Object): mock.IRequestHandler; - whenPUT(url: RegExp, data?: string, headers?: Object): mock.IRequestHandler; - whenPUT(url: RegExp, data?: RegExp, headers?: Object): mock.IRequestHandler; - whenPUT(url: RegExp, data?: (data: string) => boolean, headers?: Object): mock.IRequestHandler; - whenPUT(url: RegExp, data?: Object, headers?: Object): mock.IRequestHandler; + /** + * Creates a new backend definition for JSONP requests. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + */ + whenJSONP(url: string | RegExp | ((url: string) => boolean)): mock.IRequestHandler; + + /** + * Creates a new backend definition for PATCH requests. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + */ + whenPATCH(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler; + + /** + * Creates a new backend definition for POST requests. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + */ + whenPOST(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler; + + /** + * Creates a new backend definition for PUT requests. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + */ + whenPUT(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler; } export module mock { // returned interface by the the mocked HttpBackendService expect/when methods interface IRequestHandler { - respond(func: Function): void; - respond(status: number, data?: any, headers?: any): void; - respond(data: any, headers?: any): void; + + /** + * Controls the response for a matched request using a function to construct the response. + * Returns the RequestHandler object for possible overrides. + * @param func Function that receives the request HTTP method, url, data, and headers and returns an array containing response status (number), data, headers, and status text. + */ + respond(func: ((method: string, url: string, data?: string | Object, headers?: Object) => [number, string, Object, string])): IRequestHandler; - // Available wehn ngMockE2E is loaded - passThrough(): void; + /** + * Controls the response for a matched request using supplied static data to construct the response. + * Returns the RequestHandler object for possible overrides. + * @param status HTTP status code to add to the response. + * @param data Data to add to the response. + * @param headers Headers object to add to the response. + * @param responseText Response text to add to the response. + */ + respond(status: number, data: string | Object, headers?: Object, responseText?: string): IRequestHandler; + + /** + * Controls the response for a matched request using the HTTP status code 200 and supplied static data to construct the response. + * Returns the RequestHandler object for possible overrides. + * @param data Data to add to the response. + * @param headers Headers object to add to the response. + * @param responseText Response text to add to the response. + */ + respond(data: string | {}, headers?: Object, responseText?: string): IRequestHandler; + + // Available when ngMockE2E is loaded + /** + * Any request matching a backend definition or expectation with passThrough handler will be passed through to the real backend (an XHR request will be made to the server.) + */ + passThrough(): IRequestHandler; } } From 796e02caace603efa00d00ca9f07dc0affc1dd4c Mon Sep 17 00:00:00 2001 From: tcurtis1 Date: Tue, 4 Aug 2015 15:44:06 -0600 Subject: [PATCH 038/345] Changes to httpBackend to conform to angular documentation here: https://code.angularjs.org/1.3.16/docs/api/ngMock/service/$httpBackend Mainly add the option to pass a function in the url parameter. Also updated IRequestHandler interface respond function to return an IRequestHandler, and updated overloads. Also added documentation. --- angularjs/angular-mocks-tests.ts | 100 ++++++++++++++++++++++++++++++- angularjs/angular-mocks.d.ts | 34 ++++++----- 2 files changed, 118 insertions(+), 16 deletions(-) diff --git a/angularjs/angular-mocks-tests.ts b/angularjs/angular-mocks-tests.ts index e9cd21642..57820af08 100644 --- a/angularjs/angular-mocks-tests.ts +++ b/angularjs/angular-mocks-tests.ts @@ -126,18 +126,35 @@ requestHandler = httpBackendService.expect('GET', /test.local/, function (data: requestHandler = httpBackendService.expect('GET', /test.local/, { key: 'value' }); requestHandler = httpBackendService.expect('GET', /test.local/, { key: 'value' }, { header: 'value' }); requestHandler = httpBackendService.expect('GET', /test.local/, { key: 'value' }, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }); +requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, 'response data'); +requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, 'response data', { header: 'value' }); +requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, 'response data', function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, /response data/); +requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, /response data/, { header: 'value' }); +requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, /response data/, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, function (data: string): boolean { return true; }); +requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, { key: 'value' }); +requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, { key: 'value' }, function (headers: Object): boolean { return true; }); requestHandler = httpBackendService.expectDELETE('http://test.local'); requestHandler = httpBackendService.expectDELETE('http://test.local', { header: 'value' }); requestHandler = httpBackendService.expectDELETE(/test.local/, { header: 'value' }); +requestHandler = httpBackendService.expectDELETE((url: string) => { return true; }, { header: 'value' }); requestHandler = httpBackendService.expectGET('http://test.local'); requestHandler = httpBackendService.expectGET('http://test.local', { header: 'value' }); requestHandler = httpBackendService.expectGET(/test.local/, { header: 'value' }); +requestHandler = httpBackendService.expectGET((url: string) => { return true; }, { header: 'value' }); requestHandler = httpBackendService.expectHEAD('http://test.local'); requestHandler = httpBackendService.expectHEAD('http://test.local', { header: 'value' }); requestHandler = httpBackendService.expectHEAD(/test.local/, { header: 'value' }); +requestHandler = httpBackendService.expectHEAD((url: string) => { return true; }, { header: 'value' }); requestHandler = httpBackendService.expectJSONP('http://test.local'); requestHandler = httpBackendService.expectJSONP(/test.local/); +requestHandler = httpBackendService.expectJSONP((url: string) => { return true; }); requestHandler = httpBackendService.expectPATCH('http://test.local'); requestHandler = httpBackendService.expectPATCH('http://test.local', 'response data'); @@ -157,6 +174,15 @@ requestHandler = httpBackendService.expectPATCH(/test.local/, function (data: st requestHandler = httpBackendService.expectPATCH(/test.local/, function (data: string): boolean { return true; }, { header: 'value' }); requestHandler = httpBackendService.expectPATCH(/test.local/, { key: 'value' }); requestHandler = httpBackendService.expectPATCH(/test.local/, { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }); +requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, 'response data'); +requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, 'response data', { header: 'value' }); +requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, /response data/); +requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, /response data/, { header: 'value' }); +requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, function (data: string): boolean { return true; }); +requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, { key: 'value' }); +requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, { key: 'value' }, { header: 'value' }); requestHandler = httpBackendService.expectPOST('http://test.local'); requestHandler = httpBackendService.expectPOST('http://test.local', 'response data'); @@ -176,6 +202,15 @@ requestHandler = httpBackendService.expectPOST(/test.local/, function (data: str requestHandler = httpBackendService.expectPOST(/test.local/, function (data: string): boolean { return true; }, { header: 'value' }); requestHandler = httpBackendService.expectPOST(/test.local/, { key: 'value' }); requestHandler = httpBackendService.expectPOST(/test.local/, { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.expectPOST((url: string) => { return true; }); +requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, 'response data'); +requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, 'response data', { header: 'value' }); +requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, /response data/); +requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, /response data/, { header: 'value' }); +requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, function (data: string): boolean { return true; }); +requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, { key: 'value' }); +requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, { key: 'value' }, { header: 'value' }); requestHandler = httpBackendService.expectPUT('http://test.local'); requestHandler = httpBackendService.expectPUT('http://test.local', 'response data'); @@ -195,6 +230,15 @@ requestHandler = httpBackendService.expectPUT(/test.local/, function (data: stri requestHandler = httpBackendService.expectPUT(/test.local/, function (data: string): boolean { return true; }, { header: 'value' }); requestHandler = httpBackendService.expectPUT(/test.local/, { key: 'value' }); requestHandler = httpBackendService.expectPUT(/test.local/, { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.expectPUT((url: string) => { return true; }); +requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, 'response data'); +requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, 'response data', { header: 'value' }); +requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, /response data/); +requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, /response data/, { header: 'value' }); +requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, function (data: string): boolean { return true; }); +requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, { key: 'value' }); +requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, { key: 'value' }, { header: 'value' }); requestHandler = httpBackendService.when('GET', 'http://test.local'); requestHandler = httpBackendService.when('GET', 'http://test.local', 'response data'); @@ -222,18 +266,35 @@ requestHandler = httpBackendService.when('GET', /test.local/, function (data: st requestHandler = httpBackendService.when('GET', /test.local/, { key: 'value' }); requestHandler = httpBackendService.when('GET', /test.local/, { key: 'value' }, { header: 'value' }); requestHandler = httpBackendService.when('GET', /test.local/, { key: 'value' }, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.when('GET', (url: string) => { return true; }); +requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, 'response data'); +requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, 'response data', { header: 'value' }); +requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, 'response data', function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, /response data/); +requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, /response data/, { header: 'value' }); +requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, /response data/, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, function (data: string): boolean { return true; }); +requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, { key: 'value' }); +requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, { key: 'value' }, function (headers: Object): boolean { return true; }); requestHandler = httpBackendService.whenDELETE('http://test.local'); requestHandler = httpBackendService.whenDELETE('http://test.local', { header: 'value' }); requestHandler = httpBackendService.whenDELETE(/test.local/, { header: 'value' }); +requestHandler = httpBackendService.whenDELETE((url: string) => { return true; }, { header: 'value' }); requestHandler = httpBackendService.whenGET('http://test.local'); requestHandler = httpBackendService.whenGET('http://test.local', { header: 'value' }); requestHandler = httpBackendService.whenGET(/test.local/, { header: 'value' }); +requestHandler = httpBackendService.whenGET((url: string) => { return true; }, { header: 'value' }); requestHandler = httpBackendService.whenHEAD('http://test.local'); requestHandler = httpBackendService.whenHEAD('http://test.local', { header: 'value' }); requestHandler = httpBackendService.whenHEAD(/test.local/, { header: 'value' }); +requestHandler = httpBackendService.whenHEAD((url: string) => { return true; }, { header: 'value' }); requestHandler = httpBackendService.whenJSONP('http://test.local'); requestHandler = httpBackendService.whenJSONP(/test.local/); +requestHandler = httpBackendService.whenJSONP((url: string) => { return true; }); requestHandler = httpBackendService.whenPATCH('http://test.local'); requestHandler = httpBackendService.whenPATCH('http://test.local', 'response data'); @@ -253,6 +314,15 @@ requestHandler = httpBackendService.whenPATCH(/test.local/, function (data: stri requestHandler = httpBackendService.whenPATCH(/test.local/, function (data: string): boolean { return true; }, { header: 'value' }); requestHandler = httpBackendService.whenPATCH(/test.local/, { key: 'value' }); requestHandler = httpBackendService.whenPATCH(/test.local/, { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }); +requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, 'response data'); +requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, 'response data', { header: 'value' }); +requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, /response data/); +requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, /response data/, { header: 'value' }); +requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, function (data: string): boolean { return true; }); +requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, { key: 'value' }); +requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, { key: 'value' }, { header: 'value' }); requestHandler = httpBackendService.whenPOST('http://test.local'); requestHandler = httpBackendService.whenPOST('http://test.local', 'response data'); @@ -272,6 +342,15 @@ requestHandler = httpBackendService.whenPOST(/test.local/, function (data: strin requestHandler = httpBackendService.whenPOST(/test.local/, function (data: string): boolean { return true; }, { header: 'value' }); requestHandler = httpBackendService.whenPOST(/test.local/, { key: 'value' }); requestHandler = httpBackendService.whenPOST(/test.local/, { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.whenPOST((url: string) => { return true; }); +requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, 'response data'); +requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, 'response data', { header: 'value' }); +requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, /response data/); +requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, /response data/, { header: 'value' }); +requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, function (data: string): boolean { return true; }); +requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, { key: 'value' }); +requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, { key: 'value' }, { header: 'value' }); requestHandler = httpBackendService.whenPUT('http://test.local'); requestHandler = httpBackendService.whenPUT('http://test.local', 'response data'); @@ -291,15 +370,32 @@ requestHandler = httpBackendService.whenPUT(/test.local/, function (data: string requestHandler = httpBackendService.whenPUT(/test.local/, function (data: string): boolean { return true; }, { header: 'value' }); requestHandler = httpBackendService.whenPUT(/test.local/, { key: 'value' }); requestHandler = httpBackendService.whenPUT(/test.local/, { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.whenPUT((url: string) => { return true; }); +requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, 'response data'); +requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, 'response data', { header: 'value' }); +requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, /response data/); +requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, /response data/, { header: 'value' }); +requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, function (data: string): boolean { return true; }); +requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, { key: 'value' }); +requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, { key: 'value' }, { header: 'value' }); /////////////////////////////////////// // IRequestHandler /////////////////////////////////////// requestHandler.passThrough(); -requestHandler.respond(function () { }); +requestHandler.passThrough().passThrough(); +requestHandler.respond((method, url, data, headers) => [404, 'data', { header: 'value' }, 'responseText']); +requestHandler.respond((method, url, data, headers) => [404, 'data', { header: 'value' }, 'responseText']).respond({}); +requestHandler.respond((method, url, data, headers) => { return [404, { key: 'value' }, { header: 'value' }, 'responseText']; }); +requestHandler.respond('data'); +requestHandler.respond('data').respond({}); requestHandler.respond({ key: 'value' }); requestHandler.respond({ key: 'value' }, { header: 'value' }); -requestHandler.respond(404); +requestHandler.respond({ key: 'value' }, { header: 'value' }, 'responseText'); +requestHandler.respond(404, 'data'); +requestHandler.respond(404, 'data').respond({}); requestHandler.respond(404, { key: 'value' }); requestHandler.respond(404, { key: 'value' }, { header: 'value' }); +requestHandler.respond(404, { key: 'value' }, { header: 'value' }, 'responseText'); diff --git a/angularjs/angular-mocks.d.ts b/angularjs/angular-mocks.d.ts index f12f2b847..20aa85f72 100644 --- a/angularjs/angular-mocks.d.ts +++ b/angularjs/angular-mocks.d.ts @@ -1,7 +1,6 @@ // Type definitions for Angular JS 1.3 (ngMock, ngMockE2E module) // Project: http://angularjs.org -// Definitions by: Diego Vilar -// Definitions by: Tony Curtis +// Definitions by: Diego Vilar , Tony Curtis // Definitions: https://github.com/borisyankov/DefinitelyTyped /// @@ -119,7 +118,6 @@ declare module angular { */ verifyNoOutstandingRequest(): void; - /** * Creates a new request expectation. * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. @@ -267,7 +265,15 @@ declare module angular { } export module mock { - + // this interface makes it possible to diferentiate between a function parameter (in the first overload for IRequestHandler) + // and the data: string | Object parameter in the second overload. Since a function is an object, and the first overload + // takes one function param and the second overload takes a data string or Object with the other two parameters being optional, + // there was no type difference between respond((a,b,c,d) => {}) and respond({}). Using the JsonResponseData interface + // as a type creates a difference in the signatures changing data: string | Object to data: string | JsonResponseData + interface JsonResponseData extends Object { + [key: string] : any; + } + // returned interface by the the mocked HttpBackendService expect/when methods interface IRequestHandler { @@ -276,7 +282,16 @@ declare module angular { * Returns the RequestHandler object for possible overrides. * @param func Function that receives the request HTTP method, url, data, and headers and returns an array containing response status (number), data, headers, and status text. */ - respond(func: ((method: string, url: string, data?: string | Object, headers?: Object) => [number, string, Object, string])): IRequestHandler; + respond(func: ((method: string, url: string, data: string | Object, headers: Object) => [number, string | Object, Object, string])): IRequestHandler; + + /** + * Controls the response for a matched request using the HTTP status code 200 and supplied static data to construct the response. + * Returns the RequestHandler object for possible overrides. + * @param data Data to add to the response. + * @param headers Headers object to add to the response. + * @param responseText Response text to add to the response. + */ + respond(data: string | JsonResponseData, headers?: Object, responseText?: string): IRequestHandler; /** * Controls the response for a matched request using supplied static data to construct the response. @@ -288,15 +303,6 @@ declare module angular { */ respond(status: number, data: string | Object, headers?: Object, responseText?: string): IRequestHandler; - /** - * Controls the response for a matched request using the HTTP status code 200 and supplied static data to construct the response. - * Returns the RequestHandler object for possible overrides. - * @param data Data to add to the response. - * @param headers Headers object to add to the response. - * @param responseText Response text to add to the response. - */ - respond(data: string | {}, headers?: Object, responseText?: string): IRequestHandler; - // Available when ngMockE2E is loaded /** * Any request matching a backend definition or expectation with passThrough handler will be passed through to the real backend (an XHR request will be made to the server.) From ea24441ae4b3a413dbde70adc7b3f8e640258bb6 Mon Sep 17 00:00:00 2001 From: tcurtis1 Date: Tue, 4 Aug 2015 19:30:56 -0600 Subject: [PATCH 039/345] Problem with JsonResponseData interface, removed it. --- angularjs/angular-mocks-tests.ts | 2 ++ angularjs/angular-mocks.d.ts | 27 +++++++++------------------ 2 files changed, 11 insertions(+), 18 deletions(-) diff --git a/angularjs/angular-mocks-tests.ts b/angularjs/angular-mocks-tests.ts index 57820af08..63ea220f6 100644 --- a/angularjs/angular-mocks-tests.ts +++ b/angularjs/angular-mocks-tests.ts @@ -384,6 +384,7 @@ requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, { /////////////////////////////////////// // IRequestHandler /////////////////////////////////////// +var expectedData = { key: 'value'}; requestHandler.passThrough(); requestHandler.passThrough().passThrough(); requestHandler.respond((method, url, data, headers) => [404, 'data', { header: 'value' }, 'responseText']); @@ -391,6 +392,7 @@ requestHandler.respond((method, url, data, headers) => [404, 'data', { header: ' requestHandler.respond((method, url, data, headers) => { return [404, { key: 'value' }, { header: 'value' }, 'responseText']; }); requestHandler.respond('data'); requestHandler.respond('data').respond({}); +requestHandler.respond(expectedData); requestHandler.respond({ key: 'value' }); requestHandler.respond({ key: 'value' }, { header: 'value' }); requestHandler.respond({ key: 'value' }, { header: 'value' }, 'responseText'); diff --git a/angularjs/angular-mocks.d.ts b/angularjs/angular-mocks.d.ts index 20aa85f72..7e3806353 100644 --- a/angularjs/angular-mocks.d.ts +++ b/angularjs/angular-mocks.d.ts @@ -265,15 +265,6 @@ declare module angular { } export module mock { - // this interface makes it possible to diferentiate between a function parameter (in the first overload for IRequestHandler) - // and the data: string | Object parameter in the second overload. Since a function is an object, and the first overload - // takes one function param and the second overload takes a data string or Object with the other two parameters being optional, - // there was no type difference between respond((a,b,c,d) => {}) and respond({}). Using the JsonResponseData interface - // as a type creates a difference in the signatures changing data: string | Object to data: string | JsonResponseData - interface JsonResponseData extends Object { - [key: string] : any; - } - // returned interface by the the mocked HttpBackendService expect/when methods interface IRequestHandler { @@ -284,15 +275,6 @@ declare module angular { */ respond(func: ((method: string, url: string, data: string | Object, headers: Object) => [number, string | Object, Object, string])): IRequestHandler; - /** - * Controls the response for a matched request using the HTTP status code 200 and supplied static data to construct the response. - * Returns the RequestHandler object for possible overrides. - * @param data Data to add to the response. - * @param headers Headers object to add to the response. - * @param responseText Response text to add to the response. - */ - respond(data: string | JsonResponseData, headers?: Object, responseText?: string): IRequestHandler; - /** * Controls the response for a matched request using supplied static data to construct the response. * Returns the RequestHandler object for possible overrides. @@ -303,6 +285,15 @@ declare module angular { */ respond(status: number, data: string | Object, headers?: Object, responseText?: string): IRequestHandler; + /** + * Controls the response for a matched request using the HTTP status code 200 and supplied static data to construct the response. + * Returns the RequestHandler object for possible overrides. + * @param data Data to add to the response. + * @param headers Headers object to add to the response. + * @param responseText Response text to add to the response. + */ + respond(data: string | Object, headers?: Object, responseText?: string): IRequestHandler; + // Available when ngMockE2E is loaded /** * Any request matching a backend definition or expectation with passThrough handler will be passed through to the real backend (an XHR request will be made to the server.) From da093877f475389bf0e4b62d29afbf17fbd597a4 Mon Sep 17 00:00:00 2001 From: Ivan Drinchev Date: Thu, 6 Aug 2015 20:06:25 +0200 Subject: [PATCH 040/345] Added definitions for Sequelize 3.4.1 --- sequelize/sequelize-2.0.0.d.ts | 2787 +++++++ sequelize/sequelize-test.ts | 1284 ++++ ...lize-tests.ts => sequelize-tests-2.0.0.ts} | 2 +- sequelize/sequelize.d.ts | 6802 +++++++++++------ 4 files changed, 8520 insertions(+), 2355 deletions(-) create mode 100644 sequelize/sequelize-2.0.0.d.ts create mode 100644 sequelize/sequelize-test.ts rename sequelize/{sequelize-tests.ts => sequelize-tests-2.0.0.ts} (99%) diff --git a/sequelize/sequelize-2.0.0.d.ts b/sequelize/sequelize-2.0.0.d.ts new file mode 100644 index 000000000..1bb6be593 --- /dev/null +++ b/sequelize/sequelize-2.0.0.d.ts @@ -0,0 +1,2787 @@ +// Type definitions for Sequelize 2.0.0 dev13 +// Project: http://sequelizejs.com +// Definitions by: samuelneff , Peter Harris +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// Based on original work by: samuelneff + +/// +/// + +declare module "sequelize" +{ + module sequelize { + interface SequelizeStaticAndInstance { + + /** + * A reference to sequelize utilities. Most users will not need to use these utils directly. However, you might want + * to use Sequelize.Utils._, which is a reference to the lodash library, if you don't already have it imported in + * your project. + */ + Utils: Utils; + + /** + * A modified version of bluebird promises, that allows listening for sql events. + * + * @see Promise + */ + Promise: Promise; + + /** + * Exposes the validator.js object, so you can extend it with custom validation functions. The validator is exposed + * both on the instance, and on the constructor. + * + * @see Validator + */ + Validator: Validator; + + QueryTypes: QueryTypes; + + /** + * A general error class. + */ + Error: Error; + + /** + * Emitted when a validation fails. + * + * @see ValidationError + */ + ValidationError: ValidationError; + + /** + * Creates a object representing a database function. This can be used in search queries, both in where and order + * parts, and as default values in column definitions. If you want to refer to columns in your function, you should + * use sequelize.col, so that the columns are properly interpreted as columns and not a strings. + * + * @param fn The function you want to call. + * @param args All further arguments will be passed as arguments to the function. + */ + fn(fn: string, ...args: Array): any; + + /** + * Creates a object representing a column in the DB. This is often useful in conjunction with sequelize.fn, since + * raw string arguments to fn will be escaped. + * + * @param col The name of the column + */ + col(col: string): Col; + + /** + * Creates a object representing a call to the cast function. + * + * @param val The value to cast. + * @param type The type to cast it to. + */ + cast(val: any, type: string): Cast; + + /** + * Creates a object representing a literal, i.e. something that will not be escaped. + * + * @param val Value to convert to a literal. + */ + literal(val: any): Literal; + + /** + * An AND query. + * + * @param args Each argument (string or object) will be joined by AND. + */ + and(...args: Array): And; + + /** + * An OR query. + * + * @param args Each argument (string or object) will be joined by OR. + */ + or(...args: Array): Or; + + /** + * A way of specifying attr = condition. Mostly used internally. + * + * @param attr The attribute + * @param condition The condition. Can be both a simply type, or a further condition (.or, .and, .literal etc.) + */ + where(attr: string, condition: any): Where; + } + + interface SequelizeStatic extends SequelizeStaticAndInstance, DataTypes { + /** + * Instantiate sequelize with name of database and username + * @param database database name + * @param username user name + */ + new (database: string, username: string): Sequelize; + + /** + * Instantiate sequelize with name of database, username and password + * @param database database name + * @param username user name + * @param password password + */ + new (database: string, username: string, password: string): Sequelize; + + /** + * Instantiate sequelize with name of database, username, password, and options. + * @param database database name + * @param username user name + * @param password password + * @param options options. @see Options + */ + new (database: string, username: string, password: string, options: Options): Sequelize; + + /** + * Instantiate sequelize with name of database, username, and options. + * + * @param database database name + * @param username user name + * @param options options. @see Options + */ + new (database: string, username: string, options: Options): Sequelize; + + /** + * Instantiate sequlize with an URI + * @param connectionString A full database URI + * @param options Options for sequelize. @see Options + */ + new (connectionString: string, options?: Options): Sequelize; + } + + interface Sequelize extends SequelizeStaticAndInstance { + /** + * Sequelize configuration (undocumented). + */ + config: Config; + + /** + * Sequelize options (undocumented). + */ + options: Options; + + /** + * Models are stored here under the name given to sequelize.define + */ + models: any; + modelManager: ModelManager; + daoFactoryManager: ModelManager; + transactionManager: TransactionManager; + importCache: any; + + /** + * A reference to the sequelize transaction class. Use this to access isolationLevels when creating a transaction. + * + * @see Transaction + */ + Transaction: TransactionStatic; + + /** + * Returns the specified dialect. + */ + getDialect(): string; + + /** + * Returns the singleton instance of QueryInterface. + */ + getQueryInterface(): QueryInterface; + + /** + * Returns the singleton instance of Migrator. + * @param options Migration options + * @param force A flag that defines if the migrator should get instantiated or not. + */ + getMigrator(options?: MigratorOptions, force?: boolean): Migrator; + + /** + * Define a new model, representing a table in the DB. + * + * @param daoName The name of the entity (table). Typically specified in singular form. + * @param attributes A hash of attributes to define. Each attribute can be either a string name for the attribute + * or can be an object defining the attribute and its options. Note attributes is not fully + * typed since TypeScript does not support union types--it can be either a string or an + * options object. @see AttributeOptions. + * @param options Table options. @see DefineOptions. + */ + define(daoName: string, attributes: any, options?: DefineOptions): Model; + + /** + * Fetch a DAO factory which is already defined. + * + * @param daoName The name of a model defined with Sequelize.define. + */ + model(daoName: string): Model; + + /** + * Checks whether a model with the given name is defined. + * + * @param daoName The name of a model defined with Sequelize.define. + */ + isDefined(daoName: string): boolean; + + /** + * Imports a model defined in another file. + * + * @param path The path to the file that holds the model you want to import. If the part is relative, it will be + * resolved relatively to the calling file + */ + import(path: string): Model; + + /** + * Execute a query on the DB, with the possibility to bypass all the sequelize goodness. + * + * @param sql SQL statement to execute. + * + * @param callee If callee is provided, the selected data will be used to build an instance of the DAO represented + * by the factory. Equivalent to calling Model.build with the values provided by the query. + * + * @param options Query options. + * + * @param replacements Either an object of named parameter replacements in the format :param or an array of + * unnamed replacements to replace ? in your SQL. + */ + query(sql: string, callee?: Model, options?: QueryOptions, replacements?: any): EventEmitter; + + query(sql: string, callee?: Model, options?: QueryOptions): EventEmitterT>; + + /** + * Create a new database schema. + * + * @param schema Name of the schema. + */ + createSchema(schema: string): EventEmitter; + + /** + * Show all defined schemas. + */ + showAllSchemas(): EventEmitter; + + /** + * Drop a single schema. + * + * @param schema Name of the schema. + */ + dropSchema(schema: string): EventEmitter; + + /** + * Drop all schemas. + */ + dropAllSchemas(): EventEmitter; + + /** + * Sync all defined DAOs to the DB. + * + * @param options Options. + */ + sync(options?: SyncOptions): EventEmitter; + + /** + * Drop all tables defined through this sequelize instance. This is done by calling Model.drop on each model. + * + * @param options The options passed to each call to Model.drop. + */ + drop(options: DropOptions): EventEmitter; + + /** + * Test the connection by trying to authenticate. Alias for 'validate'. + */ + authenticate(): EventEmitter; + + /** + * Alias for authenticate(). Test the connection by trying to authenticate. Alias for 'validate'. + */ + validate(): EventEmitter; + + /** + * !! DEPRECATED : When passing a callback to a transaction a promise chain is expected in return, + * the transaction will be committed or rejected based on the promise chain returned to the callback. + * + * Start a transaction. When using transactions, you should pass the transaction in the options argument in order + * for the query to happen under that transaction. + * + * @param callback Called when the transaction has been set up and is ready for use. Callback takes transaction + * argument (overload available for error and transaction arguments too). + */ + transaction(callback: (transaction: Transaction) => boolean): Promise; + + /** + * Start a transaction. When using transactions, you should pass the transaction in the options argument in order + * for the query to happen under that transaction. + * + * @param options Transaction options. + * @param callback Called when the transaction has been set up and is ready for use. Callback takes transaction + * argument (overload available for error and transaction arguments too). + */ + transaction(options?: TransactionOptions, callback?: (transaction: Transaction) => void): PromiseT; + + close(): void; + } + + interface Config { + database?: string; + username?: string; + password?: string; + host?: string; + port?: number; + pool?: PoolOptions; + protocol?: string; + queue?: boolean; + native?: boolean; + ssl?: boolean; + replication?: ReplicationOptions; + dialectModulePath?: string; + maxConcurrentQueries?: number; + dialectOptions?: any; + } + + interface Model extends Hooks, Associations { + /** + * A reference to the sequelize instance. + */ + sequelize: Sequelize; + + /** + * The name of the model, typically singular. + */ + name: string; + + /** + * The name of the underlying database table, typically plural. + */ + tableName: string; + + options: DefineOptions; + attributes: any; + rawAttributes: any; + modelManager: ModelManager; + daoFactoryManager: ModelManager; + associations: any; + scopeObj: any; + + /** + * Sync this Model to the DB, that is create the table. Upon success, the callback will be called with the model + * instance (this). + */ + sync(options?: SyncOptions): PromiseT>; + + /** + * Drop the table represented by this Model. + * + * @param options + */ + drop(options?: DropOptions): Promise; + + /** + * Apply a schema to this model. For postgres, this will actually place the schema in front of the table name - + * "schema"."tableName", while the schema will be prepended to the table name for mysql and sqlite - + * 'schema.tablename'. + * + * @param schema The name of the schema. + * @param options Schema options. + */ + schema(schema: string, options?: SchemaOptions): Model; + + /** + * Get the tablename of the model, taking schema into account. The method will return The name as a string if the + * model has no schema, or an object with tableName, schema and delimiter properties. + */ + getTableName(): any; + + /** + * Apply a scope created in define to the model. + * + * @param options The scope(s) to apply. Scopes can either be passed as consecutive arguments, or as an array of + * arguments. To apply simple scopes, pass them as strings. For scope function, pass an object, + * with a method property. The value can either be a string, if the method does not take any + * arguments, or an array, where the first element is the name of the method, and consecutive + * elements are arguments to that method. Pass null to remove all scopes, including the default. + */ + scope(options: any): Model; + + /** + * Search for multiple instances.. + * + * @param options A hash of options to describe the scope of the search. + * @param queryOptions Set the query options, e.g. raw, specifying that you want raw data instead of built + * Instances. See sequelize.query for options. + */ + findAll(options?: FindOptions, queryOptions?: QueryOptions): PromiseT>; + + /** + * Search for a single instance. This applies LIMIT 1, so the listener will always be called with a single instance. + * + * @param options A hash of options to describe the scope of the search. + * @param queryOptions Set the query options, e.g. raw, specifying that you want raw data instead of built + * Instances. See sequelize.query for options + */ + find(options?: FindOptions, queryOptions?: QueryOptions): PromiseT; + + /** + * Search for a single instance. This applies LIMIT 1, so the listener will always be called with a single instance. + * + * @param options A number to search by id. + * @param queryOptions Set the query options, e.g. raw, specifying that you want raw data instead of built + * Instances. See sequelize.query for options + */ + find(id?: number, queryOptions?: QueryOptions): PromiseT; + + /** + * Run an aggregation method on the specified field. + * + * @param field The field to aggregate over. Can be a field name or *. + * @param aggregateFunction The function to use for aggregation, e.g. sum, max etc. + * @param options Query options, particularly options.dataType. + */ + aggregate(field: string, aggregateFunction: string, options: FindOptions): PromiseT; + + /** + * Count the number of records matching the provided where clause. + * + * @param options Conditions and options for the query. + */ + count(options?: FindOptions): PromiseT; + + /** + * Find all the rows matching your query, within a specified offset / limit, and get the total number of rows + * matching your query. This is very usefull for paging. + * + * @param findOptions Filtering options + * @param queryOptions Query options + */ + findAndCountAll(findOptions?: FindOptions, queryOptions?: QueryOptions): PromiseT>; + + /** + * Find the maximum value of field. + * + * @param field + * @param options + */ + max(field: string, options?: FindOptions): PromiseT; + + /** + * Find the minimum value of field. + * + * @param field + * @param options + */ + min(field: string, options?: FindOptions): PromiseT; + + /** + * Find the sum of field. + * + * @param field + * @param options + */ + sum(field: string, options?: FindOptions): PromiseT; + + /** + * Builds a new model instance. Values is an object of key value pairs, must be defined but can be empty. + * + * @param values any from which to build entity instance. + * @param options any construction options. + */ + build(values: TPojo, options?: BuildOptions): TInstance; + + /** + * Builds a new model instance and calls save on it.. + * + * @param values + * @param options + */ + create(values: TPojo, options?: CopyOptions): PromiseT; + + /** + * Find a row that matches the query, or build (but don't save) the row if none is found. The successfull result + * of the promise will be (instance, initialized) - Make sure to use .spread(). + * + * @param where A hash of search attributes. Note that this method differs from finders, in that the syntax + * is { attr1: 42 } and NOT { where: { attr1: 42}}. This may be subject to change in 2.0 + * @param defaults Default values to use if building a new instance + * @param options Options passed to the find call + */ + findOrInitialize(where: any, defaults?: TPojo, options?: QueryOptions): PromiseT; + + /** + * Find a row that matches the query, or build and save the row if none is found The successfull result of the + * promise will be (instance, created) - Make sure to use .spread(). + * + * @param where A hash of search attributes. Note that this method differs from finders, in that the syntax is + * { attr1: 42 } and NOT { where: { attr1: 42}}. This is subject to change in 2.0 + * @param defaults Default values to use if creating a new instance + * @param options Options passed to the find and create calls. + */ + findOrCreate(where: any, defaults?: TPojo, options?: FindOrCreateOptions): PromiseT; + + /** + * Create and insert multiple instances in bulk. + * + * @param records List of objects (key/value pairs) to create instances from. + * @param options + */ + bulkCreate(records: Array, options?: BulkCreateOptions): PromiseT>; + + /** + * Delete multiple instances. + */ + destroy(where?: any, options?: DestroyOptions): Promise; + + /** + * Update multiple instances that match the where options. + * + * @param attrValueHash A hash of fields to change and their new values + * @param where Options to describe the scope of the search. Note that these options are not wrapped in a + * { where: ... } is in find / findAll calls etc. This is probably due to change in 2.0. + */ + update(attrValueHash: TPojo, where: any, options?: UpdateOptions): Promise; + + /** + * Run a describe query on the table. The result will be return to the listener as a hash of attributes and their + * types. + */ + describe(): PromiseT; + + /** + * A proxy to the node-sql query builder, which allows you to build your query through a chain of method calls. + * The returned instance already has all the fields property populated with the field of the model. + */ + dataset(): any; + } + + interface Instance { + /** + * Returns true if this instance has not yet been persisted to the database. + */ + isNewRecord: boolean; + + /** + * Returns the Model the instance was created from. + */ + Model: Model; + + /** + * A reference to the sequelize instance. + */ + sequelize: Sequelize; + + /** + * If timestamps and paranoid are enabled, returns whether the deletedAt timestamp of this instance is set. + * Otherwise, always returns false. + */ + isDeleted: boolean; + + /** + * Get the values of this Instance. Proxies to this.get. + */ + values: TPojo; + + /** + * A getter for this.changed(). Returns true if any keys have changed. + */ + isDirty: boolean; + + /** + * Get the values of the primary keys of this instance. + */ + primaryKeyValues: TPojo; + + /** + * Get the value of the underlying data value. + * + * @param key Field to retrieve. + */ + getDataValue(key: string): any; + + /** + * Update the underlying data value. + * + * @param key Field to set. + * @param value Value to set. + */ + setDataValue(key: string, value: any): void; + + /** + * Retrieves the value for the key when specified. If no key is given, returns all values of the instance, also + * invoking virtual getters. + */ + get(key?: string): any; + + /** + * Set is used to update values on the instance (the sequelize representation of the instance that is, remember + * that nothing will be persisted before you actually call save). + */ + set(key: string, value: any, options?: SetOptions): void; + + /** + * If changed is called with a string it will return a boolean indicating whether the value of that key in + * dataValues is different from the value in _previousDataValues. If changed is called without an argument, it will + * return an array of keys that have changed. + */ + changed(key: string): any; + + /** + * If changed is called with a string it will return a boolean indicating whether the value of that key in + * dataValues is different from the value in _previousDataValues. If changed is called without an argument, it will + * return an array of keys that have changed. + */ + changed(): Array; + + /** + * Returns the previous value for key from _previousDataValues. + */ + previous(key: string): any; + + /** + * Validate this instance, and if the validation passes, persist it to the database. + */ + save(fields?: Array, options?: SaveOptions): PromiseT; + + /** + * Refresh the current instance in-place, i.e. update the object with current data from the DB and return the same + * object. This is different from doing a find(Instance.id), because that would create and return a new instance. + * With this method, all references to the Instance are updated with the new data and no new objects are created. + */ + reload(options?: FindOptions): PromiseT; + + /** + * Validate the attribute of this instance according to validation rules set in the model definition. + */ + validate(options?: ValidateOptions): PromiseT; + + /** + * This is the same as calling setAttributes, then calling save. + */ + updateAttributes(updates: TPojo, options: SaveOptions): PromiseT; + + /** + * Destroy the row corresponding to this instance. Depending on your setting for paranoid, the row will either be + * completely deleted, or have its deletedAt timestamp set to the current time. + * + * @param options Allows caller to specify if delete should be forced. + */ + destroy(options?: DestroyInstanceOptions): Promise; + + /** + * Increment the value of one or more columns. This is done in the database, which means it does not use the + * values currently stored on the Instance. + * + * @param fields If a string is provided, that column is incremented by the value of by given in options. If an + * array is provided, the same is true for each column. If and object is provided, each column is + * incremented by the value given. + * @param options Increment options. + */ + increment(fields: any, options?: IncrementOptions): Promise; + + /** + * Decrement the value of one or more columns. This is done in the database, which means it does not use the + * values currently stored on the Instance. + * + * @param fields If a string is provided, that column is decremented by the value of by given in options. If an + * array is provided, the same is true for each column. If and object is provided, each column is + * decremented by the value given. + * @param options Decrement options. + */ + decrement(fields: any, options?: IncrementOptions): Promise; + + /** + * Check whether all values of this and other Instance are the same. + */ + equal(other: TInstance): boolean; + + /** + * Check if this is eqaul to one of others by calling equals. + * + * @param others Other instances to compare to. + */ + equalsOneOf(others: Array): boolean; + + /** + * Convert the instance to a JSON representation. Proxies to calling get with no keys. This means get all values + * gotten from the DB, and apply all custom getters. + */ + toJSON(): TPojo; + } + + interface Transaction extends TransactionStatic { + /** + * Commit the transaction. + */ + commit(): Transaction; + + /** + * Rollback (abort) the transaction. + */ + rollback(): Transaction; + } + + interface TransactionStatic { + /** + * The possible isolation levels to use when starting a transaction + */ + ISOLATION_LEVELS: TransactionIsolationLevels; + + /** + * Possible options for row locking. Used in conjuction with find calls. + */ + LOCK: TransactionLocks; + } + + interface TransactionIsolationLevels { + READ_UNCOMMITTED: string;// "READ UNCOMMITTED" + READ_COMMITTED: string; // "READ COMMITTED" + REPEATABLE_READ: string; // "REPEATABLE READ" + SERIALIZABLE: string; // "SERIALIZABLE" + } + + interface TransactionLocks { + UPDATE: string; // UPDATE + SHARE: string; // SHARE + } + + interface Hooks { + + /** + * Add a named hook to the model. + * + * @param hooktype + */ + addHook(hooktype: string, name: string, fn: (...args: Array) => void): boolean; + + /** + * Add a hook to the model. + * + * @param hooktype + */ + addHook(hooktype: string, fn: (...args: Array) => void): boolean; + + /** + * A named hook that is run before validation. + */ + beforeValidate(name: string, validator: (dao: T, callback: (err?: Error) => void) => void): void; + + /** + * A hook that is run before validation. + */ + beforeValidate(validator: (dao: T, callback: (err?: Error) => void) => void): void; + + /** + * A named hook that is run before validation. + */ + afterValidate(name: string, validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A hook that is run before validation. + */ + afterValidate(validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A named hook that is run before creating a single instance. + */ + beforeCreate(name: string, validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A hook that is run before creating a single instance. + */ + beforeCreate(validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A named hook that is run after creating a single instance. + */ + afterCreate(name: string, validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A hook that is run after creating a single instance. + */ + afterCreate(validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A named hook that is run before destroying a single instance. + */ + beforeDestroy(name: string, validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A hook that is run before destroying a single instance. + */ + beforeDestroy(validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A named hook that is run after destroying a single instance. + */ + afterDestroy(name: string, validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A hook that is run after destroying a single instance. + */ + afterDestroy(validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A named hook that is run before updating a single instance. + */ + beforeUpdate(name: string, validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A hook that is run before updating a single instance. + */ + beforeUpdate(validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A named hook that is run after updating a single instance. + */ + afterUpdate(name: string, validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A hook that is run after updating a single instance. + */ + afterUpdate(validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A named hook that is run before creating instances in bulk. + */ + beforeBulkCreate(name: string, validator: (daos: Array, fields: Array, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A hook that is run before creating instances in bulk. + */ + beforeBulkCreate(validator: (daos: Array, fields: Array, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A named hook that is run after creating instances in bulk. + */ + afterBulkCreate(name: string, validator: (daos: Array, fields: Array, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A hook that is run after creating instances in bulk. + */ + afterBulkCreate(validator: (daos: Array, fields: Array, callback: (err?: Error, dao?: T) => void) => void): void; + + /** + * A named hook that is run before destroying instances in bulk. + */ + beforeBulkDestroy(name: string, validator: (where: any, callback: (err?: Error, where?: any) => void) => void): void; + + /** + * A hook that is run before destroying instances in bulk. + */ + beforeBulkDestroy(validator: (where: any, callback: (err?: Error, where?: any) => void) => void): void; + + /** + * A named hook that is run after destroying instances in bulk. + */ + afterBulkDestroy(name: string, validator: (where: any, callback: (err?: Error, where?: any) => void) => void): void; + + /** + * A hook that is run after destroying instances in bulk. + */ + afterBulkDestroy(validator: (where: any, callback: (err?: Error, where?: any) => void) => void): void; + + /** + * A named hook that is run before updating instances in bulk. + */ + beforeBulkUpdate(name: string, validator: (instances: Array, where: any, callback: (err?: Error, instances?: Array, where?: any) => void) => void): void; + + /** + * A hook that is run before updating instances in bulk. + */ + beforeBulkUpdate(validator: (instances: Array, where: any, callback: (err?: Error, instances?: Array, where?: any) => void) => void): void; + + /** + * A named hook that is run after updating instances in bulk. + */ + afterBulkUpdate(name: string, validator: (instances: Array, where: any, callback: (err?: Error, instances?: Array, where?: any) => void) => void): void; + + /** + * A hook that is run after updating instances in bulk. + */ + afterBulkUpdate(validator: (instances: Array, where: any, callback: (err?: Error, instances?: Array, where?: any) => void) => void): void; + } + + interface Associations { + /** + * Creates an association between this (the source) and the provided target. The foreign key is added on the target. + * + * @param target + * @param options + */ + hasOne(target: Model, options?: AssociationOptions): void; + + /** + * Creates an association between this (the source) and the provided target. The foreign key is added on the source. + * + * @param target + * @param options + */ + belongsTo(target: Model, options?: AssociationOptions): void; + + /** + * Creates an association to connect sources with multiple targets. Furthermore the targets can also have connections to multiple sources. + * + * @param target + * @param options + */ + belongsToMany(target: Model, options?: AssociationOptions): void; + + /** + * Create an association that is either 1:m or n:m. + * + * @param target + * @param options + */ + hasMany(target: Model, options?: AssociationOptions): void; + } + + /** + * Extension of external project that doesn't have definitions. + * + * See https://github.com/chriso/validator.js and https://github.com/sequelize/sequelize/blob/master/lib/instance-validator.js + */ + interface Validator { + + } + + /** + * Custom class defined, but no extra methods or functionality even. + */ + interface ValidationError extends Error { + + } + + interface QueryChainer { + /** + * Add an query to the chainer. This can be done in two ways - either by invoking the method like you would + * normally, and then adding the returned emitter to the chainer, or by passing the class that you want to call a + * method on, the name of the method, and its parameters to the chainer. The second form might sound a bit + * cumbersome, but it is used when you want to run queries in serial. + * + * @param emitterOrKlass + * @param method + * @param params + * @param options + */ + add(emitterOrKlass: any, method?: string, params?: any, options?: any): QueryChainer; + + /** + * Run the query chainer. In reality, this means, wait for all the added emitters to finish, since the queries + * began executing as soon as you invoked their methods. + */ + run(): EventEmitter; + + /** + * Run the chainer serially, so that each query waits for the previous one to finish before it starts. + * + * @param options @see QueryChainerRunSeriallyOptions + */ + runSerially(options?: QueryChainerRunSeriallyOptions): EventEmitter; + } + + interface QueryInterface { + + /** + * Returns the dialect-specific sql generator. + */ + QueryGenerator: QueryGenerator; + + /** + * Queries the schema (table list). + * + * @param schema The schema to query. Applies only to Postgres. + */ + createSchema(schema?: string): EventEmitter; + + /** + * Drops the specified schema (table). + * + * @param schema The name of the table to drop. + */ + dropSchema(schema: string): EventEmitter; + + /** + * Drops all tables. + */ + dropAllSchemas(): EventEmitter; + + /** + * Queries all table names in the database. + * + * @param options + */ + showAllSchemas(options?: QueryOptions): EventEmitter; + + /** + * Creates a table with specified attributes. + * @param tableName Name of table to create + * @param attributes Hash of attributes, key is attribute name, value is data type + * @param options Query options. + * + * @return The return type will be a Promise when dialect is Postgres and an EventEmitter for MySQL and SQLite. + */ + createTable(tableName: string, attributes: any, options?: QueryOptions): any; + + /** + * Drops the specified table. + * + * @param tableName Table name. + * @param options Query options, particularly "force". + */ + dropTable(tableName: string, options?: QueryOptions): EventEmitter; + dropAllTables(options?: QueryOptions): EventEmitter; + dropAllEnums(options?: QueryOptions): EventEmitter; + renameTable(before: string, after: string): EventEmitter; + showAllTables(options?: QueryOptions): EventEmitter; + describeTable(tableName: string, options?: QueryOptions): EventEmitter; + addColumn(tableName: string, attributeName: any, dataTypeOrOptions?: any): EventEmitter; + removeColumn(tableName: string, attributeName: string): EventEmitter; + changeColumn(tableName: string, attributeName: string, dataTypeOrOptions: any): EventEmitter; + renameColumn(tableName: string, attrNameBefore: string, attrNameAfter: string): EventEmitter; + addIndex(tableName: string, attributes: Array, options?: QueryOptions): EventEmitter; + showIndex(tableName: string, options?: QueryOptions): EventEmitter; + getForeignKeysForTables(tableNames: Array): EventEmitter; + removeIndex(tableName: string, attributes: Array): EventEmitter; + removeIndex(tableName: string, indexName: string): EventEmitter; + insert(dao: TModel, tableName: string, values: any, options?: QueryOptions): EventEmitter; + /** + * Inserts several records into the specified table. + * @param tableName Table to insert into. + * @param records Array of key/value pairs to insert as records. + * @param options Query options + * @param attributes For Postgres only, used to identify if an attribute is auto-increment and thus handled specially. + */ + bulkInsert(tableName: string, records: Array, options?: QueryOptions, attributes?: any): EventEmitter; + + update(dao: TModel, tableName: string, values: Array, where: any, options?: QueryOptions): EventEmitter; + bulkUpdate(tableName: string, values: Array, where: any, options?: QueryOptions, attributes?: any): EventEmitter; + delete(dao: TModel, tableName: string, where: any, options?: QueryOptions): EventEmitter; + bulkDelete(tableName: string, where: any, options?: QueryOptions): EventEmitter; + bulkDelete(tableName: string, where: any, options: QueryOptions, model: TModel): EventEmitter; + select(factory: TModel, tableName: string, scope?: any, queryOptions?: QueryOptions): EventEmitter; + increment(dao: TModel, tableName: string, values: Array, where: any, options?: QueryOptions): EventEmitter; + rawSelect(tableName: string, options: QueryOptions, attributeSelector: string, model: TModel): EventEmitter; + /** + * Postgres only. Creates a trigger on specified table to call the specified function with supplied parameters. + * + * @param tableName + * @param triggerName + * @param timingType + * @param fireOnArray + * @param functionName + * @param functionParams + * @param optionsArray + */ + createTrigger(tableName: string, triggerName: string, timingType: string, fireOnArray: Array, functionName: string, functionParams: Array, optionsArray: Array): EventEmitter; + /** + * Postgres only. Drops the specified trigger. + * + * @param tableName + * @param triggerName + */ + dropTrigger(tableName: string, triggerName: string): EventEmitter; + renameTrigger(tableName: string, oldTriggerName: string, newTriggerName: string): EventEmitter; + createFunction(functionName: string, params: Array, returnType: string, language: string, body: string, options?: QueryOptions): EventEmitter; + dropFunction(functionName: string, params: Array): EventEmitter; + renameFunction(oldFunctionName: string, params: Array, newFunctionName: string): EventEmitter; + /** + * Escape an identifier (e.g. a table or attribute name). If force is true, + * the identifier will be quoted even if the `quoteIdentifiers` option is + * false. + */ + quoteIdentifier(identifier: string, force: boolean): EventEmitter; + quoteTable(tableName: string): EventEmitter; + quoteIdentifiers(identifiers: string, force: boolean): EventEmitter; + escape(value: string): EventEmitter; + setAutocommit(transaction: Transaction, value: boolean): EventEmitter; + setIsolationLevel(transaction: Transaction, value: string): EventEmitter; + startTransaction(transaction: Transaction, options?: QueryOptions): EventEmitter; + commitTransaction(transaction: Transaction, options?: QueryOptions): EventEmitter; + rollbackTransaction(transaction: Transaction, options?: QueryOptions): EventEmitter; + } + + interface QueryGenerator { + createSchema(schemaName: string): string; + dropSchema(schemaName: string): string; + showSchemasQuery(): string; + addSchema(param: Model): Schema; + createTableQuery(tableName: string, attributes: Array, options?: CreateTableQueryOptions): string; + describeTableQuery(tableName: string, schema: string, schemaDelimiter: string): string; + dropTableQuery(tableName: string, options?: { cascade: string }): string; + renameTableQuery(before: string, after: string): string; + showTablesQuery(): string; + addColumnQuery(tableName: string, attributes: any): string; + removeColumnQuery(tableName: string, attributeName: string): string; + changeColumnQuery(tableName: string, attributes: any): string; + renameColumnQuery(tableName: string, attrNameBefore: string, attrNameAfter: string): string; + insertQuery(table: string, valueHash: any, modelAttributes: any): string; + bulkInsertQuery(tableName: string, attrValueHashes: any): string; + updateQuery(tableName: string, attrValueHash: any, where: any, options: InsertOptions, attributes: any): string; + deleteQuery(tableName: string, where: any, options: DestroyOptions): string; + deleteQuery(tableName: string, where: any, options: DestroyOptions, model: Model): string; + /** + * Creates a query to increment a value. Note "options" here is an additional hash of values to update. + * + * @param tableName + * @param attrValueHash + * @param where + * @param options + */ + incrementQuery(tableName: string, attrValueHash: any, where: any, options?: any): string; + addIndexQuery(tableName: string, attributes: Array, options?: IndexOptions): string; + /** + * Return indices for a table. Not options may be passed but is not used, so can be anything. + * @param tableName + * @param options + */ + showIndexQuery(tableName: string, options?: any): string; // options is actually not used + removeIndexQuery(tableName: string, indexNameOrAttributes: string): string; + removeIndexQuery(tableName: string, indexNameOrAttributes: Array): string; + attributesToSQL(attributes: Array): string; + findAutoIncrementField(factory: Model): Array; + quoteTable(param: any, as: boolean): string; + quote(obj: any, parent: any, force: boolean): string; + createTrigger(tableName: string, triggerName: string, timingType: string, fireOnArray: TriggerOptions, functionName: string, functionParams: Array): string; + dropTrigger(tableName: string, triggerName: string): string; + renameTrigger(tableName: string, oldTriggerName: string, newTriggerName: string): string; + createFunction(functionName: string, params: Array, returnType: string, language: string, body: string, options?: Array): string; + dropFunction(functionName: string, params: Array): string; + renameFunction(oldFunctionName: string, params: Array, newFunctionName: string): string; + quoteIdentifier(identifier: string, force?: boolean): string; + quoteIdentifiers(identifiers: string, force?: boolean): string; + /** + * Not documented, and reading through the code, I'm not sure what all the options available are for value/field. + * + * @param value + * @param field + */ + escape(value: any, field: any): string; + getForeignKeysQuery(tableName: string, schemaName: string): string; + dropForeignKeyQuery(tableName: string, foreignKey: string): string; + selectQuery(tableName: string, options: SelectOptions, model?: Model): string; + selectQuery(tableName: Array, options: SelectOptions, model?: Model): string; + selectQuery(tableName: Array>, options: SelectOptions, model?: Model): string; + setAutocommitQuery(value: boolean): string; + setIsolationLevelQuery(value: string): string; + /** + * Returns start transaction query. Options is not used. + * @param options + */ + startTransactionQuery(options?: any): string; + /** + * Returns start transaction query. Options is not used. + * @param options + */ + commitTransactionQuery(options?: any): string; + /** + * Returns start transaction query. Options is not used. + * @param options + */ + rollbackTransactionQuery(options?: any): string; + addLimitAndOffset(options: SelectOptions, query?: string): string; + getWhereConditions(smth: any, tableName: string, factory: Model, options?: any, prepend?: boolean): string; + prependTableNameToHash(tableName: string, hash?: any): string; + findAssociation(attribute: string, dao: Model): string; + getAssociationFilterDAO(filterStr: string, dao: Model): string; + isAssociationFilter(filterStr: string, dao: Model, options?: any): string; + getAssociationFilterColumn(filterStr: string, dao: Model, options?: { include: boolean }): string; + getConditionalJoins(options: { where?: any }, originalDao: Model): string; + arrayValue(value: Array, key: string, _key: string, factory?: any, logicResult?: any): string; + hashToWhereConditions(hash: any, dao: Model, options?: HashToWhereConditionsOption): string; + booleanValue(value: boolean): string; + } + + interface Schema { + tableName: string; + table: string; + name: string; + schema: string; + delimiter: string; + } + + interface QueryTypes { + SELECT: string; + BULKUPDATE: string; + BULKDELETE: string; + } + + interface ModelManager { + daos: Array>; + sequelize: Sequelize; + addDAO(dao: Model): Model; + removeDAO(dao: Model): void; + getDAO(daoName: string, options?: ModelMangerGetDaoOptions): Model; + all: Array>; + + /** + * Iterate over DAOs in an order suitable for e.g. creating tables. Will + * take foreign key constraints into account so that dependencies are visited + * before dependents. + */ + forEachDAO(iterator: (dao: Model, name: string) => void, options?: ModelManagerForEachDaoOptions): void; + } + + interface TransactionManager { + sequelize: Sequelize; + connectorManagers: any; + getConnectorManager(uuid?: string): ConnectorManager; + releaseConnectionManager(uuid?: string): void; + + /** + * Execute a query on the DB, with the possibility to bypass all the sequelize goodness. + * + * @param sql SQL statement to execute. + * + * @param callee If callee is provided, the selected data will be used to build an instance of the DAO represented + * by the factory. Equivalent to calling Model.build with the values provided by the query. + * + * @param options Query options. + * + */ + query(sql: string, callee?: Model, options?: QueryOptions): EventEmitter; + + query(sql: string, callee?: Model, options?: QueryOptions): EventEmitter; + } + + interface ConnectorManager { + + /** + * Execute a query on the DB, with the possibility to bypass all the sequelize goodness. + * + * @param sql SQL statement to execute. + * + * @param callee If callee is provided, the selected data will be used to build an instance of the DAO represented + * by the factory. Equivalent to calling Model.build with the values provided by the query. + * + * @param options Query options. + * + */ + query(sql: string, callee?: Model, options?: QueryOptions): EventEmitter; + + afterTransactionSetup(callback: () => void): void; + connect(): void; + disconnect(): void; + reconnect(): void; + cleanup(): void; + } + + interface Migrator { + queryInterface: QueryInterface; + migrate(options?: MigratorOptions): EventEmitter; + getUndoneMigrations(callback: (err: Error, result: Array) => void): void; + findOrCreateMetaDAO(syncOptions?: SyncOptions): EventEmitter; + exec(filename: string, options?: MigratorExecOptions): EventEmitter; + getLastMigrationFromDatabase(): EventEmitter; + getLastMigrationIdFromDatabase(): EventEmitter; + getFormattedDateString(s: string): string; + stringToDate(s: string): Date; + saveSuccessfulMigration(from: Migration, to: Migration, callback: (metaData: MetaInstance) => void): void; + deleteUndoneMigration(from: Migration, to: Migration, callback: () => void): void; + execute(options?: MigrationExecuteOptions): EventEmitter; + isBefore(date: Date, options?: MigrationCompareOptions): boolean; + isAfter(date: Date, options?: MigrationCompareOptions): boolean; + + } + + interface Migration extends QueryInterface { + migrator: Migrator; + path: string; + filename: string; + migrationId: number; + date: Date; + queryInterface: QueryInterface; + migration: (err: Error, migration: Migration, dataTypes: any, callback: (err: Error) => void) => void; + + } + + interface EventEmitter extends EventEmitterT, NodeJS.EventEmitter { } + + interface EventEmitterT extends NodeJS.EventEmitter { + /** + * Create a new emitter instance. + * + * @param handler + */ + new (handler: (emitter: EventEmitterT) => void): EventEmitterT; + + /** + * Run the function that was passed when the emitter was instantiated. + */ + run(): EventEmitterT; + + /** + * Listen for success events. + * + * @param onSuccess + */ + success(onSuccess: (result: R) => void): EventEmitterT; + + /** + * Alias for success(handler). Listen for success events. + * + * @param onSuccess + */ + ok(onSuccess: (result: R) => void): EventEmitterT; + + /** + * Listen for error events. + * + * @param onError + */ + error(onError: (err: Error) => void): EventEmitterT; + + /** + * Alias for error(handler). Listen for error events. + * + * @param onError + */ + fail(onError: (err: Error) => void): EventEmitterT; + + /** + * Alias for error(handler). Listen for error events. + * + * @param onError + */ + failure(onError: (err: Error) => void): EventEmitterT; + + /** + * Listen for both success and error events. + * + * @param onDone + */ + done(onDone: (err: Error, result: R) => void): EventEmitterT; + + /** + * Alias for done(handler). Listen for both success and error events. + * + * @param onDone + */ + complete(onDone: (err: Error, result: R) => void): EventEmitterT; + + /** + * Attach a function that is called every time the function that created this emitter executes a query. + * + * @param onSQL + */ + sql(onSQL: (sql: string) => void): EventEmitterT; + + /** + * Proxy every event of this event emitter to another one. + * + * @param emitter The event emitter that should receive the events. + * @param options Contains an array of the events to proxy. Defaults to sql, error and success + */ + proxy(emitter: EventEmitterT, options?: ProxyOptions): EventEmitterT; + + + } + + interface Options { + /** + * The dialect you of the database you are connecting to. One of mysql, postgres, sqlite and mariadb. + * Default is mysql. + */ + dialect?: string; + + /** + * If specified, load the dialect library from this path. For example, if you want to use pg.js instead of pg when + * connecting to a pg database, you should specify 'pg.js' here + */ + dialectModulePath?: string; + + /** + * The host of the relational database. Default 'localhost'. + */ + host?: string; + + /** + * Integer The port of the relational database. + */ + port?: number; + + /** + * The protocol of the relational database. Default 'tcp'. + */ + protocol?: string; + + /** + * Default options for model definitions. See sequelize.define for options. + */ + define?: DefineOptions; + + /** + * Default options for sequelize.query + */ + query?: QueryOptions; + + /** + * Default options for sequelize.sync + */ + sync?: SyncOptions; + + /** + * The timezone used when converting a date from the database into a javascript date. The timezone is also used to + * SET TIMEZONE when connecting to the server, to ensure that the result of NOW, CURRENT_TIMESTAMP and other time + * related functions have in the right timezone. For best cross platform performance use the format +/-HH:MM. + * Default '+00:00'. + */ + timezone?: string; + + /** + * Logging options. Function used to log. Default is console.log. Signature is (message:string) => void. + * + * Set to "false" to disable logging. + */ + logging?: any; + + /** logging=console.log] Function A function that gets executed everytime Sequelize would log something. + * A flag that defines if null values should be passed to SQL queries or not. + */ + omitNull?: boolean; + + /** + * Boolean Queue queries, so that only maxConcurrentQueries number of queries are executing at once. If false, all + * queries will be executed immediately. + */ + queue?: boolean; + + /** + * The maximum number of queries that should be executed at once if queue is true. + */ + maxConcurrentQueries?: number; + + /** + * A flag that defines if native library shall be used or not. Currently only has an effect for postgres + */ + native?: boolean; + + /** + * Use read / write replication. To enable replication, pass an object, with two properties, read and write. Write + * should be an object (a single server for handling writes), and read an array of object (several servers to + * handle reads). Each read/write server can have the following properties?: host, port, username, password, database + */ + replication?: ReplicationOptions; + + /** + * Connection pool options. + * + */ + pool?: PoolOptions; + + /** + * Set to false to make table names and attributes case-insensitive on Postgres and skip double quoting of them. + * Default true. + */ + quoteIdentifiers?: boolean; + + /** + * Language. Default "en". + */ + language?: string; + } + + interface PoolOptions { + maxConnections?: number; + + minConnections?: number; + + /** + * The maximum time, in milliseconds, that a connection can be idle before being released. + */ + maxIdleTime?: number; + + /** + * A function that validates a connection. Called with client. The default function checks that client is an + * object, and that its state is not disconnected. + * + * Note, this is not documented, and after reading code I'm not sure what client's type is. + */ + validateConnection?: (client?: any) => boolean; + } + + interface AttributeOptions { + /** + * A string or a data type + */ + type?: string; + + /** + * If false, the column will have a NOT NULL constraint, and a not null validation will be run before an instance + * is saved. + */ + allowNull?: boolean; + + /** + * A literal default value, a javascript function, or an SQL function (see sequelize.fn) + */ + defaultValue?: any; + + /** + * If true, the column will get a unique constraint. If a string is provided, the column will be part of a + * composite unique index. If multiple columns have the same string, they will be part of the same unique index. + */ + unique?: any; + + primaryKey?: boolean; + + /** + * If set, sequelize will map the attribute name to a different name in the database. + */ + field?: string; + + autoIncrement?: boolean; + + comment?: string; + + /** + * If this column references another table, provide it here as a Model, or a string. + */ + references?: any; + + /** + * The column of the foreign table that this column references. Default 'id'. + */ + referencesKey?: string; + + /** + * What should happen when the referenced key is updated. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or + * NO ACTION. + */ + onUpdate?: string; + + /** + * What should happen when the referenced key is deleted. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or + * NO ACTION. + */ + onDelete?: string; + + /** + * Provide a custom getter for this column. Use this.getDataValue(String) to manipulate the underlying values. + */ + get?: () => any; + + /** + * Provide a custom setter for this column. Use this.setDataValue(String, Value) to manipulate the underlying values. + */ + set?: (value?: any) => void; + + /** + * An object of validations to execute for this column every time the model is saved. Can be either the name of a + * validation provided by validator.js, a validation function provided by extending validator.js (see the + * DAOValidator property for more details), or a custom validation function. Custom validation functions are called + * with the value of the field, and can possibly take a second callback argument, to signal that they are + * asynchronous. If the validator is sync, it should throw in the case of a failed validation, it it is async, + * the callback should be called with the error text. + */ + validate?: any; + } + + interface ForeignKeyAttributeOptions extends AttributeOptions { + /** + * The name of the foreign key in the target table. Defaults to the name of source + primary key of source. + */ + fieldName: string; + } + + interface DefineOptions { + /** + * Define the default search scope to use for this model. Scopes have the same form as the options passed to + * find / findAll. + */ + defaultScope?: FindOptions; + + /** + * More scopes, defined in the same way as defaultScope above. See Model.scope for more information about how + * scopes are defined, and what you can do with them + */ + scopes?: any; + + /** + * Don't persits null values. This means that all columns with null values will not be saved. + */ + omitNull?: boolean; + + /** + * Adds createdAt and updatedAt timestamps to the model. Default true. + */ + timestamps?: boolean; + + /** + * Calling destroy will not delete the model, but instead set a deletedAt timestamp if this is true. Needs + * timestamps=true to work. Default false. + */ + paranoid?: boolean; + + /** + * Converts all camelCased columns to underscored if true. Default false. + */ + underscored?: boolean; + + /** + * Converts camelCased model names to underscored tablenames if true. Default false. + */ + underscoredAll?: boolean; + + /** + * If freezeTableName is true, sequelize will not try to alter the DAO name to get the table name. Otherwise, the + * dao name will be pluralized. Default false. + */ + freezeTableName?: boolean; + + /** + * Override the name of the createdAt column if a string is provided, or disable it if false. Timestamps must be true. + */ + createdAt?: any; + + /** + * Override the name of the updatedAt column if a string is provided, or disable it if false. Timestamps must be true. + */ + updatedAt?: any; + + /** + * Override the name of the deletedAt column if a string is provided, or disable it if false. Timestamps must be true. + */ + deletedAt?: any; + + /** + * Defaults to pluralized DAO name, unless freezeTableName is true, in which case it uses DAO name verbatim. + */ + tableName?: string; + + /** + * Provide getter functions that work like those defined per column. If you provide a getter method with the same + * name as a column, it will be used to access the value of that column. If you provide a name that does not match + * a column, this function will act as a virtual getter, that can fetch multiple other values. + */ + getterMethods?: any; + + /** + * Provide setter functions that work like those defined per column. If you provide a setter method with the same + * name as a column, it will be used to update the value of that column. If you provide a name that does not match + * a column, this function will act as a virtual setter, that can act on and set other values, but will not be + * persisted + */ + setterMethods?: any; + + /** + * Provide functions that are added to each instance (DAO). + */ + instanceMethods?: any; + + /** + * Provide functions that are added to the model (Model). + */ + classMethods?: any; + + /** + * Default 'public'. + */ + schema?: string; + schemaDelimiter?: string; + engine?: string; + charset?: string; + comment?: string; + collate?: string; + whereCollection?: any; + language?: string; + + /** + * An object of hook function that are called before and after certain lifecycle events. The possible hooks are?: + * beforeValidate, afterValidate, beforeBulkCreate, beforeBulkDestroy, beforeBulkUpdate, beforeCreate, + * beforeDestroy, beforeUpdate, afterCreate, afterDestroy, afterUpdate, afterBulkCreate, afterBulkDestory and + * afterBulkUpdate. See Hooks for more information about hook functions and their signatures. Each property can + * either be a function, or an array of functions. + */ + hooks?: Hooks; + + /** + * An object of model wide validations. Validations have access to all model values via this. If the validator + * function takes an argument, it is assumed to be async, and is called with a callback that accepts an optional + * error. + */ + validate?: any; + + /** + * + */ + indexes?: Array; + } + + interface DefineIndexOptions { + /** + * The name of the index. Defaults to model name + _ + fields concatenated. + */ + name?: string; + + /** + * Index type. Only used by mysql. One of UNIQUE, FULLTEXT and SPATIAL. + */ + type: string; + + /** + * The method to create the index by (USING statement in SQL). BTREE and HASH are supported by mysql and postgres, + * and postgres additionally supports GIST and GIN. + */ + method: string; + + /** + * Should the index by unique? Can also be triggered by setting type to UNIQUE. Default false (unless type = "UNIQUE", + * then true). + */ + unique?: boolean; + + /** + * PostgreSQL will build the index without taking any write locks. Postgres only. Default false. + */ + concurrently?: boolean; + + /** + * An array of the fields to index. Each field can either be a string containing the name of the field, or an object + * with the following attributes: attribute (field name), length (create a prefix index of length chars), order (the + * direction the column should be sorted in), collate (the collation (sort order) for the column) + */ + fields: Array; + } + + interface QueryOptions { + /** + * If true, sequelize will not try to format the results of the query, or build an instance of a model from the + * result. + */ + raw?: boolean; + + /** + * The transaction that the query should be executed under. + */ + transaction?: Transaction; + + /** + * The type of query you are executing. The query type affects how results are formatted before they are passed + * back. If no type is provided sequelize will try to guess the right type based on the sql, and fall back to + * SELECT. The type is a string, but Sequelize.QueryTypes is provided is convenience shortcuts. Current options + * are SELECT, BULKUPDATE and BULKDELETE. + * + * Default is SELECT. + */ + type?: string; + + /** + * Lock the selected rows in either share or update mode. Possible options are transaction.LOCK.UPDATE and + * transaction.LOCK.SHARE. See transaction.LOCK for an example. + */ + lock?: string; + + /** + * For aggregate function calls, the type of the result. If field is a field in this Model, the default will be the + * type of that field, otherwise defaults to float. + */ + dataType?: any; + + /** + * A function that logs sql queries, or false for no logging. + */ + logging?: any; + + /** + * If plain is true, then sequelize will only return the first record of the result set. In case of false it will + * all records. + */ + plain?: boolean; + } + + interface SyncOptions { + /** + * If force is true, each DAO will do DROP TABLE IF EXISTS ..., before it tries to create its own table. + * Default false. + */ + force?: boolean; + + /** + * A function that logs sql queries, or false for no logging. + */ + logging?: any; + + /** + * The schema that the tables should be created in. This can be overriden for each table in sequelize.define. + * Default 'public'. + */ + schema?: string; + } + + interface ReplicationOptions { + read?: Array; + write?: Server; + } + + interface Server { + host?: string; + port?: number; + database?: string; + username?: string; + password?: string; + } + + interface DropOptions { + /** + * Also drop all objects depending on this table, such as views. Only works in postgres. + * + * Default false. + */ + cascade?: boolean; + } + + interface SchemaOptions { + /** + * The character(s) that separates the schema name from the table name. Default '.'. + */ + schemaDelimiter?: string; + } + + interface FindOptions { + /** + * A hash of attributes to describe your search. + */ + where?: any; + + /** + * A list of the attributes that you want to select. To rename an attribute, you can pass an array, with two + * elements - the first is the name of the attribute in the DB (or some kind of expression such as + * Sequelize.literal, Sequelize.fn and so on), and the second is the name you want the attribute to have in the + * returned instance + */ + attributes?: Array; + + /** + * A list of associations to eagerly load. Supported is either { include?: [ Model1, Model2, ...] } or { include?: + * [ { model?: Model1, as?: 'Alias' } ] }. If your association are set up with an as (eg. X.hasMany(Y, { as?: 'Z }, + * you need to specify Z in the as attribute when eager loading Y). When using the object form, you can also + * specify attributes to specify what columns to load, where to limit the relations, and include to load further + * nested relations + */ + include?: any; + + /** + * Specifies an ordering. If a string is provided, it will be esacped. Using an array, you can provide several + * columns / functions to order by. Each element can be further wrapped in a two-element array. The first element + * is the column / function to order by, the second is the direction. For example?: order?: [['name', 'DESC']]. In + * this way the column will be escaped, but the direction will not. + */ + order?: any; + + limit?: number; + + offset?: number; + } + + interface BuildOptions { + /** + * If set to true, values will ignore field and virtual setters. Default false. + */ + raw?: boolean; + + /** + * Default true. + */ + isNewRecord?: boolean; + + /** + * Default true. + */ + isDirty?: boolean; + + /** + * an array of include options - Used to build prefetched/included model instances. See set. + */ + include?: Array; + } + + interface CopyOptions extends BuildOptions { + /** + * If set, only columns matching those in fields will be saved. + */ + fields?: Array; + + /** + * + */ + transaction?: Transaction; + } + + interface FindOrCreateOptions extends FindOptions, QueryOptions { + + } + + interface BulkCreateOptions { + /** + * Fields to insert (defaults to all fields). + */ + fields?: Array; + + /** + * Should each row be subject to validation before it is inserted. The whole insert will fail if one row fails + * validation. Default false. + */ + validate?: boolean; + + /** + * Run before / after create hooks for each individual Instance? BulkCreate hooks will still be run. Default false; + */ + hooks?: boolean; + + /** + * Ignore duplicate values for primary keys? (not supported by postgres). Default false. + */ + ignoreDuplicates?: boolean; + } + + interface DestroyOptions { + /** + * If set to true, destroy will find all records within the where parameter and will execute before-/ after + * bulkDestroy hooks on each row. + */ + hooks?: boolean; + + /** + * How many rows to delete + */ + limit?: number; + + /** + * If set to true, dialects that support it will use TRUNCATE instead of DELETE FROM. If a table is truncated the + * where and limit options are ignored. + */ + truncate?: boolean; + } + + interface DestroyInstanceOptions { + /** + * If set to true, paranoid models will actually be deleted. + */ + force: boolean; + } + + interface InsertOptions { + limit?: number; + returning?: string; + allowNull?: string; + } + + interface UpdateOptions { + /** + * Should each row be subject to validation before it is inserted. The whole insert will fail if one row fails + * validation. Default true. + */ + validate?: boolean; + + /** + * Run before / after bulkUpdate hooks? Default false. + */ + hooks?: boolean; + + /** + * How many rows to update (only for mysql and mariadb). + */ + limit?: number; + } + + interface SetOptions { + /** + * If set to true, field and virtual setters will be ignored. Default false. + */ + raw?: boolean; + + /** + * Clear all previously set data values. Default false. + */ + reset?: boolean; + + include?: any; + } + + interface SaveOptions { + /** + * An alternative way of setting which fields should be persisted. + */ + fields?: any; + + /** + * If true, the updatedAt timestamp will not be updated. Default false. + */ + silent?: boolean; + + transaction?: Transaction; + } + + interface ValidateOptions { + /** + * An array of strings. All properties that are in this array will not be validated. + */ + skip: Array; + } + + interface IncrementOptions { + /** + * The number to increment by. Default 1. + */ + by?: number; + + transaction?: Transaction; + } + + interface IndexOptions { + indicesType?: string; + indexType?: string; + indexName?: string; + parser?: any; + } + + interface ProxyOptions { + /** + * An array of the events to proxy. Defaults to sql, error and success. + */ + events: Array; + } + + interface AssociationOptions { + /** + * Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For + * example if User.hasOne(Profile, {onDelete: 'cascade', hooks:true}), the before-/afterDestroy hooks for profile + * will be called when a user is deleted. Otherwise the profile will be deleted without invoking any hooks. + * Default false. + */ + hooks?: boolean; + + /** + * The name of the table that is used to join source and target in n:m associations. Can also be a sequelize model + * if you want to define the junction table yourself and add extra attributes to it. + */ + through?: any; + + /** + * The alias of this model. If you create multiple associations between the same tables, you should provide an + * alias to be able to distinguish between them. If you provide an alias when creating the assocition, you should + * provide the same alias when eager loading and when getting assocated models. Defaults to the singularized + * version of target.name + */ + as?: string; + + /** + * The foreignKey can be either a string name of the foreign key in the target table, + * or can be an object defining the foreign key and its options. Note foreignKey is not fully + * typed since TypeScript does not support union types--it can be either a string or an + * options object. String name defaults to the name of source + primary key of source. + * + * @see ForeignKeyAttributeOptions. + */ + foreignKey?: any; + + /** + * What should happen when the referenced key is deleted. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or + * NO ACTION. Default SET NULL. + */ + onDelete?: string; + + /** + * What should happen when the referenced key is updated. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or + * NO ACTION. Default CASCADE. + */ + onUpdate?: string; + + /** + * Should on update and on delete constraints be enabled on the foreign key. + */ + constraints?: boolean; + } + + interface TriggerOptions { + insert?: Array; + update?: Array; + delete?: Array; + truncate?: Array; + } + + interface TriggerParam { + type: string; + direction?: string; + name?: string; + } + + interface SelectOptions { + limit?: number; + offset?: number; + attributes?: Array; + hasIncludeWhere?: boolean; + hasIncludeRequired?: boolean; + hasMultiAssociation?: boolean; + tableAs?: string; + table?: string; + include?: Array; + includeIgnoreAttributes?: boolean; + where?: any; + /** + * String field name or array of strings of field names. + */ + group?: any; + having?: any; + order?: any; + lock?: string; + } + + interface HashToWhereConditionsOption { + include?: boolean; + keysEscaped?: boolean; + } + + interface ModelMangerGetDaoOptions { + attribute: string; + } + + interface ModelManagerForEachDaoOptions { + /** + * Default true. + */ + reverse: boolean; + } + + interface MigratorOptions { + /** + * A flag that defines if the migrator should get instantiated or not.. + */ + force: boolean; + } + + interface FindAndCountResult { + /** + * The matching model instances. + */ + rows?: Array; + + /** + * The total number of rows. This may be more than the rows returned if a limit and/or offset was supplied. + */ + count?: number; + } + + interface Col { + /** + * Column name. + */ + col: string; + } + + interface Cast { + /** + * The value to cast. + */ + val: any; + + /** + * The type to cast it to. + */ + type: string; + } + + interface Literal { + val: any; + } + + interface And { + /** + * Each argument (string or object) will be joined by AND. + */ + args: Array; + } + + interface Or { + /** + * Each argument (string or object) will be joined by OR. + */ + args: Array; + } + + interface Where { + /** + * The attribute. + */ + attribute: string; + + /** + * The condition. Can be both a simply type, or a further condition (.or, .and, .literal etc.). + */ + logic: any; + } + + interface TransactionOptions { + /** + * + */ + autocommit?: boolean; + + /** + * One of: 'READ UNCOMMITTED', 'READ COMMITTED', 'REPEATABLE READ', 'SERIALIZABLE'. Default 'REPEATABLE READ'. + */ + isolationLevel?: string; + } + + interface QueryChainerRunSeriallyOptions { + /** + * If set to true, all pending emitters will be skipped if a previous emitter failed. Default false. + */ + skipOnError: boolean; + } + + interface CreateTableQueryOptions { + comment?: string; + uniqueKeys?: Array; + charset?: string; + } + + interface MigratorExecOptions { + before?: (migrator: Migrator) => void; + after?: (migrator: Migrator) => void; + success?: (migrator: Migrator) => void; + } + + interface MigrationExecuteOptions { + method: string; + } + + interface MigrationCompareOptions { + /** + * Default false. + */ + withoutEquals: boolean; + } + + interface Promise { + /** + * Listen for events, event emitter style. Mostly for backwards compatibility with EventEmitter. + * + * @param evt Event + * @param fct Handler + */ + on(evt: string, fct: () => void): void; + + /** + * Emit an event from the emitter. + * + * @param type The type of event. + * @param value All other arguments will be passed to the event listeners. + */ + emit(type: string, ...value: Array): void; + + /** + * Listen for success events. + */ + success(onSuccess: () => void): Promise; + + /** + * Alias for success(handler). Listen for success events. + */ + ok(onSuccess: () => void): Promise; + + /** + * Listen for error events. + * + * @param onError Error handler. + */ + error(onError: (err?: Error) => void): Promise; + + /** + * Alias for error(handler). Listen for error events. + * + * @param onError Error handler. + */ + fail(onError: (err?: Error) => void): Promise; + + /** + * Alias for error(handler). Listen for error events. + * + * @param onError Error handler. + */ + failure(onError: (err?: Error) => void): Promise; + + /** + * Listen for both success and error events.. + */ + done(handler: (err: Error, result?: any) => void): Promise; + + /** + * Alias for done(handler). Listen for both success and error events.. + */ + complete(handler: (err: Error, result?: any) => void): Promise; + + /** + * Attach a function that is called every time the function that created this emitter executes a query. + * + * @param onSQL + */ + sql(onSQL: (sql: string) => void): Promise; + + /** + * Proxy every event of this promise to another one. + * + * @param promise The promise that should receive the events. + * @param options Contains an array of the events to proxy. Defaults to sql, error and success + */ + proxy(promise: Promise, options?: ProxyOptions): Promise; + + + /** + * Attach listeners to the emitter, promise style. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * Note that this function will always only be called with one argument, as per + * the promises/A spec. For functions that emit multiple arguments + * (e.g. findOrCreate) @see spread + * @param onRejected + */ + then(onFulfilled?: (result?: any) => void, onRejected?: (result?: any) => void): Promise; + + /** + * Attach listeners to the emitter, promise style. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * Note that this function will always only be called with one argument, as per + * the promises/A spec. For functions that emit multiple arguments + * (e.g. findOrCreate) @see spread + * @param onRejected + */ + then(onFulfilled?: (result?: any) => Promise, onRejected?: (result?: any) => Promise): Promise; + + /** + * Attach listeners to the emitter, promise style. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * Note that this function will always only be called with one argument, as per + * the promises/A spec. For functions that emit multiple arguments + * (e.g. findOrCreate) @see spread + * @param onRejected + */ + then(onFulfilled?: (result?: any) => PromiseT, onRejected?: (result?: any) => PromiseT): PromiseT; + + /** + * Attach listeners to the emitter, promise style. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * Note that this function will always only be called with one argument, as per + * the promises/A spec. For functions that emit multiple arguments + * (e.g. findOrCreate) @see spread + * @param onRejected + */ + then(onFulfilled?: (result?: any) => PromiseT, onRejected?: (result?: any) => void): PromiseT; + + /** + * Attach listeners to the emitter, promise style. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * Note that this function will always only be called with one argument, as per + * the promises/A spec. For functions that emit multiple arguments + * (e.g. findOrCreate) @see spread + * @param onRejected + */ + then(onFulfilled?: (result?: any) => void, onRejected?: (result?: any) => PromiseT): PromiseT; + + /** + * Attach listeners to the emitter, promise style. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * Note that this function will always only be called with one argument, as per + * the promises/A spec. For functions that emit multiple arguments + * (e.g. findOrCreate) @see spread + * @param onRejected + */ + then(onFulfilled?: (result?: any) => PromiseT, onRejected?: (result?: any) => PromiseT): Promise; + + /** + * Attach listeners to the emitter, promise style. This listener will recieve all arguments emitted by the emitter, + * as opposed to then which will only recieve the first argument. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * @param onRejected + */ + spread(onFulfilled?: (...results: Array) => Promise, onRejected?: (...results: Array) => Promise): Promise; + + /** + * Attach listeners to the emitter, promise style. This listener will recieve all arguments emitted by the emitter, + * as opposed to then which will only recieve the first argument. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * @param onRejected + */ + spread(onFulfilled?: (...results: Array) => void, onRejected?: (...results: Array) => void): Promise; + + /** + * Attach listeners to the emitter, promise style. This listener will recieve all arguments emitted by the emitter, + * as opposed to then which will only recieve the first argument. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * @param onRejected + */ + spread(onFulfilled?: (...results: Array) => Promise, onRejected?: (...results: Array) => void): Promise; + + /** + * Attach listeners to the emitter, promise style. This listener will recieve all arguments emitted by the emitter, + * as opposed to then which will only recieve the first argument. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * @param onRejected + */ + spread(onFulfilled?: (...results: Array) => void, onRejected?: (...results: Array) => Promise): Promise; + + /** + * Attach listeners to the emitter, promise style. This listener will recieve all arguments emitted by the emitter, + * as opposed to then which will only recieve the first argument. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * @param onRejected + */ + spread(onFulfilled?: (...results: Array) => PromiseT, onRejected?: (...results: Array) => PromiseT): PromiseT; + + /** + * Attach listeners to the emitter, promise style. This listener will recieve all arguments emitted by the emitter, + * as opposed to then which will only recieve the first argument. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * @param onRejected + */ + spread(onFulfilled?: (...results: Array) => void, onRejected?: (...results: Array) => PromiseT): PromiseT; + + /** + * Attach listeners to the emitter, promise style. This listener will recieve all arguments emitted by the emitter, + * as opposed to then which will only recieve the first argument. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * @param onRejected + */ + spread(onFulfilled?: (...results: Array) => PromiseT, onRejected?: (...results: Array) => void): PromiseT; + + /** + * Attach listeners to the emitter, promise style. This listener will recieve all arguments emitted by the emitter, + * as opposed to then which will only recieve the first argument. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * @param onRejected + */ + spread(onFulfilled?: (...results: Array) => PromiseT, onRejected?: (...results: Array) => PromiseT): Promise; + + /** + * Shorthand for then(null, onRejected) + */ + catch(onRejected: (result?: any) => Promise): Promise; + + /** + * Shorthand for then(null, onRejected) + */ + catch(onRejected: (result?: any) => PromiseT): PromiseT; + + /** + * Shorthand for then(null, onRejected) + */ + catch(onRejected: (result?: any) => void): Promise; + } + + interface PromiseT extends Promise { + /** + * Listen for events, event emitter style. Mostly for backwards compatibility with EventEmitter. + * + * @param evt Event + * @param fct Handler + */ + on(evt: string, fct: (t: T) => void): void; + + /** + * Emit an event from the emitter. + * + * @param type The type of event. + * @param value All other arguments will be passed to the event listeners. + */ + emit(type: string, ...value: Array): void; + + /** + * Listen for success events. + */ + success(onSuccess: (t: T) => void): PromiseT; + + /** + * Alias for success(handler). Listen for success events. + */ + ok(onSuccess: (t: T) => void): PromiseT; + + /** + * Listen for both success and error events.. + */ + done(handler: (err: Error, result: T) => void): PromiseT; + + /** + * Alias for done(handler). Listen for both success and error events.. + */ + complete(handler: (err: Error, result: T) => void): PromiseT; + + /** + * Attach a function that is called every time the function that created this emitter executes a query. + * + * @param onSQL + */ + sql(onSQL: (sql: string) => void): PromiseT; + + /** + * Proxy every event of this promise to another one. + * + * @param promise The promise that should receive the events. + * @param options Contains an array of the events to proxy. Defaults to sql, error and success + */ + proxy(promise: PromiseT, options?: ProxyOptions): PromiseT; + + /** + * Attach listeners to the emitter, promise style. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * Note that this function will always only be called with one argument, as per + * the promises/A spec. For functions that emit multiple arguments + * (e.g. findOrCreate) @see spread + * @param onRejected + */ + then(onFulfilled?: (result?: T) => void, onRejected?: (result?: T) => void): Promise; + + /** + * Attach listeners to the emitter, promise style. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * Note that this function will always only be called with one argument, as per + * the promises/A spec. For functions that emit multiple arguments + * (e.g. findOrCreate) @see spread + * @param onRejected + */ + then(onFulfilled?: (result?: T) => Promise, onRejected?: (result?: T) => Promise): Promise; + + /** + * Attach listeners to the emitter, promise style. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * Note that this function will always only be called with one argument, as per + * the promises/A spec. For functions that emit multiple arguments + * (e.g. findOrCreate) @see spread + * @param onRejected + */ + then(onFulfilled?: (result?: T) => PromiseT, onRejected?: (result?: T) => PromiseT): PromiseT; + + /** + * Attach listeners to the emitter, promise style. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * Note that this function will always only be called with one argument, as per + * the promises/A spec. For functions that emit multiple arguments + * (e.g. findOrCreate) @see spread + * @param onRejected + */ + then(onFulfilled?: (result?: T) => PromiseT, onRejected?: (result?: T) => void): PromiseT; + + /** + * Attach listeners to the emitter, promise style. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * Note that this function will always only be called with one argument, as per + * the promises/A spec. For functions that emit multiple arguments + * (e.g. findOrCreate) @see spread + * @param onRejected + */ + then(onFulfilled?: (result?: T) => void, onRejected?: (result?: T) => PromiseT): PromiseT; + + /** + * Attach listeners to the emitter, promise style. + * + * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). + * Note that this function will always only be called with one argument, as per + * the promises/A spec. For functions that emit multiple arguments + * (e.g. findOrCreate) @see spread + * @param onRejected + */ + then(onFulfilled?: (result?: T) => PromiseT, onRejected?: (result?: T) => PromiseT): Promise; + + /** + * Shorthand for then(null, onRejected) + */ + catch(onRejected: (result?: T) => Promise): Promise; + + /** + * Shorthand for then(null, onRejected) + */ + catch(onRejected: (result?: T) => PromiseT): PromiseT; + + /** + * Shorthand for then(null, onRejected) + */ + catch(onRejected: (result?: T) => void): Promise; + } + + interface Utils { + _: Lodash; + + /** + * Formats a string to parse and interpolate values into the string based on the optionally provided SQL dialect. + * @param arr Array where first element is string with placeholders and remaining attributes are values to replace placeholders. + * @param dialect SQL Dialect. + */ + format(arr: Array, dialect?: string): string; + + /** + * Formats a SQL string replacing named placeholders with values from the parameters object with matching key names. + * + * @param sql String to format. + * @param parameters Key/value hash with values to replace in string. + * @param dialect SQL Dialect + */ + formatNamedParameters(sql: string, parameters: any, dialect?: string): string; + + injectScope(scope: string, merge: boolean): any; + + smartWhere(whereArg: any, dialect: string): any; + + compileSmartWhere(obj: any, dialect: string): Array; + + getWhereLogic(logic: string, val?: any): string; + + isHash(obj: any): boolean; + + hasChanged(attrValue: any, value: any): boolean; + + argsArePrimaryKeys(args: Array, primaryKeys: any): boolean; + + /** + * Consistently combines two table names such that the alphabetically first name always comes first when combined. + * + * @param table1 + * @param table2 + */ + combineTableNames(table1: string, table2: string): string; + + singularize(s: string, language?: string): string; + + pluralize(s: string, language: string): string; + + /** + * Same concept as _.merge, but don't overwrite properties that have already been assigned + */ + mergeDefaults: typeof _.merge; + + lowercaseFirst(str: string): string; + + uppercaseFirst(str: string): string; + + spliceStr(str: string, index: number, count: number, add: string): string; + + camelize(str: string): string; + + removeCommentsFromFunctionString(s: string): string; + + toDefaultValue(value: any): any; + + defaultValueSchemable(value: any): boolean; + setAttributes(hash: any, identifier: string, instance: any, prefix: string): any; + removeNullValuesFromHash(hash: any, omitNull: boolean, options: any): any; + firstValueOfHash(obj: any): any; + inherit(subClass: any, superClass: any): any; + stack(): string; + now(dialect: string): Date; + + /** + * Runs provided function on next tick, depending on environment. + * + * @param f + */ + tick(f: Function): void; + + /** + * Surrounds a string with tick marks while removing all existing tick marks from the string. + * @param s String to tick + * @param tickChar Tick mark. Default ` + */ + addTicks(s: string, tickChar?: string): string; + + removeTicks(s: string, tickChar?: string): string; + + generateUUID(): string; + + validateParameter(value: any, expectation: any): boolean; + + CustomEventEmitter: EventEmitter; + Promise: Promise; + QueryChainer: QueryChainer; + Lingo: any; // external project, no definitions yet} + } + + interface Lodash extends _.LoDashStatic { + camelizeIf(str: string, condition: boolean): string; + camelizeIf(str: string, condition: any): string; + underscoredIf(str: string, condition: boolean): string; + underscoredIf(str: string, condition: any): string; + /** + * * Returns an array with some falsy values removed. The values null, "", undefined and NaN are considered falsey. + * + * @param arr Array to compact. + */ + compactLite(arr: Array): Array; + } + + interface MetaPojo { + from: string; + to: string; + } + interface MetaInstance extends MetaPojo, Model { + + } + + interface DataTypeStringBase { + BINARY: DataTypeString; + } + interface DataTypeNumberBase { + UNSIGNED: boolean; + ZEROFILL: boolean; + } + + interface DataTypeString extends DataTypeStringBase { + } + interface DataTypeChar extends DataTypeStringBase { + } + interface DataTypeInteger extends DataTypeNumberBase { + } + interface DataTypeBigInt extends DataTypeNumberBase { + } + interface DataTypeFloat extends DataTypeNumberBase { + } + interface DataTypeBlob { + } + interface DataTypeDecimal { + PRECISION: number; + SCALE: number; + } + + interface DataTypeVirtual { + } + interface DataTypeEnum { + (...values: Array): DataTypeEnum; + } + interface DataTypeArray { + } + interface DataTypeHstore { + } + + interface DataTypes { + STRING: DataTypeString; + CHAR: DataTypeChar; + TEXT: string; + INTEGER: DataTypeInteger; + BIGINT: DataTypeBigInt; + DATE: string; + BOOLEAN: string; + FLOAT: DataTypeFloat; + NOW: string; + BLOB: DataTypeBlob; + DECIMAL: DataTypeDecimal; + UUID: string; + UUIDV1: string; + UUIDV4: string; + VIRTUAL: DataTypeVirtual; + NONE: DataTypeVirtual; + ENUM: DataTypeEnum; + ARRAY: DataTypeArray; + HSTORE: DataTypeHstore; + } + } + + var sequelize: sequelize.SequelizeStatic; + + export = sequelize; +} diff --git a/sequelize/sequelize-test.ts b/sequelize/sequelize-test.ts new file mode 100644 index 000000000..ebc8cc0ce --- /dev/null +++ b/sequelize/sequelize-test.ts @@ -0,0 +1,1284 @@ +/// + +import Sequelize = require("sequelize"); + +// +// Fixtures +// ~~~~~~~~~~ +// + +interface AnyAttributes { }; +interface AnyInstance extends Sequelize.Instance { }; + +var s = new Sequelize( '' ); +var sequelize = s; +var DataTypes = Sequelize; +var User = s.define( 'user', {} ); +var user = User.build(); +var Task = s.define( 'task', {} ); +var Group = s.define( 'group', {} ); +var Comment = s.define( 'comment', {} ); +var Post = s.define( 'post', {} ); +var t = null; +s.transaction().then( ( a ) => t = a ); + +// +// Generics +// ~~~~~~~~~~ +// + +interface GUserAttributes { + id? : number; + username? : string; +} + +interface GUserInstance extends Sequelize.Instance {} +var GUser = s.define( 'user', { id: Sequelize.INTEGER, username : Sequelize.STRING }); +GUser.create({ id : 1, username : 'one' }).then( ( guser ) => guser.save() ); + +var schema : Sequelize.DefineAttributes = { + key : { type : Sequelize.STRING, primaryKey : true }, + value : Sequelize.STRING +}; + +s.define('user', schema); + +interface GTaskAttributes { + revision? : number; + name? : string; +} +interface GTaskInstance extends Sequelize.Instance {} +var GTask = s.define( 'task', { revision : Sequelize.INTEGER, name : Sequelize.STRING }); + +GUser.hasMany(GTask); + + + +// +// Associations +// ~~~~~~~~~~~~~~ +// +// https://github.com/sequelize/sequelize/tree/v3.4.1/test/integration/associations +// + +User.hasOne( Task ); +User.hasOne( Task, { foreignKey : 'primaryGroupId', as : 'primaryUsers' } ); +User.hasOne( Task, { foreignKey : 'userCoolIdTag' } ); +User.hasOne( Task, { foreignKey : 'userId', keyType : Sequelize.STRING, constraints : false } ); +Task.hasOne( User, { foreignKey : { name : 'taskId', field : 'task_id' } } ); +User.hasOne( Task, { foreignKey : { name : 'uid', allowNull : false } } ); +User.hasOne( Task, { onDelete : 'cascade' } ); +User.hasOne( Task, { onUpdate : 'cascade' } ); +User.hasOne( Task, { onDelete : 'cascade', hooks : true } ); +User.hasOne( Task, { foreignKey : { allowNull : false } } ); +User.hasOne( Task, { foreignKeyConstraint : true } ); + +User.belongsTo( Task ); +User.belongsTo( Task, { foreignKey : 'primaryGroupId', as : 'primaryUsers' } ); +Task.belongsTo( User, { foreignKey : 'user_id' } ); +Task.belongsTo( User, { foreignKey : 'user_name', targetKey : 'username' } ); +User.belongsTo( User, { foreignKey : 'userId', keyType : Sequelize.STRING, constraints : false } ); +User.belongsTo( Post, { foreignKey : { name : 'AccountId', field : 'account_id' } } ); +Task.belongsTo( User, { foreignKey : { allowNull : false, name : 'uid' } } ); +Task.belongsTo( User, { constraints : false } ); +Task.belongsTo( User, { onDelete : 'cascade' } ); +Task.belongsTo( User, { onUpdate : 'restrict' } ); +User.belongsTo( User, { + as : 'parentBlocks', + foreignKey : 'child', + foreignKeyConstraint : true +} ); + +User.hasMany( User ); +User.hasMany( User, { foreignKey : 'primaryGroupId', as : 'primaryUsers' } ); +User.hasMany( Task, { foreignKey : 'userId' } ); +User.hasMany( Task, { foreignKey : 'userId', as : 'activeTasks', scope : { active : true } } ); +User.hasMany( Task, { foreignKey : 'userId', keyType : Sequelize.STRING, constraints : false } ); +User.hasMany( Task, { foreignKey : { name : 'uid', allowNull : false } } ); +User.hasMany( Task, { foreignKey : { allowNull : true } } ); +User.hasMany( Task, { as : 'Children' } ); +User.hasMany( Task, { as : { singular : 'task', plural : 'taskz' } } ); +User.hasMany( Task, { constraints : false } ); +User.hasMany( Task, { onDelete : 'cascade' } ); +User.hasMany( Task, { onUpdate : 'cascade' } ); +Post.hasMany( Task, { foreignKey : 'commentable_id', scope : { commentable : 'post' } } ); +User.hasMany( User, { + as : 'childBlocks', + foreignKey : 'parent', + foreignKeyConstraint : true +} ); + +User.belongsToMany( Task, { through : 'UserTasks' } ); +User.belongsToMany( User, { through : Task } ); +User.belongsToMany( Group, { as : 'groups', through : Task, foreignKey : 'id_user' } ); +User.belongsToMany( Task, { as : 'activeTasks', through : Task, scope : { active : true } } ); +User.belongsToMany( Task, { as : 'startedTasks', through : { model : Task, scope : { started : true } } } ); +User.belongsToMany( Group, { through : 'group_members', foreignKey : 'group_id', otherKey : 'member_id' } ); +User.belongsToMany( User, { as : 'Participants', through : User } ); +User.belongsToMany( Group, { through : 'user_places', foreignKey : 'user_id' } ); +User.belongsToMany( Group, { + through : 'user_projects', + as : 'Projects', + foreignKey : { + field : 'user_id', + name : 'userId' + }, + otherKey : { + field : 'project_id', + name : 'projectId' + } +} ); +User.belongsToMany( Task, { onDelete : 'RESTRICT', through : 'tasksusers' } ); +User.belongsToMany( Task, { constraints : false, through : 'tasksusers' } ); +User.belongsToMany( Task, { foreignKey : { name : 'user_id', defaultValue : 42 }, through : 'UserProjects' } ); +User.belongsToMany( Post, { through : User } ); +Post.belongsToMany( User, { as : 'categories', through : User, scope : { type : 'category' } } ); +Post.belongsToMany( User, { as : 'tags', through : User, scope : { type : 'tag' } } ); +Post.belongsToMany( User, { + through : { + model : User, + unique : false, + scope : { + taggable : 'post' + } + }, + foreignKey : 'taggable_id', + constraints : false +} ); +Post.belongsToMany( Post, { through : { model : Post, unique : false }, foreignKey : 'tag_id' } ); +Post.belongsToMany( Post, { as : 'Parents', through : 'Family', foreignKey : 'ChildId', otherKey : 'PersonId' } ); + +// +// DataTypes +// ~~~~~~~~~~~ +// +// https://github.com/sequelize/sequelize/blob/v3.4.1/test/unit/sql/data-types.test.js +// + +Sequelize.STRING; +Sequelize.STRING( 1234 ); +Sequelize.STRING( { length : 1234 } ); +Sequelize.STRING( 1234 ).BINARY; +Sequelize.STRING.BINARY; +Sequelize.TEXT; +Sequelize.TEXT( 'tiny' ); +Sequelize.TEXT( { length : 'tiny' } ); +Sequelize.TEXT( 'medium' ); +Sequelize.TEXT( 'long' ); +Sequelize.CHAR; +Sequelize.CHAR( 12 ); +Sequelize.CHAR( { length : 12 } ); +Sequelize.CHAR( 12 ).BINARY; +Sequelize.CHAR.BINARY; +Sequelize.BOOLEAN; +Sequelize.DATE; +Sequelize.UUID; +Sequelize.UUIDV1; +Sequelize.UUIDV4; +Sequelize.NOW; +Sequelize.INTEGER; +Sequelize.INTEGER.UNSIGNED; +Sequelize.INTEGER.UNSIGNED.ZEROFILL; +Sequelize.INTEGER( 11 ); +Sequelize.INTEGER( { length : 11 } ); +Sequelize.INTEGER( 11 ).UNSIGNED; +Sequelize.INTEGER( 11 ).UNSIGNED.ZEROFILL; +Sequelize.INTEGER( 11 ).ZEROFILL; +Sequelize.INTEGER( 11 ).ZEROFILL.UNSIGNED; +Sequelize.BIGINT; +Sequelize.BIGINT.UNSIGNED; +Sequelize.BIGINT.UNSIGNED.ZEROFILL; +Sequelize.BIGINT( 11 ); +Sequelize.BIGINT( { length : 11 } ); +Sequelize.BIGINT( 11 ).UNSIGNED; +Sequelize.BIGINT( 11 ).UNSIGNED.ZEROFILL; +Sequelize.BIGINT( 11 ).ZEROFILL; +Sequelize.BIGINT( 11 ).ZEROFILL.UNSIGNED; +Sequelize.REAL.UNSIGNED; +Sequelize.REAL( 11 ); +Sequelize.REAL( { length : 11 } ); +Sequelize.REAL( 11 ).UNSIGNED; +Sequelize.REAL( 11 ).UNSIGNED.ZEROFILL; +Sequelize.REAL( 11 ).ZEROFILL; +Sequelize.REAL( 11 ).ZEROFILL.UNSIGNED; +Sequelize.REAL( 11, 12 ); +Sequelize.REAL( 11, 12 ).UNSIGNED; +Sequelize.REAL( { length : 11, decimals : 12 } ).UNSIGNED; +Sequelize.REAL( 11, 12 ).UNSIGNED.ZEROFILL; +Sequelize.REAL( 11, 12 ).ZEROFILL; +Sequelize.REAL( 11, 12 ).ZEROFILL.UNSIGNED; +Sequelize.DOUBLE; +Sequelize.DOUBLE.UNSIGNED; +Sequelize.DOUBLE( 11 ); +Sequelize.DOUBLE( 11 ).UNSIGNED; +Sequelize.DOUBLE( { length : 11 } ).UNSIGNED; +Sequelize.DOUBLE( 11 ).UNSIGNED.ZEROFILL; +Sequelize.DOUBLE( 11 ).ZEROFILL; +Sequelize.DOUBLE( 11 ).ZEROFILL.UNSIGNED; +Sequelize.DOUBLE( 11, 12 ); +Sequelize.DOUBLE( 11, 12 ).UNSIGNED; +Sequelize.DOUBLE( 11, 12 ).UNSIGNED.ZEROFILL; +Sequelize.DOUBLE( 11, 12 ).ZEROFILL; +Sequelize.DOUBLE( 11, 12 ).ZEROFILL.UNSIGNED; +Sequelize.FLOAT; +Sequelize.FLOAT.UNSIGNED; +Sequelize.FLOAT( 11 ); +Sequelize.FLOAT( 11 ).UNSIGNED; +Sequelize.FLOAT( 11 ).UNSIGNED.ZEROFILL; +Sequelize.FLOAT( 11 ).ZEROFILL; +Sequelize.FLOAT( { length : 11 } ).ZEROFILL; +Sequelize.FLOAT( 11 ).ZEROFILL.UNSIGNED; +Sequelize.FLOAT( 11, 12 ); +Sequelize.FLOAT( 11, 12 ).UNSIGNED; +Sequelize.FLOAT( { length : 11, decimals : 12 } ).UNSIGNED; +Sequelize.FLOAT( 11, 12 ).UNSIGNED.ZEROFILL; +Sequelize.FLOAT( 11, 12 ).ZEROFILL; +Sequelize.FLOAT( 11, 12 ).ZEROFILL.UNSIGNED; +Sequelize.NUMERIC; +Sequelize.NUMERIC( 15, 5 ); +Sequelize.DECIMAL; +Sequelize.DECIMAL( 10, 2 ); +Sequelize.DECIMAL( { precision : 10, scale : 2 } ); +Sequelize.DECIMAL( 10 ); +Sequelize.DECIMAL( { precision : 10 } ); +Sequelize.ENUM( 'value 1', 'value 2' ); +Sequelize.BLOB; +Sequelize.BLOB( 'tiny' ); +Sequelize.BLOB( 'medium' ); +Sequelize.BLOB( { length : 'medium' } ); +Sequelize.BLOB( 'long' ); +Sequelize.ARRAY( Sequelize.STRING ); +Sequelize.ARRAY( Sequelize.STRING( 100 ) ); +Sequelize.ARRAY( Sequelize.INTEGER ); +Sequelize.ARRAY( Sequelize.HSTORE ); +Sequelize.ARRAY( Sequelize.ARRAY( Sequelize.STRING ) ); +Sequelize.ARRAY( Sequelize.TEXT ); +Sequelize.ARRAY( Sequelize.DATE ); +Sequelize.ARRAY( Sequelize.BOOLEAN ); +Sequelize.ARRAY( Sequelize.DECIMAL ); +Sequelize.ARRAY( Sequelize.DECIMAL( 6 ) ); +Sequelize.ARRAY( Sequelize.DECIMAL( 6, 4 ) ); +Sequelize.ARRAY( Sequelize.DOUBLE ); +Sequelize.ARRAY( Sequelize.REAL ); +Sequelize.ARRAY( Sequelize.JSON ); +Sequelize.ARRAY( Sequelize.JSONB ); +Sequelize.GEOMETRY; +Sequelize.GEOMETRY( 'POINT' ); +Sequelize.GEOMETRY( 'LINESTRING' ); +Sequelize.GEOMETRY( 'POLYGON' ); +Sequelize.GEOMETRY( 'POINT', 4326 ); + +// +// Deferrable +// ~~~~~~~~~~~~ +// +// https://github.com/sequelize/sequelize/blob/v3.4.1/test/integration/sequelize/deferrable.test.js +// + +Sequelize.Deferrable.NOT; +Sequelize.Deferrable.INITIALLY_IMMEDIATE; +Sequelize.Deferrable.INITIALLY_DEFERRED; +Sequelize.Deferrable.SET_DEFERRED; +Sequelize.Deferrable.SET_DEFERRED( ['taskTableName_user_id_fkey'] ); +Sequelize.Deferrable.SET_IMMEDIATE; +Sequelize.Deferrable.SET_IMMEDIATE( ['taskTableName_user_id_fkey'] ); + +// +// Errors +// ~~~~~~~~ +// +// https://github.com/sequelize/sequelize/blob/v3.4.1/test/integration/error.test.js +// + +Sequelize.Error; +Sequelize.ValidationError; +s.Error; +s.ValidationError; +new s.ValidationError( 'Validation Error', [ + new s.ValidationErrorItem( ' cannot be null', 'notNull Violation', '', null ) + , new s.ValidationErrorItem( ' cannot be an array or an object', 'string violation', + '', null ) +] ); +new s.Error(); +new s.ValidationError(); +new s.ValidationErrorItem( 'invalid', 'type', 'first_name', null ); +new s.ValidationErrorItem( 'invalid', 'type', 'last_name', null ); +new s.DatabaseError( new Error( 'original database error message' ) ); +new s.ConnectionError( new Error( 'original connection error message' ) ); +new s.ConnectionRefusedError( new Error( 'original connection error message' ) ); +new s.AccessDeniedError( new Error( 'original connection error message' ) ); +new s.HostNotFoundError( new Error( 'original connection error message' ) ); +new s.HostNotReachableError( new Error( 'original connection error message' ) ); +new s.InvalidConnectionError( new Error( 'original connection error message' ) ); +new s.ConnectionTimedOutError( new Error( 'original connection error message' ) ); + +// +// Hooks +// ~~~~~~~ +// +// https://github.com/sequelize/sequelize/blob/v3.4.1/test/integration/hooks.test.js +// + +User.addHook( 'afterCreate', function( instance, options, next ) { next(); } ); +User.addHook( 'afterCreate', 'myHook', function( instance, options, next ) { next(); } ); +s.addHook( 'beforeInit', function( config, options ) { } ); +User.hook( 'afterCreate', 'myHook', function( instance, options, next ) { next(); } ); +User.hook( 'afterCreate', 'myHook', function( instance, options, next ) { next(); } ); + +User.removeHook( 'afterCreate', 'myHook' ); + +User.hasHook( 'afterCreate' ); +User.hasHooks( 'afterCreate' ); + +User.beforeValidate( function( user, options ) { user.isNewRecord; } ); +User.beforeValidate( 'myHook', function( user, options ) { user.isNewRecord; } ); + +User.afterValidate( function( user, options ) { user.isNewRecord; } ); +User.afterValidate( 'myHook', function( user, options ) { user.isNewRecord; } ); + +User.beforeCreate( function( user, options ) { user.isNewRecord; } ); +User.beforeCreate( function( user, options, fn ) {fn();} ); +User.beforeCreate( 'myHook', function( user, options ) { user.isNewRecord; } ); + +User.afterCreate( function( user, options ) { user.isNewRecord; } ); +User.afterCreate( function( user, options, fn ) {fn();} ); +User.afterCreate( 'myHook', function( user, options ) { user.isNewRecord; } ); + +User.beforeDestroy( function( user, options ) {throw new Error( 'Whoops!' );} ); +User.beforeDestroy( function( user, options, fn ) {fn();} ); +User.beforeDestroy( 'myHook', function( user, options ) {throw new Error( 'Whoops!' );} ); +User.beforeDelete( function( user, options ) {throw new Error( 'Whoops!' );} ); +User.beforeDelete( 'myHook', function( user, options ) {throw new Error( 'Whoops!' );} ); + +User.afterDestroy( function( user, options ) {throw new Error( 'Whoops!' );} ); +User.afterDestroy( 'myHook', function( user, options ) {throw new Error( 'Whoops!' );} ); +User.afterDestroy( function( user, options, fn ) {fn();} ); +User.afterDelete( function( user, options ) {throw new Error( 'Whoops!' );} ); +User.afterDelete( 'myHook', function( user, options ) {throw new Error( 'Whoops!' );} ); + +User.beforeUpdate( function( user, options ) {throw new Error( 'Whoops!' ); } ); +User.beforeUpdate( 'myHook', function( user, options ) {throw new Error( 'Whoops!' ); } ); + +User.afterUpdate( function( user, options ) {throw new Error( 'Whoops!' );} ); +User.afterUpdate( 'myHook', function( user, options ) {throw new Error( 'Whoops!' );} ); + +User.beforeBulkCreate( function( daos, options ) { throw new Error( 'Whoops!' );} ); +User.beforeBulkCreate( 'myHook', function( daos, options ) { throw new Error( 'Whoops!' );} ); +User.beforeBulkCreate( function( daos, options, fn ) {fn();} ); + +User.afterBulkCreate( function( daos, options ) {throw new Error( 'Whoops!' ); } ); +User.afterBulkCreate( 'myHook', function( daos, options ) {throw new Error( 'Whoops!' ); } ); +User.afterBulkCreate( function( daos, options, fn ) {fn();} ); + +User.beforeBulkDestroy( function( options ) {throw new Error( 'Whoops!' );} ); +User.beforeBulkDestroy( function( options, fn ) {fn();} ); +User.beforeBulkDestroy( 'myHook', function( options, fn ) {fn();} ); +User.beforeBulkDelete( 'myHook', function( options, fn ) {fn();} ); + +User.afterBulkDestroy( function( options ) {throw new Error( 'Whoops!' );} ); +User.afterBulkDestroy( function( options, fn ) {fn();} ); +User.afterBulkDestroy( 'myHook', function( options, fn ) {fn();} ); +User.afterBulkDelete( 'myHook', function( options, fn ) {fn();} ); + +User.beforeBulkUpdate( function( options ) {throw new Error( 'Whoops!' );} ); +User.beforeBulkUpdate( 'myHook', function( options ) {throw new Error( 'Whoops!' );} ); + +User.afterBulkUpdate( function( options ) {throw new Error( 'Whoops!' );} ); +User.afterBulkUpdate( 'myHook', function( options ) {throw new Error( 'Whoops!' );} ); + +User.beforeFind( function( options ) {} ); +User.beforeFind( 'myHook', function( options ) {} ); + +User.beforeFindAfterExpandIncludeAll( function( options ) {} ); +User.beforeFindAfterExpandIncludeAll( 'myHook', function( options ) {} ); + +User.beforeFindAfterOptions( function( options ) {} ); +User.beforeFindAfterOptions( 'myHook', function( options ) {} ); + +User.afterFind( function( user ) {} ); +User.afterFind( 'myHook', function( user ) {} ); + +s.beforeDefine( function( attributes, options ) {} ); +s.beforeDefine( 'myHook', function( attributes, options ) {} ); + +s.afterDefine( function( model ) {} ); +s.afterDefine( 'myHook', function( model ) {} ); + +s.beforeInit( function( config, options ) {} ); +s.beforeInit( 'myHook', function( attributes, options ) {} ); + +s.afterInit( function( model ) {} ); +s.afterInit( 'myHook', function( model ) {} ); + +s.define( 'User', {}, { + hooks : { + beforeValidate : function( user, options, fn ) {fn();}, + afterValidate : function( user, options, fn ) {fn();}, + beforeCreate : function( user, options, fn ) {fn();}, + afterCreate : function( user, options, fn ) {fn();}, + beforeDestroy : function( user, options, fn ) {fn();}, + afterDestroy : function( user, options, fn ) {fn();}, + beforeDelete : function( user, options, fn ) {fn();}, + afterDelete : function( user, options, fn ) {fn();}, + beforeUpdate : function( user, options, fn ) {fn();}, + afterUpdate : function( user, options, fn ) {fn();} + } +} ); + +// +// Instance +// ~~~~~~~~~~ +// +// https://github.com/sequelize/sequelize/blob/v3.4.1/test/integration/instance.test.js +// https://github.com/sequelize/sequelize/blob/v3.4.1/test/integration/instance/update.test.js +// https://github.com/sequelize/sequelize/blob/v3.4.1/test/integration/instance/values.test.js +// + +user.isNewRecord = true; + +user.Model.build( { a : 'b' } ); + +user.sequelize.close(); + +user.where(); + +user.getDataValue( '' ); + +user.setDataValue( '', '' ); +user.setDataValue( '', {} ); + +user.get( 'aNumber', { plain : true, clone : true } ); +user.get(); + +user.set( 'email', 'B' ); +user.set( { name : 'B', bio : 'B' } ).save().then( ( p ) => p ); +user.set( 'birthdate', new Date() ); +user.set( { id : 1, t : 'c', q : [{ id : 1, n : 'a' }, { id : 2, n : 'Beta' }], u : { id : 1, f : 'b', l : 'd' } } ); +user.setAttributes( { a : 3 } ); +user.setAttributes( { id : 1, a : 'n', c : [{ id : 1 }, { id : 2, f : 'e' }], x : { id : 1, f : 'h', l : 'd' } } ); + +user.changed( 'name' ); +user.changed(); + +user.previous( 'name' ); + +user.save().then( ( p ) => p ); +user.save( { fields : ['a'] } ).then( ( p ) => p ); +user.save( { transaction : t } ); + +user.reload(); +user.reload( { attributes : ['bNumber'] } ); +user.reload( { transaction : t } ); + +user.validate(); + +user.update( { bNumber : 2 }, { where : { id : 1 } } ); +user.update( { username : 'userman' }, { silent : true } ); +user.update( { username : 'yolo' }, { logging : function() { } } ); +user.update( { username : 'bar' }, { where : { username : 'foo' }, transaction : t } ).then( ( p ) => p ); +user.updateAttributes( { a : 3 } ).then( ( p ) => p ); +user.updateAttributes( { a : 3 }, { fields : ['secretValue'], logging : function( sql ) {} } ); + +user.destroy().then( ( p ) => p ); +user.destroy( { logging : function( sql ) {} } ); +user.destroy( { transaction : t } ).then( ( p ) => p ); + +user.restore(); + +user.increment( 'number', { by : 2 } ).then( ( p ) => p ); +user.increment( ['aNumber'], { by : 2, where : { bNumber : 1 } } ).then( ( p ) => p ); +user.increment( ['aNumber'], { by : 2 } ).then( ( p ) => p ); +user.increment( 'aNumber' ).then( ( p ) => p ); +user.increment( { 'aNumber' : 1, 'bNumber' : 2 } ).then( ( p ) => p ); +user.increment( 'number', { by : 2, transaction : t } ).then( ( p ) => p ); + +user.decrement( 'aNumber', { by : 2 } ).then( ( p ) => p ); +user.decrement( ['aNumber'], { by : 2 } ).then( ( p ) => p ); +user.decrement( 'aNumber' ).then( ( p ) => p ); +user.decrement( { 'aNumber' : 1, 'bNumber' : 2 } ).then( ( p ) => p ); +user.decrement( 'number', { by : 2, transaction : t } ).then( ( p ) => p ); + +user.equals( user ); + +user.equalsOneOf( [user, user] ); + +user.toJSON(); + +// +// Model +// ~~~~~~~ +// +// https://github.com/sequelize/sequelize/blob/v3.4.1/test/integration/model.test.js +// + +User.removeAttribute( 'id' ); + +User.sync( { force : true } ).then( function() { } ); +User.sync( { force : true, logging : function() { } } ); + +User.drop(); + +User.schema( 'special' ); +User.schema( 'special' ).create( { age : 3 }, { logging : function( UserSpecial ) {} } ); + +User.getTableName(); + +User.scope( 'lowAccess' ).count(); +User.scope( { where : { parent_id : 2 } } ); + +User.findAll(); +User.findAll( { where : { data : { employment : null } } } ); +User.findAll( { where : { aNumber : { gte : 10 } } } ).then( ( u ) => u[0].isNewRecord ); +User.findAll( { where : [s.or( { u : 'b' }, { u : ';' } ), s.and( { id : [1, 2] } )], include : [{ model : User }] } ); +User.findAll( { + where : [s.or( { a : 'b' }, { c : 'd' } ), s.and( { id : [1, 2, 3] }, + s.or( { deletedAt : null }, { deletedAt : { gt : new Date( 0 ) } } ) )] +} ); +User.findAll( { paranoid : false, where : [' IS NOT NULL '], include : [{ model : User }] } ); +User.findAll( { transaction : t } ); +User.findAll( { where : { data : { name : { last : 's' }, employment : { $ne : 'a' } } }, order : [['id', 'ASC']] } ); +User.findAll( { where : { username : ['boo', 'boo2'] } } ); +User.findAll( { where : { username : { like : '%2' } } } ); +User.findAll( { where : { theDate : { '..' : ['2013-01-02', '2013-01-11'] } } } ); +User.findAll( { where : { intVal : { '!..' : [8, 10] } } } ); +User.findAll( { where : { theDate : { between : ['2013-01-02', '2013-01-11'] } } } ); +User.findAll( { where : { theDate : { between : ['2013-01-02', '2013-01-11'] }, intVal : 10 } } ); +User.findAll( { where : { theDate : { between : ['2012-12-10', '2013-01-02'] } } } ); +User.findAll( { where : { theDate : { nbetween : ['2013-01-04', '2013-01-20'] } } } ); +User.findAll( { order : [s.col( 'name' )] } ); +User.findAll( { order : [['theDate', 'DESC']] } ); +User.findAll( { include : [User], order : [[User, User, 'numYears', 'c']] } ); +User.findAll( { include : [{ model : User, include : [User, { model : User, as : 'residents' }] }] } ); +User.findAll( { order : [[User, { model : User, as : 'residents' }, 'lastName', 'c']] } ); +User.findAll( { include : [User], order : [[User, 'name', 'c']] } ); +User.findAll( { include : [{ all : 'HasMany', attributes : ['name'] }] } ); +User.findAll( { include : [{ all : true }, { model : User, attributes : ['id'] }] } ); +User.findAll( { include : [{ all : 'BelongsTo' }] } ); +User.findAll( { include : [{ all : true }] } ); +User.findAll( { where : { username : 'barfooz' }, raw : true } ); +User.findAll( { where : { name : 'worker' }, include : [{ model : User, as : 'ToDos' }] } ); +User.findAll( { where : { user_id : 1 }, attributes : ['a', 'b'], include : [{ model : User, attributes : ['c'] }] } ); +User.findAll( { order : s.literal( 'email =' ) } ); +User.findAll( { order : [s.literal( 'email = ' + s.escape( 'test@sequelizejs.com' ) )] } ); +User.findAll( { order : [['id', ';DELETE YOLO INJECTIONS']] } ); +User.findAll( { include : [User], order : [[User, 'id', ';DELETE YOLO INJECTIONS']] } ); +User.findAll( { include : [User], order : [['id', 'ASC NULLS LAST'], [User, 'id', 'DESC NULLS FIRST']] } ); +User.findAll( { include : [{ model : User, where : { title : 'DoDat' }, include : [{ model : User }] }] } ); + +User.findById( 'a string' ); + +User.findOne( { where : { username : 'foo' } } ); +User.findOne( { where : { id : 1 }, attributes : ['id', ['username', 'name']] } ); +User.findOne( { where : { id : 1 }, attributes : ['id'] } ); +User.findOne( { where : { username : 'foo' }, logging : function( sql ) { } } ); +User.findOne( { limit : 10 } ); +User.findOne( { include : [1] } ); +User.findOne( { where : { title : 'homework' }, include : [User] } ); +User.findOne( { where : { name : 'environment' }, include : [{ model : User, as : 'PrivateDomain' }] } ); +User.findOne( { where : { username : 'foo' }, transaction : t } ).then( ( p ) => p ); +User.findOne( { include : [User] } ); +User.findOne( { include : [{ model : User, as : 'Work' }] } ); +User.findOne( { where : { name : 'worker' }, include : [{ model : User, as : 'ToDo' }] } ); +User.findOne( { include : [{ model : User, as : 'ToDo' }, { model : User, as : 'DoTo' }] } ); +User.findOne( { where : { name : 'worker' }, include : [User] } ); +User.findOne( { where : { name : 'Boris' }, include : [User, { model : User, as : 'Photos' }] } ); +User.findOne( { where : { username : 'someone' }, include : [User] } ); +User.findOne( { where : { username : 'barfooz' }, raw : true } ); +User.findOne( { updatedAt : { ne : null } } ); +User.find( { where : { intVal : { gt : 5 } } } ); +User.find( { where : { intVal : { lte : 5 } } } ); + +User.count(); +User.count( { transaction : t } ); +User.count().then( function( c ) { c.toFixed() } ); +User.count( { where : ["username LIKE '%us%'"] } ); +User.count( { include : [{ model : User, required : false }] } ); +User.count( { distinct : true, include : [{ model : User, required : false }] } ); +User.count( { attributes : ['data'], group : ['data'] } ); +User.count( { where : { access_level : { gt : 5 } } } ); + +User.findAndCountAll( { offset : 5, limit : 1, include : [User, { model : User, as : 'a' }] } ); + +User.max( 'age', { transaction : t } ); +User.max( 'age' ); +User.max( 'age', { logging : function( sql ) { } } ); + +User.min( 'age', { transaction : t } ); +User.min( 'age' ); +User.min( 'age', { logging : function( sql ) { } } ); + +User.sum( 'order' ); +User.sum( 'age', { where : { 'gender' : 'male' } } ); +User.sum( 'age', { logging : function( sql ) { } } ); + +User.build( { username : 'John Wayne' } ).save(); +User.build(); +User.build( { id : 1, T : [{ n : 'a' }, { id : 2 }], A : { id : 1, n : 'a', c : 'a' } }, { include : [User, Task] } ); +User.build( { id : 1, }, { include : [{ model : User, as : 'followers' }, { model : Task, as : 'categories' }] } ); + +User.create(); +User.create( { createdAt : 1, updatedAt : 2 }, { silent : true } ); +User.create( {}, { returning : true } ); +User.create( { intVal : s.literal( 'CAST(1-2 AS' ) } ); +User.create( { secretValue : s.fn( 'upper', 'sequelize' ) } ); +User.create( { myvals : [1, 2, 3, 4], mystr : ['One', 'Two', 'Three', 'Four'] } ); +User.create( { name : 'Fluffy Bunny', smth : 'else' }, { logging : function( sql ) {} } ); +User.create( {}, { fields : [] } ); +User.create( { name : 'Yolo Bear', email : 'yolo@bear.com' }, { fields : ['name'] } ); +User.create( { title : 'Chair', User : { first_name : 'Mick', last_name : 'Broadstone' } }, { include : [User] } ); +User.create( { title : 'Chair', creator : { first_name : 'Matt', last_name : 'Hansen' } }, { include : [User] } ); +User.create( { id : 1, title : 'e', Tags : [{ id : 1, name : 'c' }, { id : 2, name : 'd' }] }, { include : [User] } ); +User.create( { id : 'My own ID!' } ).then( ( i ) => i.isNewRecord ); + +User.findOrInitialize( { where : { username : 'foo' } } ).then( ( p ) => p ); +User.findOrInitialize( { where : { username : 'foo' }, transaction : t } ); +User.findOrInitialize( { where : { username : 'foo' }, defaults : { foo : 'asd' }, transaction : t } ); + +User.findOrCreate( { where : { a : 'b' }, defaults : { json : { a : { b : 'c' }, d : [1, 2, 3] } } } ); +User.findOrCreate( { where : { a : 'b' }, defaults : { json : 'a', data : 'b' } } ); +User.findOrCreate( { where : { a : 'b' }, transaction : t, lock : t.LOCK.UPDATE } ); +User.findOrCreate( { where : { a : 'b' }, logging : function( sql ) { } } ); +User.findOrCreate( { where : { username : 'Username' }, defaults : { data : 'some data' }, transaction : t } ); +User.findOrCreate( { where : { objectId : 'asdasdasd' }, defaults : { username : 'gottlieb' } } ); +User.findOrCreate( { where : { id : undefined }, defaults : { name : Math.random().toString() } } ); +User.findOrCreate( { where : { email : 'unique.email.@d.com', companyId : Math.floor( Math.random() * 5 ) } } ); +User.findOrCreate( { where : { objectId : 1 }, defaults : { bool : false } } ); +User.findOrCreate( { where : 'c', defaults : {} } ); + +User.upsert( { id : 42, username : 'doe', foo : s.fn( 'upper', 'mixedCase2' ) } ); + +User.bulkCreate( [{ aNumber : 10 }, { aNumber : 12 }] ).then( ( i ) => i[0].isNewRecord ); +User.bulkCreate( [{ username : 'bar' }, { username : 'bar' }, { username : 'bar' }] ); +User.bulkCreate( [{}, {}], { validate : true, individualHooks : true } ); +User.bulkCreate( [{ style : 'ipa' }], { logging : function() { } } ); +User.bulkCreate( [{ a : 'b', c : 'd', e : 'f' }, { a : 'b', c : 'd', e : 'f' }], { fields : ['a', 'b'] } ); +User.bulkCreate( [{ name : 'foo', code : '123' }, { code : 'c' }, { name : 'bar', code : '1' }], { validate : true } ); +User.bulkCreate( [{ name : 'foo', code : '123' }, { code : '1234' }], { fields : ['code'], validate : true } ); +User.bulkCreate( [{ name : 'a', c : 'b' }, { name : 'e', c : 'f' }], { fields : ['e', 'f'], ignoreDuplicates : true } ); + +User.truncate(); + +User.destroy( { where : { client_id : 13 } } ).then( ( a ) => a.toFixed() ); +User.destroy( { force : true } ); +User.destroy( { where : {}, transaction : t } ); +User.destroy( { where : { access_level : { lt : 5 } } } ); +User.destroy( { truncate : true } ); +User.destroy( { where : {} } ); + +User.restore( { where : { secretValue : '42' } } ); + +User.update( { username : 'ruben' }, { where : {} } ); +User.update( { username : 'ruben' }, { where : { access_level : { lt : 5 } } } ); +User.update( { username : 'ruben' }, { where : { username : 'dan' } } ); +User.update( { username : 'bar' }, { where : { username : 'foo' }, transaction : t } ); +User.update( { username : 'Bill', secretValue : '43' }, { where : { secretValue : '42' }, fields : ['username'] } ); +User.update( { username : s.cast( '1', 'char' ) }, { where : { username : 'John' } } ); +User.update( { username : s.fn( 'upper', s.col( 'username' ) ) }, { where : { username : 'John' } } ); +User.update( { username : 'Bill' }, { where : { secretValue : '42' }, returning : true } ); +User.update( { secretValue : '43' }, { where : { username : 'Peter' }, limit : 1 } ); +User.update( { name : Math.random().toString() }, { where : { id : '1' } } ); +User.update( { a : { b : 10, c : 'd' } }, { where : { username : 'Jan' }, sideEffects : false } ); +User.update( { geometry : { type : 'Point', coordinates : [49.807222, -86.984722] } }, { + where : { + u : { + u : 'u', + geometry : { type : 'Point', coordinates : [49.807222, -86.984722] } + } + } +} ); +User.update( { + geometry : { + type : 'Polygon', + coordinates : [[[100.0, 0.0], [102.0, 0.0], [102.0, 1.0], [100.0, 1.0], [100.0, 0.0]]] + } +}, { + where : { + username : { + username : 'username', + geometry : { type : 'Point', coordinates : [49.807222, -86.984722] } + } + } +} ); + +User.unscoped().find( { where : { username : 'bob' } } ); +User.unscoped().count(); + +// +// Query Interface +// ~~~~~~~~~~~~~~~~~ +// +// https://github.com/sequelize/sequelize/blob/v3.4.1/test/integration/query-interface.test.js +// + +var queryInterface = s.getQueryInterface(); + +queryInterface.dropAllTables(); +queryInterface.showAllTables( { logging : function() { } } ); +queryInterface.createTable( 'table', { name : Sequelize.STRING }, { logging : function() { } } ); +queryInterface.createTable( 'skipme', { name : Sequelize.STRING } ); +queryInterface.dropAllTables( { skip : ['skipme'] } ); +queryInterface.dropTable( 'Group', { logging : function() { } } ); +queryInterface.addIndex( 'Group', ['username', 'isAdmin'], { logging : function() { } } ); +queryInterface.showIndex( 'Group', { logging : function() { } } ); +queryInterface.removeIndex( 'Group', ['username', 'isAdmin'], { logging : function() { } } ); +queryInterface.showIndex( 'Group' ); +queryInterface.createTable( 'table', { name : { type : Sequelize.STRING } }, { schema : 'schema' } ); +queryInterface.addIndex( { schema : 'a', tableName : 'c' }, ['d', 'e'], { logging : function() {} }, 'schema_table' ); +queryInterface.showIndex( { schema : 'schema', tableName : 'table' }, { logging : function() {} } ); +queryInterface.addIndex( 'Group', ['from'] ); +queryInterface.describeTable( '_Users', { logging : function() {} } ); +queryInterface.createTable( 's', { table_id : { type : Sequelize.INTEGER, primaryKey : true, autoIncrement : true } } ); +queryInterface.insert( null, 'TableWithPK', {}, { raw : true, returning : true, plain : true } ); +queryInterface.createTable( 'SomeTable', { someEnum : Sequelize.ENUM( 'value1', 'value2', 'value3' ) } ); +queryInterface.createTable( 'SomeTable', { someEnum : { type : Sequelize.ENUM, values : ['b1', 'b2', 'b3'] } } ); +queryInterface.createTable( 't', { someEnum : { type : Sequelize.ENUM, values : ['c1', 'c2', 'c3'], field : 'd' } } ); +queryInterface.createTable( 'User', { name : { type : Sequelize.STRING } }, { schema : 'hero' } ); +queryInterface.rawSelect( 'User', { schema : 'hero', logging : function() {} }, 'name' ); +queryInterface.renameColumn( '_Users', 'username', 'pseudo', { logging : function() {} } ); +queryInterface.renameColumn( { schema : 'archive', tableName : 'Users' }, 'username', 'pseudo' ); +queryInterface.renameColumn( '_Users', 'username', 'pseudo' ); +queryInterface.createTable( { tableName : 'y', schema : 'a' }, + { id : { type : Sequelize.INTEGER, primaryKey : true, autoIncrement : true }, currency : Sequelize.INTEGER } ); +queryInterface.changeColumn( { tableName : 'a', schema : 'b' }, 'c', { type : Sequelize.FLOAT }, + { logging : () => s } ); +queryInterface.createTable( 'users', { id : { type : Sequelize.INTEGER, primaryKey : true, autoIncrement : true } } ); +queryInterface.createTable( 'level', { id : { type : Sequelize.INTEGER, primaryKey : true, autoIncrement : true } } ); +queryInterface.addColumn( 'users', 'someEnum', Sequelize.ENUM( 'value1', 'value2', 'value3' ) ); +queryInterface.addColumn( 'users', 'so', { type : Sequelize.ENUM, values : ['value1', 'value2', 'value3'] } ); +queryInterface.createTable( 'hosts', { + id : { + type : Sequelize.INTEGER, + primaryKey : true, + autoIncrement : true + }, + admin : { + type : Sequelize.INTEGER, + references : { + model : User, + key : 'id' + } + }, + operator : { + type : Sequelize.INTEGER, + references : { + model : User, + key : 'id' + }, + onUpdate : 'cascade' + }, + owner : { + type : Sequelize.INTEGER, + references : { + model : User, + key : 'id' + }, + onUpdate : 'cascade', + onDelete : 'set null' + } +} ); + +// +// Query Types +// ~~~~~~~~~~~~~ +// + +s.getDialect(); +s.validate(); +s.authenticate(); +s.isDefined( '' ); +s.model( 'pp' ); +s.query( '', { raw : true } ); +s.query( '' ); +s.query( '' ).then( function( res ) {} ); +s.query( '' ).spread( function( a ) {}, function( b ) {} ); +s.query( { query : 'select ? as foo, ? as bar', values : [1, 2] }, { raw : true, replacements : [1, 2] } ); +s.query( '', { raw : true, nest : false } ); +s.query( 'select ? as foo, ? as bar', { type : this.sequelize.QueryTypes.SELECT, replacements : [1, 2] } ); +s.query( { query : 'select ? as foo, ? as bar', values : [1, 2] }, { type : s.QueryTypes.SELECT } ); +s.query( 'select :one as foo, :two as bar', { raw : true, replacements : { one : 1, two : 2 } } ); +s.transaction().then( function( t ) { s.set( { foo : 'bar' }, { transaction : t } ) } ); +s.define( 'foo', { bar : Sequelize.STRING }, { collate : 'utf8_bin' } ); +s.define( 'Foto', { name : Sequelize.STRING }, { tableName : 'photos' } ); +s.databaseVersion().then( function( version ) { } ); + +// +// Sequelize +// ~~~~~~~~~~~ +// + +new Sequelize( 'db', 'user', 'pw', { logging : false } ); +new Sequelize( 'db', 'user', 'pass', { + dialect : '', + port : 99999, + pool : {} +} ); +new Sequelize( '' ).query( '', { type : s.QueryTypes.FOREIGNKEYS, logging : function() {} } ); +new Sequelize( 'sqlite://test.sqlite' ); +new Sequelize( 'wat', 'trololo', 'wow', { port : 99999 } ); +new Sequelize( 'localhost', 'wtf', 'lol', { port : 99999 } ); +new Sequelize( 'sequelize', null, null, { + replication : { + read : { + host : 'localhost', + username : 'omg', + password : 'lol' + } + } +} ); + +s.model( 'Project' ); +s.define( 'Project', { + name : Sequelize.STRING +} ); + +var s = new Sequelize( '' ); +var testModel = s.define( 'User', { + username : Sequelize.STRING, + secretValue : Sequelize.STRING, + data : Sequelize.STRING, + intVal : Sequelize.INTEGER, + theDate : Sequelize.DATE, + aBool : Sequelize.BOOLEAN +} ); +var testModel = s.define( 'FrozenUser', {}, { freezeTableName : true } ); +s.define( 'UserWithClassAndInstanceMethods', {}, { + classMethods : { doSmth : function() { return 1; } }, + instanceMethods : { makeItSo : function() { return 2; } } +} ); +s.define( 'UserCol', { + id : { + type : Sequelize.STRING, + defaultValue : 'User', + primaryKey : true + } +} ); +s.define( 'UserWithTwoAutoIncrements', { + userid : { type : Sequelize.INTEGER, primaryKey : true, autoIncrement : true }, + userscore : { type : Sequelize.INTEGER, primaryKey : true, autoIncrement : true } +} ); +s.define( 'Foo', { + field : Sequelize.INTEGER +}, { + validate : { + field : function() {} + } +} ); +var UserTable = s.define( 'UserCol', { + aNumber : Sequelize.INTEGER, + createdAt : { + type : Sequelize.DATE, + defaultValue : new Date() + }, + updatedAt : { + type : Sequelize.DATE, + defaultValue : new Date() + } +}, { timestamps : true } ); + +s.define( 'UserCol', { + aNumber : Sequelize.INTEGER +}, { + timestamps : true, + updatedAt : 'updatedOn', + createdAt : 'dateCreated', + deletedAt : 'deletedAtThisTime', + paranoid : true +} ); +s.define( 'UpdatingUser', { + name : Sequelize.STRING +}, { + timestamps : true, + updatedAt : false, + createdAt : false, + deletedAt : 'deletedAtThisTime', + paranoid : true +} ); +s.define( 'TaskBuild', { + title : { + type : Sequelize.STRING( 50 ), + allowNull : false, + defaultValue : '' + } +}, { + setterMethods : { + title : function() { } + } +} ); +s.define( 'UserCol', { + aNumber : Sequelize.INTEGER +}, { + paranoid : true, + underscored : true +} ); + +s.define( 'UserWithUniqueUsername', { + username : { type : Sequelize.STRING, unique : { name : 'user_and_email', msg : 'User and email must be unique' } }, + email : { type : Sequelize.STRING, unique : 'user_and_email' } +} ); +s.define( 'UserWithUniqueUsername', { + user_id : { type : Sequelize.INTEGER }, + email : { type : Sequelize.STRING } +}, { + indexes : [ + { + name : 'user_and_email_index', + msg : 'User and email must be unique', + unique : true, + method : 'BTREE', + fields : ['user_id', { attribute : 'email', collate : 'en_US', order : 'DESC', length : 5 }] + }] +} ); + +s.define( 'TaskBuild', { + title : { type : Sequelize.STRING, defaultValue : 'a task!' }, + foo : { type : Sequelize.INTEGER, defaultValue : 2 }, + bar : { type : Sequelize.DATE }, + foobar : { type : Sequelize.TEXT, defaultValue : 'asd' }, + flag : { type : Sequelize.BOOLEAN, defaultValue : false } +} ); +s.define( 'ProductWithSettersAndGetters1', { + price : { + type : Sequelize.INTEGER, + get : function() { + return 'answer = ' + this.getDataValue( 'price' ); + }, + set : function( v ) { + return this.setDataValue( 'price', v + 42 ); + } + } +} ); +s.define( 'ProductWithSettersAndGetters2', { + priceInCents : Sequelize.INTEGER +}, { + setterMethods : { + price : function( value ) { + this.dataValues.priceInCents = value * 100; + } + }, + getterMethods : { + price : function() { + return '$' + (this.getDataValue( 'priceInCents' ) / 100); + }, + + priceInCents : function() { + return this.dataValues.priceInCents; + } + } +} ); + +s.define( 'post', { + title : Sequelize.STRING, + authorId : { type : Sequelize.INTEGER, references : testModel, referencesKey : 'id' } +} ); +s.define( 'post', { + title : Sequelize.STRING, + authorId : { type : Sequelize.INTEGER, references : { model : testModel, key : 'id' } } +} ); + +s.define( 'User', { + username : Sequelize.STRING, + geometry : Sequelize.GEOMETRY( 'POINT' ) +} ); + +s.define( 'ScopeMe', { + username : Sequelize.STRING, + email : Sequelize.STRING, + access_level : Sequelize.INTEGER, + other_value : Sequelize.INTEGER, + parent_id : Sequelize.INTEGER +}, { + defaultScope : { + where : { + access_level : { + gte : 5 + } + } + }, + scopes : { + isTony : { + where : { + username : 'tony' + } + }, + } +} ); +s.define( 'company', { + active : Sequelize.BOOLEAN +}, { + defaultScope : { + where : { active : true } + }, + scopes : { + notActive : { + where : { + active : false + } + }, + reversed : { + order : [['id', 'DESC']] + } + } +} ); +s.define( 'profile', { + active : Sequelize.BOOLEAN +}, { + defaultScope : { + where : { active : true } + }, + scopes : { + notActive : { + where : { + active : false + } + }, + } +} ); + +s.define( 'ScopeMe', { + username : Sequelize.STRING, + email : Sequelize.STRING, + access_level : Sequelize.INTEGER, + other_value : Sequelize.INTEGER +}, { + defaultScope : { + where : { + access_level : { + gte : 5 + } + } + }, + scopes : { + lowAccess : { + where : { + access_level : { + lte : 5 + } + } + }, + withOrder : { + order : 'username' + } + } +} ); + +s.define( 'ScopeMe', { + username : Sequelize.STRING, + email : Sequelize.STRING, + access_level : Sequelize.INTEGER, + other_value : Sequelize.INTEGER +}, { + defaultScope : { + where : { + access_level : { + gte : 5 + } + } + }, + scopes : { + lowAccess : { + where : { + access_level : { + lte : 5 + } + } + } + } +} ); + +s.define( 'user', { + id : { + type : Sequelize.INTEGER, + allowNull : false, + primaryKey : true, + autoIncrement : true, + field : 'userId' + }, + name : { + type : Sequelize.STRING, + field : 'full_name' + }, + taskCount : { + type : Sequelize.INTEGER, + field : 'task_count', + defaultValue : 0, + allowNull : false + } +}, { + tableName : 'users', + timestamps : false +} ); +s.define( 'task', { + id : { + type : Sequelize.INTEGER, + allowNull : false, + primaryKey : true, + autoIncrement : true, + field : 'taskId' + }, + title : { + type : Sequelize.STRING, + field : 'name' + } +}, { + tableName : 'tasks', + timestamps : false +} ); +s.define( 'comment', { + id : { + type : Sequelize.INTEGER, + allowNull : false, + primaryKey : true, + autoIncrement : true, + field : 'commentId' + }, + text : { + type : Sequelize.STRING, + field : 'comment_text' + }, + notes : { + type : Sequelize.STRING, + field : 'notes' + } +}, { + tableName : 'comments', + timestamps : false +} ); +s.define( 'test', { + id : { + type : Sequelize.INTEGER, + field : 'test_id', + autoIncrement : true, + primaryKey : true, + validate : { + min : 1 + } + }, + title : { + allowNull : false, + type : Sequelize.STRING( 255 ), + field : 'test_title' + } +}, { + timestamps : true, + underscored : true, + freezeTableName : true +} ); + +s.define( 'User', { + deletedAt : { + type : Sequelize.DATE, + field : 'deleted_at' + } +}, { + timestamps : true, + paranoid : true +} ); + +// +// Transaction +// ~~~~~~~~~~~~~ +// +// https://github.com/sequelize/sequelize/blob/v3.4.1/test/integration/transaction.test.js +// + +s.transaction().then( function( t ) { + + t.commit(); + t.rollback(); + + User.find( { + where : { + username : 'John' + }, + include : [User], + lock : t.LOCK.UPDATE, + transaction : t + } ); + User.find( { + where : { + username : 'John' + }, + include : [User], + lock : { + level : t.LOCK.UPDATE, + of : User + }, + transaction : t + } ); + User.update( { + active : true + }, { + where : { + active : false + }, + transaction : t + } ); + User.find( { + where : { + username : 'jan' + }, + lock : t.LOCK.NO_KEY_UPDATE, + transaction : t + } ); + User.find( { + where : { + username : 'jan' + }, + lock : t.LOCK.KEY_SHARE, + transaction : t + } ); + +} ); + +s.transaction( function() { + return Promise.resolve(); +} ); +s.transaction( { isolationLevel : 'SERIALIZABLE' }, function( t ) { return Promise.resolve(); } ); +s.transaction( { isolationLevel : s.Transaction.ISOLATION_LEVELS.SERIALIZABLE }, (t) => Promise.resolve() ); +s.transaction( { isolationLevel : s.Transaction.ISOLATION_LEVELS.READ_COMMITTED }, (t) => Promise.resolve() ); + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sequelize/sequelize-tests.ts b/sequelize/sequelize-tests-2.0.0.ts similarity index 99% rename from sequelize/sequelize-tests.ts rename to sequelize/sequelize-tests-2.0.0.ts index 8766745b8..b3a869a94 100644 --- a/sequelize/sequelize-tests.ts +++ b/sequelize/sequelize-tests-2.0.0.ts @@ -1,4 +1,4 @@ -/// +/// import Sequelize = require('sequelize'); diff --git a/sequelize/sequelize.d.ts b/sequelize/sequelize.d.ts index 1bb6be593..a97479d2b 100644 --- a/sequelize/sequelize.d.ts +++ b/sequelize/sequelize.d.ts @@ -1,1017 +1,2821 @@ -// Type definitions for Sequelize 2.0.0 dev13 +// Type definitions for Sequelize 3.4.1 // Project: http://sequelizejs.com -// Definitions by: samuelneff , Peter Harris +// Definitions by: samuelneff , Peter Harris , Ivan Drinchev // Definitions: https://github.com/borisyankov/DefinitelyTyped // Based on original work by: samuelneff -/// -/// +/// +/// +/// + +declare module "sequelize" { -declare module "sequelize" -{ module sequelize { - interface SequelizeStaticAndInstance { + + // + // Associations + // ~~~~~~~~~~~~~~ + // + // https://github.com/sequelize/sequelize/tree/v3.4.1/lib/associations + // + + /** + * Foreign Key Options + * + * @see AssociationOptions + */ + interface AssociationForeignKeyOptions extends ColumnOptions { /** - * A reference to sequelize utilities. Most users will not need to use these utils directly. However, you might want - * to use Sequelize.Utils._, which is a reference to the lodash library, if you don't already have it imported in - * your project. + * Attribute name for the relation */ - Utils: Utils; + name? : string; - /** - * A modified version of bluebird promises, that allows listening for sql events. - * - * @see Promise - */ - Promise: Promise; - - /** - * Exposes the validator.js object, so you can extend it with custom validation functions. The validator is exposed - * both on the instance, and on the constructor. - * - * @see Validator - */ - Validator: Validator; - - QueryTypes: QueryTypes; - - /** - * A general error class. - */ - Error: Error; - - /** - * Emitted when a validation fails. - * - * @see ValidationError - */ - ValidationError: ValidationError; - - /** - * Creates a object representing a database function. This can be used in search queries, both in where and order - * parts, and as default values in column definitions. If you want to refer to columns in your function, you should - * use sequelize.col, so that the columns are properly interpreted as columns and not a strings. - * - * @param fn The function you want to call. - * @param args All further arguments will be passed as arguments to the function. - */ - fn(fn: string, ...args: Array): any; - - /** - * Creates a object representing a column in the DB. This is often useful in conjunction with sequelize.fn, since - * raw string arguments to fn will be escaped. - * - * @param col The name of the column - */ - col(col: string): Col; - - /** - * Creates a object representing a call to the cast function. - * - * @param val The value to cast. - * @param type The type to cast it to. - */ - cast(val: any, type: string): Cast; - - /** - * Creates a object representing a literal, i.e. something that will not be escaped. - * - * @param val Value to convert to a literal. - */ - literal(val: any): Literal; - - /** - * An AND query. - * - * @param args Each argument (string or object) will be joined by AND. - */ - and(...args: Array): And; - - /** - * An OR query. - * - * @param args Each argument (string or object) will be joined by OR. - */ - or(...args: Array): Or; - - /** - * A way of specifying attr = condition. Mostly used internally. - * - * @param attr The attribute - * @param condition The condition. Can be both a simply type, or a further condition (.or, .and, .literal etc.) - */ - where(attr: string, condition: any): Where; } - interface SequelizeStatic extends SequelizeStaticAndInstance, DataTypes { - /** - * Instantiate sequelize with name of database and username - * @param database database name - * @param username user name - */ - new (database: string, username: string): Sequelize; + /** + * Options provided when associating models + * + * @see Association class + */ + interface AssociationOptions { /** - * Instantiate sequelize with name of database, username and password - * @param database database name - * @param username user name - * @param password password - */ - new (database: string, username: string, password: string): Sequelize; - - /** - * Instantiate sequelize with name of database, username, password, and options. - * @param database database name - * @param username user name - * @param password password - * @param options options. @see Options - */ - new (database: string, username: string, password: string, options: Options): Sequelize; - - /** - * Instantiate sequelize with name of database, username, and options. + * Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. + * For example if `User.hasOne(Profile, {onDelete: 'cascade', hooks:true})`, the before-/afterDestroy hooks + * for profile will be called when a user is deleted. Otherwise the profile will be deleted without invoking + * any hooks. * - * @param database database name - * @param username user name - * @param options options. @see Options + * Defaults to false */ - new (database: string, username: string, options: Options): Sequelize; + hooks?: boolean; /** - * Instantiate sequlize with an URI - * @param connectionString A full database URI - * @param options Options for sequelize. @see Options + * The alias of this model, in singular form. See also the `name` option passed to `sequelize.define`. If + * you create multiple associations between the same tables, you should provide an alias to be able to + * distinguish between them. If you provide an alias when creating the assocition, you should provide the + * same alias when eager loading and when getting assocated models. Defaults to the singularized name of + * target */ - new (connectionString: string, options?: Options): Sequelize; + as?: string | { singular: string, plural: string }; + + /** + * The name of the foreign key in the target table or an object representing the type definition for the + * foreign column (see `Sequelize.define` for syntax). When using an object, you can add a `name` property + * to set the name of the column. Defaults to the name of source + primary key of source + */ + foreignKey?: string | AssociationForeignKeyOptions; + + /** + * What happens when delete occurs. + * + * Cascade if this is a n:m, and set null if it is a 1:m + * + * Defaults to 'SET NULL' or 'CASCADE' + */ + onDelete?: string; + + /** + * What happens when update occurs + * + * Defaults to 'CASCADE' + */ + onUpdate?: string; + + /** + * Should on update and on delete constraints be enabled on the foreign key. + */ + constraints?: boolean; + foreignKeyConstraint?: boolean; + } - interface Sequelize extends SequelizeStaticAndInstance { - /** - * Sequelize configuration (undocumented). - */ - config: Config; + /** + * Options for Association Scope + * + * @see AssociationOptionsManyToMany + */ + interface AssociationScope { /** - * Sequelize options (undocumented). + * The name of the column that will be used for the associated scope and it's value */ - options: Options; + [scopeName: string] : any; - /** - * Models are stored here under the name given to sequelize.define - */ - models: any; - modelManager: ModelManager; - daoFactoryManager: ModelManager; - transactionManager: TransactionManager; - importCache: any; - - /** - * A reference to the sequelize transaction class. Use this to access isolationLevels when creating a transaction. - * - * @see Transaction - */ - Transaction: TransactionStatic; - - /** - * Returns the specified dialect. - */ - getDialect(): string; - - /** - * Returns the singleton instance of QueryInterface. - */ - getQueryInterface(): QueryInterface; - - /** - * Returns the singleton instance of Migrator. - * @param options Migration options - * @param force A flag that defines if the migrator should get instantiated or not. - */ - getMigrator(options?: MigratorOptions, force?: boolean): Migrator; - - /** - * Define a new model, representing a table in the DB. - * - * @param daoName The name of the entity (table). Typically specified in singular form. - * @param attributes A hash of attributes to define. Each attribute can be either a string name for the attribute - * or can be an object defining the attribute and its options. Note attributes is not fully - * typed since TypeScript does not support union types--it can be either a string or an - * options object. @see AttributeOptions. - * @param options Table options. @see DefineOptions. - */ - define(daoName: string, attributes: any, options?: DefineOptions): Model; - - /** - * Fetch a DAO factory which is already defined. - * - * @param daoName The name of a model defined with Sequelize.define. - */ - model(daoName: string): Model; - - /** - * Checks whether a model with the given name is defined. - * - * @param daoName The name of a model defined with Sequelize.define. - */ - isDefined(daoName: string): boolean; - - /** - * Imports a model defined in another file. - * - * @param path The path to the file that holds the model you want to import. If the part is relative, it will be - * resolved relatively to the calling file - */ - import(path: string): Model; - - /** - * Execute a query on the DB, with the possibility to bypass all the sequelize goodness. - * - * @param sql SQL statement to execute. - * - * @param callee If callee is provided, the selected data will be used to build an instance of the DAO represented - * by the factory. Equivalent to calling Model.build with the values provided by the query. - * - * @param options Query options. - * - * @param replacements Either an object of named parameter replacements in the format :param or an array of - * unnamed replacements to replace ? in your SQL. - */ - query(sql: string, callee?: Model, options?: QueryOptions, replacements?: any): EventEmitter; - - query(sql: string, callee?: Model, options?: QueryOptions): EventEmitterT>; - - /** - * Create a new database schema. - * - * @param schema Name of the schema. - */ - createSchema(schema: string): EventEmitter; - - /** - * Show all defined schemas. - */ - showAllSchemas(): EventEmitter; - - /** - * Drop a single schema. - * - * @param schema Name of the schema. - */ - dropSchema(schema: string): EventEmitter; - - /** - * Drop all schemas. - */ - dropAllSchemas(): EventEmitter; - - /** - * Sync all defined DAOs to the DB. - * - * @param options Options. - */ - sync(options?: SyncOptions): EventEmitter; - - /** - * Drop all tables defined through this sequelize instance. This is done by calling Model.drop on each model. - * - * @param options The options passed to each call to Model.drop. - */ - drop(options: DropOptions): EventEmitter; - - /** - * Test the connection by trying to authenticate. Alias for 'validate'. - */ - authenticate(): EventEmitter; - - /** - * Alias for authenticate(). Test the connection by trying to authenticate. Alias for 'validate'. - */ - validate(): EventEmitter; - - /** - * !! DEPRECATED : When passing a callback to a transaction a promise chain is expected in return, - * the transaction will be committed or rejected based on the promise chain returned to the callback. - * - * Start a transaction. When using transactions, you should pass the transaction in the options argument in order - * for the query to happen under that transaction. - * - * @param callback Called when the transaction has been set up and is ready for use. Callback takes transaction - * argument (overload available for error and transaction arguments too). - */ - transaction(callback: (transaction: Transaction) => boolean): Promise; - - /** - * Start a transaction. When using transactions, you should pass the transaction in the options argument in order - * for the query to happen under that transaction. - * - * @param options Transaction options. - * @param callback Called when the transaction has been set up and is ready for use. Callback takes transaction - * argument (overload available for error and transaction arguments too). - */ - transaction(options?: TransactionOptions, callback?: (transaction: Transaction) => void): PromiseT; - - close(): void; } - interface Config { - database?: string; - username?: string; - password?: string; - host?: string; - port?: number; - pool?: PoolOptions; - protocol?: string; - queue?: boolean; - native?: boolean; - ssl?: boolean; - replication?: ReplicationOptions; - dialectModulePath?: string; - maxConcurrentQueries?: number; - dialectOptions?: any; + /** + * Options provided for many-to-many relationships + * + * @see AssociationOptionsHasMany + * @see AssociationOptionsBelongsToMany + */ + interface AssociationOptionsManyToMany extends AssociationOptions { + + /** + * A key/value set that will be used for association create and find defaults on the target. + * (sqlite not supported for N:M) + */ + scope? : AssociationScope; + } - interface Model extends Hooks, Associations { - /** - * A reference to the sequelize instance. - */ - sequelize: Sequelize; + /** + * Options provided when associating models with hasOne relationship + * + * @see Association class hasOne method + */ + interface AssociationOptionsHasOne extends AssociationOptions { /** - * The name of the model, typically singular. + * A string or a data type to represent the identifier in the table */ - name: string; + keyType?: DataTypeAbstract; - /** - * The name of the underlying database table, typically plural. - */ - tableName: string; - - options: DefineOptions; - attributes: any; - rawAttributes: any; - modelManager: ModelManager; - daoFactoryManager: ModelManager; - associations: any; - scopeObj: any; - - /** - * Sync this Model to the DB, that is create the table. Upon success, the callback will be called with the model - * instance (this). - */ - sync(options?: SyncOptions): PromiseT>; - - /** - * Drop the table represented by this Model. - * - * @param options - */ - drop(options?: DropOptions): Promise; - - /** - * Apply a schema to this model. For postgres, this will actually place the schema in front of the table name - - * "schema"."tableName", while the schema will be prepended to the table name for mysql and sqlite - - * 'schema.tablename'. - * - * @param schema The name of the schema. - * @param options Schema options. - */ - schema(schema: string, options?: SchemaOptions): Model; - - /** - * Get the tablename of the model, taking schema into account. The method will return The name as a string if the - * model has no schema, or an object with tableName, schema and delimiter properties. - */ - getTableName(): any; - - /** - * Apply a scope created in define to the model. - * - * @param options The scope(s) to apply. Scopes can either be passed as consecutive arguments, or as an array of - * arguments. To apply simple scopes, pass them as strings. For scope function, pass an object, - * with a method property. The value can either be a string, if the method does not take any - * arguments, or an array, where the first element is the name of the method, and consecutive - * elements are arguments to that method. Pass null to remove all scopes, including the default. - */ - scope(options: any): Model; - - /** - * Search for multiple instances.. - * - * @param options A hash of options to describe the scope of the search. - * @param queryOptions Set the query options, e.g. raw, specifying that you want raw data instead of built - * Instances. See sequelize.query for options. - */ - findAll(options?: FindOptions, queryOptions?: QueryOptions): PromiseT>; - - /** - * Search for a single instance. This applies LIMIT 1, so the listener will always be called with a single instance. - * - * @param options A hash of options to describe the scope of the search. - * @param queryOptions Set the query options, e.g. raw, specifying that you want raw data instead of built - * Instances. See sequelize.query for options - */ - find(options?: FindOptions, queryOptions?: QueryOptions): PromiseT; - - /** - * Search for a single instance. This applies LIMIT 1, so the listener will always be called with a single instance. - * - * @param options A number to search by id. - * @param queryOptions Set the query options, e.g. raw, specifying that you want raw data instead of built - * Instances. See sequelize.query for options - */ - find(id?: number, queryOptions?: QueryOptions): PromiseT; - - /** - * Run an aggregation method on the specified field. - * - * @param field The field to aggregate over. Can be a field name or *. - * @param aggregateFunction The function to use for aggregation, e.g. sum, max etc. - * @param options Query options, particularly options.dataType. - */ - aggregate(field: string, aggregateFunction: string, options: FindOptions): PromiseT; - - /** - * Count the number of records matching the provided where clause. - * - * @param options Conditions and options for the query. - */ - count(options?: FindOptions): PromiseT; - - /** - * Find all the rows matching your query, within a specified offset / limit, and get the total number of rows - * matching your query. This is very usefull for paging. - * - * @param findOptions Filtering options - * @param queryOptions Query options - */ - findAndCountAll(findOptions?: FindOptions, queryOptions?: QueryOptions): PromiseT>; - - /** - * Find the maximum value of field. - * - * @param field - * @param options - */ - max(field: string, options?: FindOptions): PromiseT; - - /** - * Find the minimum value of field. - * - * @param field - * @param options - */ - min(field: string, options?: FindOptions): PromiseT; - - /** - * Find the sum of field. - * - * @param field - * @param options - */ - sum(field: string, options?: FindOptions): PromiseT; - - /** - * Builds a new model instance. Values is an object of key value pairs, must be defined but can be empty. - * - * @param values any from which to build entity instance. - * @param options any construction options. - */ - build(values: TPojo, options?: BuildOptions): TInstance; - - /** - * Builds a new model instance and calls save on it.. - * - * @param values - * @param options - */ - create(values: TPojo, options?: CopyOptions): PromiseT; - - /** - * Find a row that matches the query, or build (but don't save) the row if none is found. The successfull result - * of the promise will be (instance, initialized) - Make sure to use .spread(). - * - * @param where A hash of search attributes. Note that this method differs from finders, in that the syntax - * is { attr1: 42 } and NOT { where: { attr1: 42}}. This may be subject to change in 2.0 - * @param defaults Default values to use if building a new instance - * @param options Options passed to the find call - */ - findOrInitialize(where: any, defaults?: TPojo, options?: QueryOptions): PromiseT; - - /** - * Find a row that matches the query, or build and save the row if none is found The successfull result of the - * promise will be (instance, created) - Make sure to use .spread(). - * - * @param where A hash of search attributes. Note that this method differs from finders, in that the syntax is - * { attr1: 42 } and NOT { where: { attr1: 42}}. This is subject to change in 2.0 - * @param defaults Default values to use if creating a new instance - * @param options Options passed to the find and create calls. - */ - findOrCreate(where: any, defaults?: TPojo, options?: FindOrCreateOptions): PromiseT; - - /** - * Create and insert multiple instances in bulk. - * - * @param records List of objects (key/value pairs) to create instances from. - * @param options - */ - bulkCreate(records: Array, options?: BulkCreateOptions): PromiseT>; - - /** - * Delete multiple instances. - */ - destroy(where?: any, options?: DestroyOptions): Promise; - - /** - * Update multiple instances that match the where options. - * - * @param attrValueHash A hash of fields to change and their new values - * @param where Options to describe the scope of the search. Note that these options are not wrapped in a - * { where: ... } is in find / findAll calls etc. This is probably due to change in 2.0. - */ - update(attrValueHash: TPojo, where: any, options?: UpdateOptions): Promise; - - /** - * Run a describe query on the table. The result will be return to the listener as a hash of attributes and their - * types. - */ - describe(): PromiseT; - - /** - * A proxy to the node-sql query builder, which allows you to build your query through a chain of method calls. - * The returned instance already has all the fields property populated with the field of the model. - */ - dataset(): any; } - interface Instance { - /** - * Returns true if this instance has not yet been persisted to the database. - */ - isNewRecord: boolean; + /** + * Options provided when associating models with belongsTo relationship + * + * @see Association class belongsTo method + */ + interface AssociationOptionsBelongsTo extends AssociationOptions { /** - * Returns the Model the instance was created from. + * The name of the field to use as the key for the association in the target table. Defaults to the primary + * key of the target table */ - Model: Model; + targetKey? : string; /** - * A reference to the sequelize instance. + * A string or a data type to represent the identifier in the table */ - sequelize: Sequelize; + keyType?: DataTypeAbstract; - /** - * If timestamps and paranoid are enabled, returns whether the deletedAt timestamp of this instance is set. - * Otherwise, always returns false. - */ - isDeleted: boolean; - - /** - * Get the values of this Instance. Proxies to this.get. - */ - values: TPojo; - - /** - * A getter for this.changed(). Returns true if any keys have changed. - */ - isDirty: boolean; - - /** - * Get the values of the primary keys of this instance. - */ - primaryKeyValues: TPojo; - - /** - * Get the value of the underlying data value. - * - * @param key Field to retrieve. - */ - getDataValue(key: string): any; - - /** - * Update the underlying data value. - * - * @param key Field to set. - * @param value Value to set. - */ - setDataValue(key: string, value: any): void; - - /** - * Retrieves the value for the key when specified. If no key is given, returns all values of the instance, also - * invoking virtual getters. - */ - get(key?: string): any; - - /** - * Set is used to update values on the instance (the sequelize representation of the instance that is, remember - * that nothing will be persisted before you actually call save). - */ - set(key: string, value: any, options?: SetOptions): void; - - /** - * If changed is called with a string it will return a boolean indicating whether the value of that key in - * dataValues is different from the value in _previousDataValues. If changed is called without an argument, it will - * return an array of keys that have changed. - */ - changed(key: string): any; - - /** - * If changed is called with a string it will return a boolean indicating whether the value of that key in - * dataValues is different from the value in _previousDataValues. If changed is called without an argument, it will - * return an array of keys that have changed. - */ - changed(): Array; - - /** - * Returns the previous value for key from _previousDataValues. - */ - previous(key: string): any; - - /** - * Validate this instance, and if the validation passes, persist it to the database. - */ - save(fields?: Array, options?: SaveOptions): PromiseT; - - /** - * Refresh the current instance in-place, i.e. update the object with current data from the DB and return the same - * object. This is different from doing a find(Instance.id), because that would create and return a new instance. - * With this method, all references to the Instance are updated with the new data and no new objects are created. - */ - reload(options?: FindOptions): PromiseT; - - /** - * Validate the attribute of this instance according to validation rules set in the model definition. - */ - validate(options?: ValidateOptions): PromiseT; - - /** - * This is the same as calling setAttributes, then calling save. - */ - updateAttributes(updates: TPojo, options: SaveOptions): PromiseT; - - /** - * Destroy the row corresponding to this instance. Depending on your setting for paranoid, the row will either be - * completely deleted, or have its deletedAt timestamp set to the current time. - * - * @param options Allows caller to specify if delete should be forced. - */ - destroy(options?: DestroyInstanceOptions): Promise; - - /** - * Increment the value of one or more columns. This is done in the database, which means it does not use the - * values currently stored on the Instance. - * - * @param fields If a string is provided, that column is incremented by the value of by given in options. If an - * array is provided, the same is true for each column. If and object is provided, each column is - * incremented by the value given. - * @param options Increment options. - */ - increment(fields: any, options?: IncrementOptions): Promise; - - /** - * Decrement the value of one or more columns. This is done in the database, which means it does not use the - * values currently stored on the Instance. - * - * @param fields If a string is provided, that column is decremented by the value of by given in options. If an - * array is provided, the same is true for each column. If and object is provided, each column is - * decremented by the value given. - * @param options Decrement options. - */ - decrement(fields: any, options?: IncrementOptions): Promise; - - /** - * Check whether all values of this and other Instance are the same. - */ - equal(other: TInstance): boolean; - - /** - * Check if this is eqaul to one of others by calling equals. - * - * @param others Other instances to compare to. - */ - equalsOneOf(others: Array): boolean; - - /** - * Convert the instance to a JSON representation. Proxies to calling get with no keys. This means get all values - * gotten from the DB, and apply all custom getters. - */ - toJSON(): TPojo; } - interface Transaction extends TransactionStatic { - /** - * Commit the transaction. - */ - commit(): Transaction; + /** + * Options provided when associating models with hasMany relationship + * + * @see Association class hasMany method + */ + interface AssociationOptionsHasMany extends AssociationOptionsManyToMany { /** - * Rollback (abort) the transaction. + * A string or a data type to represent the identifier in the table */ - rollback(): Transaction; + keyType?: DataTypeAbstract; + } - interface TransactionStatic { - /** - * The possible isolation levels to use when starting a transaction - */ - ISOLATION_LEVELS: TransactionIsolationLevels; + /** + * Options provided when associating models with belongsToMany relationship + * + * @see Association class belongsToMany method + */ + interface AssociationOptionsBelongsToMany extends AssociationOptionsManyToMany { /** - * Possible options for row locking. Used in conjuction with find calls. - */ - LOCK: TransactionLocks; - } - - interface TransactionIsolationLevels { - READ_UNCOMMITTED: string;// "READ UNCOMMITTED" - READ_COMMITTED: string; // "READ COMMITTED" - REPEATABLE_READ: string; // "REPEATABLE READ" - SERIALIZABLE: string; // "SERIALIZABLE" - } - - interface TransactionLocks { - UPDATE: string; // UPDATE - SHARE: string; // SHARE - } - - interface Hooks { - - /** - * Add a named hook to the model. + * The name of the table that is used to join source and target in n:m associations. Can also be a + * sequelize + * model if you want to define the junction table yourself and add extra attributes to it. * - * @param hooktype - */ - addHook(hooktype: string, name: string, fn: (...args: Array) => void): boolean; - - /** - * Add a hook to the model. + * In 3.4.1 version of Sequelize, hasMany's use of through gives an error, and on the other hand through + * option for belongsToMany has been made required. * - * @param hooktype + * @see https://github.com/sequelize/sequelize/blob/v3.4.1/lib/associations/has-many.js + * @see https://github.com/sequelize/sequelize/blob/v3.4.1/lib/associations/belongs-to-many.js */ - addHook(hooktype: string, fn: (...args: Array) => void): boolean; + through : Model | string | ThroughOptions; /** - * A named hook that is run before validation. + * The name of the foreign key in the join table (representing the target model) or an object representing + * the type definition for the other column (see `Sequelize.define` for syntax). When using an object, you + * can add a `name` property to set the name of the colum. Defaults to the name of target + primary key of + * target */ - beforeValidate(name: string, validator: (dao: T, callback: (err?: Error) => void) => void): void; + otherKey? : string | AssociationForeignKeyOptions; - /** - * A hook that is run before validation. - */ - beforeValidate(validator: (dao: T, callback: (err?: Error) => void) => void): void; - - /** - * A named hook that is run before validation. - */ - afterValidate(name: string, validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; - - /** - * A hook that is run before validation. - */ - afterValidate(validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; - - /** - * A named hook that is run before creating a single instance. - */ - beforeCreate(name: string, validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; - - /** - * A hook that is run before creating a single instance. - */ - beforeCreate(validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; - - /** - * A named hook that is run after creating a single instance. - */ - afterCreate(name: string, validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; - - /** - * A hook that is run after creating a single instance. - */ - afterCreate(validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; - - /** - * A named hook that is run before destroying a single instance. - */ - beforeDestroy(name: string, validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; - - /** - * A hook that is run before destroying a single instance. - */ - beforeDestroy(validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; - - /** - * A named hook that is run after destroying a single instance. - */ - afterDestroy(name: string, validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; - - /** - * A hook that is run after destroying a single instance. - */ - afterDestroy(validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; - - /** - * A named hook that is run before updating a single instance. - */ - beforeUpdate(name: string, validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; - - /** - * A hook that is run before updating a single instance. - */ - beforeUpdate(validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; - - /** - * A named hook that is run after updating a single instance. - */ - afterUpdate(name: string, validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; - - /** - * A hook that is run after updating a single instance. - */ - afterUpdate(validator: (dao: T, callback: (err?: Error, dao?: T) => void) => void): void; - - /** - * A named hook that is run before creating instances in bulk. - */ - beforeBulkCreate(name: string, validator: (daos: Array, fields: Array, callback: (err?: Error, dao?: T) => void) => void): void; - - /** - * A hook that is run before creating instances in bulk. - */ - beforeBulkCreate(validator: (daos: Array, fields: Array, callback: (err?: Error, dao?: T) => void) => void): void; - - /** - * A named hook that is run after creating instances in bulk. - */ - afterBulkCreate(name: string, validator: (daos: Array, fields: Array, callback: (err?: Error, dao?: T) => void) => void): void; - - /** - * A hook that is run after creating instances in bulk. - */ - afterBulkCreate(validator: (daos: Array, fields: Array, callback: (err?: Error, dao?: T) => void) => void): void; - - /** - * A named hook that is run before destroying instances in bulk. - */ - beforeBulkDestroy(name: string, validator: (where: any, callback: (err?: Error, where?: any) => void) => void): void; - - /** - * A hook that is run before destroying instances in bulk. - */ - beforeBulkDestroy(validator: (where: any, callback: (err?: Error, where?: any) => void) => void): void; - - /** - * A named hook that is run after destroying instances in bulk. - */ - afterBulkDestroy(name: string, validator: (where: any, callback: (err?: Error, where?: any) => void) => void): void; - - /** - * A hook that is run after destroying instances in bulk. - */ - afterBulkDestroy(validator: (where: any, callback: (err?: Error, where?: any) => void) => void): void; - - /** - * A named hook that is run before updating instances in bulk. - */ - beforeBulkUpdate(name: string, validator: (instances: Array, where: any, callback: (err?: Error, instances?: Array, where?: any) => void) => void): void; - - /** - * A hook that is run before updating instances in bulk. - */ - beforeBulkUpdate(validator: (instances: Array, where: any, callback: (err?: Error, instances?: Array, where?: any) => void) => void): void; - - /** - * A named hook that is run after updating instances in bulk. - */ - afterBulkUpdate(name: string, validator: (instances: Array, where: any, callback: (err?: Error, instances?: Array, where?: any) => void) => void): void; - - /** - * A hook that is run after updating instances in bulk. - */ - afterBulkUpdate(validator: (instances: Array, where: any, callback: (err?: Error, instances?: Array, where?: any) => void) => void): void; } + /** + * Used for a association table in n:m associations. + * + * @see AssociationOptionsBelongsToMany + */ + interface ThroughOptions { + + /** + * The model used to join both sides of the N:M association. + */ + model : Model; + + /** + * A key/value set that will be used for association create and find defaults on the through model. + * (Remember to add the attributes to the through model) + */ + scope? : AssociationScope; + + /** + * If true a unique key will be generated from the foreign keys used (might want to turn this off and create + * specific unique keys when using scopes) + * + * Defaults to true + */ + unique? : boolean; + + } + + /** + * Creating assocations in sequelize is done by calling one of the belongsTo / hasOne / hasMany functions on a + * model (the source), and providing another model as the first argument to the function (the target). + * + * * hasOne - adds a foreign key to target + * * belongsTo - add a foreign key to source + * * hasMany - adds a foreign key to target, unless you also specify that target hasMany source, in which case + * a + * junction table is created with sourceId and targetId + * + * Creating an association will add a foreign key constraint to the attributes. All associations use `CASCADE` + * on update and `SET NULL` on delete, except for n:m, which also uses `CASCADE` on delete. + * + * When creating associations, you can provide an alias, via the `as` option. This is useful if the same model + * is associated twice, or you want your association to be called something other than the name of the target + * model. + * + * As an example, consider the case where users have many pictures, one of which is their profile picture. All + * pictures have a `userId`, but in addition the user model also has a `profilePictureId`, to be able to easily + * load the user's profile picture. + * + * ```js + * User.hasMany(Picture) + * User.belongsTo(Picture, { as: 'ProfilePicture', constraints: false }) + * + * user.getPictures() // gets you all pictures + * user.getProfilePicture() // gets you only the profile picture + * + * User.findAll({ + * where: ..., + * include: [ + * { model: Picture }, // load all pictures + * { model: Picture, as: 'ProfilePicture' }, // load the profile picture. Notice that the spelling must be + * the exact same as the one in the association + * ] + * }) + * ``` + * To get full control over the foreign key column added by sequelize, you can use the `foreignKey` option. It + * can either be a string, that specifies the name, or and object type definition, + * equivalent to those passed to `sequelize.define`. + * + * ```js + * User.hasMany(Picture, { foreignKey: 'uid' }) + * ``` + * + * The foreign key column in Picture will now be called `uid` instead of the default `userId`. + * + * ```js + * User.hasMany(Picture, { + * foreignKey: { + * name: 'uid', + * allowNull: false + * } + * }) + * ``` + * + * This specifies that the `uid` column can not be null. In most cases this will already be covered by the + * foreign key costraints, which sequelize creates automatically, but can be useful in case where the foreign + * keys are disabled, e.g. due to circular references (see `constraints: false` below). + * + * When fetching associated models, you can limit your query to only load some models. These queries are + * written + * in the same way as queries to `find`/`findAll`. To only get pictures in JPG, you can do: + * + * ```js + * user.getPictures({ + * where: { + * format: 'jpg' + * } + * }) + * ``` + * + * There are several ways to update and add new assoications. Continuing with our example of users and + * pictures: + * ```js + * user.addPicture(p) // Add a single picture + * user.setPictures([p1, p2]) // Associate user with ONLY these two picture, all other associations will be + * deleted user.addPictures([p1, p2]) // Associate user with these two pictures, but don't touch any current + * associations + * ``` + * + * You don't have to pass in a complete object to the association functions, if your associated model has a + * single primary key: + * + * ```js + * user.addPicture(req.query.pid) // Here pid is just an integer, representing the primary key of the picture + * ``` + * + * In the example above we have specified that a user belongs to his profile picture. Conceptually, this might + * not make sense, but since we want to add the foreign key to the user model this is the way to do it. + * + * Note how we also specified `constraints: false` for profile picture. This is because we add a foreign key + * from user to picture (profilePictureId), and from picture to user (userId). If we were to add foreign keys + * to both, it would create a cyclic dependency, and sequelize would not know which table to create first, + * since user depends on picture, and picture depends on user. These kinds of problems are detected by + * sequelize before the models are synced to the database, and you will get an error along the lines of `Error: + * Cyclic dependency found. 'users' is dependent of itself`. If you encounter this, you should either disable + * some constraints, or rethink your associations completely. + * + * @see Sequelize.Model + */ interface Associations { - /** - * Creates an association between this (the source) and the provided target. The foreign key is added on the target. - * - * @param target - * @param options - */ - hasOne(target: Model, options?: AssociationOptions): void; /** - * Creates an association between this (the source) and the provided target. The foreign key is added on the source. + * Creates an association between this (the source) and the provided target. The foreign key is added + * on the target. * - * @param target - * @param options + * Example: `User.hasOne(Profile)`. This will add userId to the profile table. + * + * @param target The model that will be associated with hasOne relationship + * @param options Options for the association */ - belongsTo(target: Model, options?: AssociationOptions): void; + hasOne( target : Model, options? : AssociationOptionsHasOne ): void; /** - * Creates an association to connect sources with multiple targets. Furthermore the targets can also have connections to multiple sources. + * Creates an association between this (the source) and the provided target. The foreign key is added on the + * source. * - * @param target - * @param options + * Example: `Profile.belongsTo(User)`. This will add userId to the profile table. + * + * @param target The model that will be associated with hasOne relationship + * @param options Options for the association */ - belongsToMany(target: Model, options?: AssociationOptions): void; + belongsTo( target : Model, options? : AssociationOptionsBelongsTo ) : void; /** * Create an association that is either 1:m or n:m. * - * @param target - * @param options + * ```js + * // Create a 1:m association between user and project + * User.hasMany(Project) + * ``` + * ```js + * // Create a n:m association between user and project + * User.hasMany(Project) + * Project.hasMany(User) + * ``` + * By default, the name of the join table will be source+target, so in this case projectsusers. This can be + * overridden by providing either a string or a Model as `through` in the options. If you use a through + * model with custom attributes, these attributes can be set when adding / setting new associations in two + * ways. Consider users and projects from before with a join table that stores whether the project has been + * started yet: + * ```js + * var UserProjects = sequelize.define('userprojects', { + * started: Sequelize.BOOLEAN + * }) + * User.hasMany(Project, { through: UserProjects }) + * Project.hasMany(User, { through: UserProjects }) + * ``` + * ```js + * jan.addProject(homework, { started: false }) // The homework project is not started yet + * jan.setProjects([makedinner, doshopping], { started: true}) // Both shopping and dinner have been + * started + * ``` + * + * If you want to set several target instances, but with different attributes you have to set the + * attributes on the instance, using a property with the name of the through model: + * + * ```js + * p1.userprojects { + * started: true + * } + * user.setProjects([p1, p2], {started: false}) // The default value is false, but p1 overrides that. + * ``` + * + * Similarily, when fetching through a join table with custom attributes, these attributes will be + * available as an object with the name of the through model. + * ```js + * user.getProjects().then(function (projects) { + * var p1 = projects[0] + * p1.userprojects.started // Is this project started yet? + * }) + * ``` + * + * @param target The model that will be associated with hasOne relationship + * @param options Options for the association */ - hasMany(target: Model, options?: AssociationOptions): void; + hasMany( target : Model, options? : AssociationOptionsHasMany ) : void; + + /** + * Create an N:M association with a join table + * + * ```js + * User.belongsToMany(Project) + * Project.belongsToMany(User) + * ``` + * By default, the name of the join table will be source+target, so in this case projectsusers. This can be + * overridden by providing either a string or a Model as `through` in the options. + * + * If you use a through model with custom attributes, these attributes can be set when adding / setting new + * associations in two ways. Consider users and projects from before with a join table that stores whether + * the project has been started yet: + * ```js + * var UserProjects = sequelize.define('userprojects', { + * started: Sequelize.BOOLEAN + * }) + * User.belongsToMany(Project, { through: UserProjects }) + * Project.belongsToMany(User, { through: UserProjects }) + * ``` + * ```js + * jan.addProject(homework, { started: false }) // The homework project is not started yet + * jan.setProjects([makedinner, doshopping], { started: true}) // Both shopping and dinner has been started + * ``` + * + * If you want to set several target instances, but with different attributes you have to set the + * attributes on the instance, using a property with the name of the through model: + * + * ```js + * p1.userprojects { + * started: true + * } + * user.setProjects([p1, p2], {started: false}) // The default value is false, but p1 overrides that. + * ``` + * + * Similarily, when fetching through a join table with custom attributes, these attributes will be + * available as an object with the name of the through model. + * ```js + * user.getProjects().then(function (projects) { + * var p1 = projects[0] + * p1.userprojects.started // Is this project started yet? + * }) + * ``` + * + * @param target The model that will be associated with hasOne relationship + * @param options Options for the association + * + */ + belongsToMany( target : Model, options : AssociationOptionsBelongsToMany ) : void; + + } + + // + // DataTypes + // ~~~~~~~~~~~ + // + // https://github.com/sequelize/sequelize/blob/v3.4.1/lib/data-types.js + // + + /** + * Abstract DataType interface. Use this if you want to create an interface that has a value any of the + * DataTypes that Sequelize supports. + */ + interface DataTypeAbstract { + + /** + * Although this is not needed for the definitions itself, we want to make sure that DataTypeAbstract is not + * something than can be evaluated to an empty object. + */ + dialectTypes : string; + + } + + interface DataTypeAbstractString extends DataTypeAbstract { + + /** + * A variable length string. Default length 255 + */ + ( options? : { length: number } ) : T; + ( length : number ) : T; + + /** + * Property BINARY for the type + */ + BINARY : T; + + } + + interface DataTypeString extends DataTypeAbstractString { } + + interface DataTypeChar extends DataTypeAbstractString { } + + interface DataTypeText extends DataTypeAbstract { + + /** + * Length of the text field. + * + * Available lengths: `tiny`, `medium`, `long` + */ + ( options? : { length: string } ) : DataTypeText; + ( length : string ) : DataTypeText; + + } + + interface DataTypeAbstractNumber extends DataTypeAbstract { + UNSIGNED : T; + ZEROFILL : T; + } + + interface DataTypeNumber extends DataTypeAbstractNumber { } + + interface DataTypeInteger extends DataTypeAbstractNumber { + + /** + * Length of the number field. + */ + ( options? : { length: number } ) : DataTypeInteger; + ( length : number ) : DataTypeInteger; + + } + + interface DataTypeBigInt extends DataTypeAbstractNumber { + + /** + * Length of the number field. + */ + ( options? : { length: number } ) : DataTypeBigInt; + ( length : number ) : DataTypeBigInt; + + } + + interface DataTypeFloat extends DataTypeAbstractNumber { + + /** + * Length of the number field and decimals of the float + */ + ( options? : { length: number, decimals?: number } ) : DataTypeFloat; + ( length : number, decimals? : number ) : DataTypeFloat; + + } + + interface DataTypeReal extends DataTypeAbstractNumber { + + /** + * Length of the number field and decimals of the real + */ + ( options? : { length: number, decimals?: number } ) : DataTypeReal; + ( length : number, decimals? : number ) : DataTypeReal; + + } + + interface DataTypeDouble extends DataTypeAbstractNumber { + + /** + * Length of the number field and decimals of the real + */ + ( options? : { length: number, decimals?: number } ) : DataTypeDouble; + ( length : number, decimals? : number ) : DataTypeDouble; + + } + + interface DataTypeDecimal extends DataTypeAbstractNumber { + + /** + * Precision and scale for the decimal number + */ + ( options? : { precision: number, scale?: number } ) : DataTypeDecimal; + ( precision : number, scale? : number ) : DataTypeDecimal; + + } + + interface DataTypeBoolean extends DataTypeAbstract { } + + interface DataTypeTime extends DataTypeAbstract { } + + interface DataTypeDate extends DataTypeAbstract { } + + interface DataTypeDateOnly extends DataTypeAbstract { } + + interface DataTypeHStore extends DataTypeAbstract { } + + interface DataTypeJSONType extends DataTypeAbstract { } + + interface DataTypeJSONB extends DataTypeAbstract { } + + interface DataTypeNow extends DataTypeAbstract { } + + interface DataTypeBlob extends DataTypeAbstract { + + /** + * Length of the blob field. + * + * Available lengths: `tiny`, `medium`, `long` + */ + ( options? : { length: string } ) : DataTypeBlob; + ( length : string ) : DataTypeBlob; + + } + + interface DataTypeRange extends DataTypeAbstract { + + /** + * Range field for Postgre + * + * Accepts subtype any of the ranges + */ + ( options? : { subtype: DataTypeAbstract } ) : DataTypeRange; + ( subtype : DataTypeAbstract ) : DataTypeRange; + + } + + interface DataTypeUUID extends DataTypeAbstract { } + + interface DataTypeUUIDv1 extends DataTypeAbstract { } + + interface DataTypeUUIDv4 extends DataTypeAbstract { } + + interface DataTypeVirtual extends DataTypeAbstract { } + + interface DataTypeEnum extends DataTypeAbstract { + + /** + * Enum field + * + * Accepts values + */ + ( options? : { values: string | string[] } ) : DataTypeEnum; + ( values : string | string[] ) : DataTypeEnum; + ( ...args : string[] ) : DataTypeEnum; + + } + + interface DataTypeArray extends DataTypeAbstract { + + /** + * Array field for Postgre + * + * Accepts type any of the DataTypes + */ + ( options : { type: DataTypeAbstract } ) : DataTypeArray; + ( type : DataTypeAbstract ) : DataTypeArray; + + } + + interface DataTypeGeometry extends DataTypeAbstract { + + /** + * Geometry field for Postgres + */ + ( type : string, srid? : number ) : DataTypeGeometry; + } /** - * Extension of external project that doesn't have definitions. + * A convenience class holding commonly used data types. The datatypes are used when definining a new model + * using + * `Sequelize.define`, like this: * - * See https://github.com/chriso/validator.js and https://github.com/sequelize/sequelize/blob/master/lib/instance-validator.js + * ```js + * sequelize.define('model', { + * column: DataTypes.INTEGER + * }) + * ``` + * When defining a model you can just as easily pass a string as type, but often using the types defined here + * is + * beneficial. For example, using `DataTypes.BLOB`, mean that that column will be returned as an instance of + * `Buffer` when being fetched by sequelize. + * + * Some data types have special properties that can be accessed in order to change the data type. + * For example, to get an unsigned integer with zerofill you can do `DataTypes.INTEGER.UNSIGNED.ZEROFILL`. + * The order you access the properties in do not matter, so `DataTypes.INTEGER.ZEROFILL.UNSIGNED` is fine as + * well. The available properties are listed under each data type. + * + * To provide a length for the data type, you can invoke it like a function: `INTEGER(2)` + * + * Three of the values provided here (`NOW`, `UUIDV1` and `UUIDV4`) are special default values, that should not + * be used to define types. Instead they are used as shorthands for defining default values. For example, to + * get a uuid field with a default value generated following v1 of the UUID standard: + * + * ```js + * sequelize.define('model', { + * uuid: { + * type: DataTypes.UUID, + * defaultValue: DataTypes.UUIDV1, + * primaryKey: true + * } + * }) + * ``` */ - interface Validator { + interface DataTypes { + ABSTRACT : DataTypeAbstract; + STRING : DataTypeString; + CHAR : DataTypeChar; + TEXT : DataTypeText; + NUMBER : DataTypeNumber; + INTEGER : DataTypeInteger; + BIGINT : DataTypeBigInt; + FLOAT : DataTypeFloat; + TIME : DataTypeTime; + DATE : DataTypeDate; + DATEONLY: DataTypeDateOnly; + BOOLEAN: DataTypeBoolean; + NOW: DataTypeNow; + BLOB: DataTypeBlob; + DECIMAL: DataTypeDecimal; + NUMERIC: DataTypeDecimal; + UUID: DataTypeUUID; + UUIDV1: DataTypeUUIDv1; + UUIDV4: DataTypeUUIDv4; + HSTORE: DataTypeHStore; + JSON: DataTypeJSONType; + JSONB: DataTypeJSONB; + VIRTUAL: DataTypeVirtual; + ARRAY: DataTypeArray; + NONE: DataTypeVirtual; + ENUM: DataTypeEnum; + RANGE: DataTypeRange; + REAL: DataTypeReal; + DOUBLE: DataTypeDouble, + 'DOUBLE PRECISION': DataTypeDouble, + GEOMETRY: DataTypeGeometry + } + + // + // Deferrable + // ~~~~~~~~~~~~ + // + // https://github.com/sequelize/sequelize/blob/v3.4.1/lib/deferrable.js + // + + /** + * Abstract Deferrable interface. Use this if you want to create an interface that has a value any of the + * Deferrables that Sequelize supports. + */ + interface DeferrableAbstract { + + /** + * Although this is not needed for the definitions itself, we want to make sure that DeferrableAbstract is + * not something than can be evaluated to an empty object. + */ + toString() : string; + toSql() : string; + + } + + interface DeferrableInitiallyDeferred extends DeferrableAbstract { + + /** + * A property that will defer constraints checks to the end of transactions. + */ + () : DeferrableInitiallyDeferred; + + } + + interface DeferrableInitiallyImmediate extends DeferrableAbstract { + + /** + * A property that will trigger the constraint checks immediately + */ + () : DeferrableInitiallyImmediate; + + } + + interface DeferrableNot extends DeferrableAbstract { + + /** + * A property that will set the constraints to not deferred. This is the default in PostgreSQL and it make + * it impossible to dynamically defer the constraints within a transaction. + */ + () : DeferrableNot; + + } + + interface DeferrableSetDeferred extends DeferrableAbstract { + + /** + * A property that will trigger an additional query at the beginning of a + * transaction which sets the constraints to deferred. + * + * @param constraints An array of constraint names. Will defer all constraints by default. + */ + ( constraints : Array ) : DeferrableSetDeferred; + + } + + interface DeferrableSetImmediate extends DeferrableAbstract { + + /** + * A property that will trigger an additional query at the beginning of a + * transaction which sets the constraints to immediately. + * + * @param constraints An array of constraint names. Will defer all constraints by default. + */ + ( constraints : Array ) : DeferrableSetImmediate; } /** - * Custom class defined, but no extra methods or functionality even. + * A collection of properties related to deferrable constraints. It can be used to + * make foreign key constraints deferrable and to set the constaints within a + * transaction. This is only supported in PostgreSQL. + * + * The foreign keys can be configured like this. It will create a foreign key + * that will check the constraints immediately when the data was inserted. + * + * ```js + * sequelize.define('Model', { + * foreign_id: { + * type: Sequelize.INTEGER, + * references: { + * model: OtherModel, + * key: 'id', + * deferrable: Sequelize.Deferrable.INITIALLY_IMMEDIATE + * } + * } + * }); + * ``` + * + * The constraints can be configured in a transaction like this. It will + * trigger a query once the transaction has been started and set the constraints + * to be checked at the very end of the transaction. + * + * ```js + * sequelize.transaction({ + * deferrable: Sequelize.Deferrable.SET_DEFERRED + * }); + * ``` */ - interface ValidationError extends Error { + interface Deferrable { + INITIALLY_DEFERRED: DeferrableInitiallyDeferred; + INITIALLY_IMMEDIATE: DeferrableInitiallyImmediate; + NOT: DeferrableNot; + SET_DEFERRED: DeferrableSetDeferred; + SET_IMMEDIATE: DeferrableSetImmediate + } + + // + // Errors + // ~~~~~~~~ + // + // https://github.com/sequelize/sequelize/blob/v3.4.1/lib/errors.js + // + + /** + * The Base Error all Sequelize Errors inherit from. + */ + interface BaseError extends ErrorConstructor { } + + interface ValidationError extends BaseError { + + /** + * Validation Error. Thrown when the sequelize validation has failed. The error contains an `errors` + * property, which is an array with 1 or more ValidationErrorItems, one for each validation that failed. + * + * @param message Error message + * @param errors Array of ValidationErrorItem objects describing the validation errors + */ + new ( message : string, errors? : Array ) : ValidationError; + + /** + * Gets all validation error items for the path / field specified. + * + * @param path The path to be checked for error items + */ + get( path : string ) : Array; } - interface QueryChainer { + interface ValidationErrorItem extends BaseError { + /** - * Add an query to the chainer. This can be done in two ways - either by invoking the method like you would - * normally, and then adding the returned emitter to the chainer, or by passing the class that you want to call a - * method on, the name of the method, and its parameters to the chainer. The second form might sound a bit - * cumbersome, but it is used when you want to run queries in serial. + * Validation Error Item + * Instances of this class are included in the `ValidationError.errors` property. + * + * @param message An error message + * @param type The type of the validation error + * @param path The field that triggered the validation error + * @param value The value that generated the error + */ + new ( message : string, type : string, path : string, value : string ) : ValidationErrorItem; + + } + + interface DatabaseError extends BaseError { + + /** + * A base class for all database related errors. + */ + new ( parent : Error ) : DatabaseError; + + } + + interface TimeoutError extends DatabaseError { + + /** + * Thrown when a database query times out because of a deadlock + */ + new ( parent : Error ) : TimeoutError; + + } + + interface UniqueConstraintError extends DatabaseError { + + /** + * Thrown when a unique constraint is violated in the database + */ + new ( options : { parent? : Error, message? : string, errors? : Object } ) : UniqueConstraintError; + + } + + interface ForeignKeyConstraintError extends DatabaseError { + + /** + * Thrown when a foreign key constraint is violated in the database + */ + new ( options : { parent? : Error, message? : string, index? : string, fields? : Array, table? : string } ) : ForeignKeyConstraintError; + + } + + interface ExclusionConstraintError extends DatabaseError { + + /** + * Thrown when an exclusion constraint is violated in the database + */ + new ( options : { parent? : Error, message? : string, constraint? : string, fields? : Array, table? : string } ) : ExclusionConstraintError; + + } + + interface ConnectionError extends BaseError { + + /** + * A base class for all connection related errors. + */ + new ( parent : Error ) : ConnectionError; + + } + + interface ConnectionRefusedError extends ConnectionError { + + /** + * Thrown when a connection to a database is refused + */ + new ( parent : Error ) : ConnectionRefusedError; + + } + + interface AccessDeniedError extends ConnectionError { + + /** + * Thrown when a connection to a database is refused due to insufficient privileges + */ + new ( parent : Error ) : AccessDeniedError; + + } + + interface HostNotFoundError extends ConnectionError { + + /** + * Thrown when a connection to a database has a hostname that was not found + */ + new ( parent : Error ) : HostNotFoundError; + + } + + interface HostNotReachableError extends ConnectionError { + + /** + * Thrown when a connection to a database has a hostname that was not reachable + */ + new ( parent : Error ) : HostNotReachableError; + + } + + interface InvalidConnectionError extends ConnectionError { + + /** + * Thrown when a connection to a database has invalid values for any of the connection parameters + */ + new ( parent : Error ) : InvalidConnectionError; + + } + + interface ConnectionTimedOutError extends ConnectionError { + + /** + * Thrown when a connection to a database times out + */ + new ( parent : Error ) : ConnectionTimedOutError; + + } + + /** + * Sequelize provides a host of custom error classes, to allow you to do easier debugging. All of these errors + * are exposed on the sequelize object and the sequelize constructor. All sequelize errors inherit from the + * base JS error object. + */ + interface Errors { + Error : BaseError; + ValidationError : ValidationError; + ValidationErrorItem : ValidationErrorItem; + DatabaseError : DatabaseError; + TimeoutError : TimeoutError; + UniqueConstraintError : UniqueConstraintError; + ExclusionConstraintError : ExclusionConstraintError; + ForeignKeyConstraintError : ForeignKeyConstraintError; + ConnectionError : ConnectionError; + ConnectionRefusedError : ConnectionRefusedError; + AccessDeniedError : AccessDeniedError; + HostNotFoundError : HostNotFoundError; + HostNotReachableError : HostNotReachableError; + InvalidConnectionError : InvalidConnectionError; + ConnectionTimedOutError : ConnectionTimedOutError; + } + + // + // Hooks + // ~~~~~~~ + // + // https://github.com/sequelize/sequelize/blob/v3.4.1/lib/hooks.js + // + + /** + * Options for Sequelize.define. We mostly duplicate the Hooks here, since there is no way to combine the two + * interfaces. + * + * beforeValidate, afterValidate, beforeBulkCreate, beforeBulkDestroy, beforeBulkUpdate, beforeCreate, + * beforeDestroy, beforeUpdate, afterCreate, afterDestroy, afterUpdate, afterBulkCreate, afterBulkDestroy and + * afterBulkUpdate. + */ + interface HooksDefineOptions { + + beforeValidate? : ( instance : TInstance, options : Object, fn? : Function ) => any; + afterValidate? : ( instance : TInstance, options : Object, fn? : Function ) => any; + beforeCreate? : ( attributes : TInstance, options : Object, fn? : Function ) => any; + afterCreate? : ( attributes : TInstance, options : Object, fn? : Function ) => any; + beforeDestroy? : ( instance : TInstance, options : Object, fn? : Function ) => any; + beforeDelete? : ( instance : TInstance, options : Object, fn? : Function ) => any; + afterDestroy? : ( instance : TInstance, options : Object, fn? : Function ) => any; + afterDelete? : ( instance : TInstance, options : Object, fn? : Function ) => any; + beforeUpdate? : ( instance : TInstance, options : Object, fn? : Function ) => any; + afterUpdate? : ( instance : TInstance, options : Object, fn? : Function ) => any; + beforeBulkCreate? : ( instances : Array, options : Object, fn? : Function ) => any; + afterBulkCreate? : ( instances : Array, options : Object, fn? : Function ) => any; + beforeBulkDestroy? : ( options : Object, fn? : Function ) => any; + beforeBulkDelete? : ( options : Object, fn? : Function ) => any; + afterBulkDestroy? : ( options : Object, fn? : Function ) => any; + afterBulkDelete? : ( options : Object, fn? : Function ) => any; + beforeBulkUpdate? : ( options : Object, fn? : Function ) => any; + afterBulkUpdate? : ( options : Object, fn? : Function ) => any; + beforeFind? : ( options : Object, fn? : Function ) => any; + beforeFindAfterExpandIncludeAll? : ( options : Object, fn? : Function ) => any; + beforeFindAfterOptions? : ( options : Object, fn? : Function ) => any; + afterFind? : ( instancesOrInstance : Array | TInstance, options : Object, + fn? : Function ) => any; + + } + + /** + * Hooks are function that are called before and after (bulk-) creation/updating/deletion and validation. + * Hooks can be added to you models in three ways: + * + * 1. By specifying them as options in `sequelize.define` + * 2. By calling `hook()` with a string and your hook handler function + * 3. By calling the function with the same name as the hook you want + * + * ```js + * // Method 1 + * sequelize.define(name, { attributes }, { + * hooks: { + * beforeBulkCreate: function () { + * // can be a single function + * }, + * beforeValidate: [ + * function () {}, + * function() {} // Or an array of several + * ] + * } + * }) + * + * // Method 2 + * Model.hook('afterDestroy', function () {}) + * + * // Method 3 + * Model.afterBulkUpdate(function () {}) + * ``` + * + * @see Sequelize.define + */ + interface Hooks { + + /** + * Add a hook to the model + * + * @param hookType + * @param name Provide a name for the hook function. It can be used to remove the hook later or to order + * hooks based on some sort of priority system in the future. + * @param fn The hook function + * + * @alias hook + */ + addHook( hookType : string, name : string, fn : Function ) : Hooks; + addHook( hookType : string, fn : Function ) : Hooks; + hook( hookType : string, name : string, fn : Function ) : Hooks; + hook( hookType : string, fn : Function ) : Hooks; + + /** + * Remove hook from the model + * + * @param hookType + * @param name + */ + removeHook( hookType : string, name : string ) : Hooks; + + /** + * Check whether the mode has any hooks of this type + * + * @param hookType + * + * @alias hasHooks + */ + hasHook( hookType : string ) : boolean; + hasHooks( hookType : string ) : boolean; + + /** + * A hook that is run before validation + * + * @param name + * @param fn A callback function that is called with instance, options + */ + beforeValidate( name : string, + fn : ( instance : TInstance, options : Object, fn? : Function ) => void ): void; + beforeValidate( fn : ( instance : TInstance, options : Object, fn? : Function ) => void ): void; + + /** + * A hook that is run after validation + * + * @param name + * @param fn A callback function that is called with instance, options + */ + afterValidate( name : string, + fn : ( instance : TInstance, options : Object, fn? : Function ) => void ): void; + afterValidate( fn : ( instance : TInstance, options : Object, fn? : Function ) => void ): void; + + /** + * A hook that is run before creating a single instance + * + * @param name + * @param fn A callback function that is called with attributes, options + */ + beforeCreate( name : string, + fn : ( attributes : TInstance, options : Object, fn? : Function ) => void ): void; + beforeCreate( fn : ( attributes : TInstance, options : Object, fn? : Function ) => void ): void; + + /** + * A hook that is run after creating a single instance + * + * @param name + * @param fn A callback function that is called with attributes, options + */ + afterCreate( name : string, + fn : ( attributes : TInstance, options : Object, fn? : Function ) => void ): void; + afterCreate( fn : ( attributes : TInstance, options : Object, fn? : Function ) => void ): void; + + /** + * A hook that is run before destroying a single instance + * + * @param name + * @param fn A callback function that is called with instance, options + * @alias beforeDelete + */ + beforeDestroy( name : string, + fn : ( instance : TInstance, options : Object, fn? : Function ) => void ): void; + beforeDestroy( fn : ( instance : TInstance, options : Object, fn? : Function ) => void ): void; + beforeDelete( name : string, + fn : ( instance : TInstance, options : Object, fn? : Function ) => void ): void; + beforeDelete( fn : ( instance : TInstance, options : Object, fn? : Function ) => void ): void; + + /** + * A hook that is run after destroying a single instance + * + * @param name + * @param fn A callback function that is called with instance, options + * @alias afterDelete + */ + afterDestroy( name : string, + fn : ( instance : TInstance, options : Object, fn? : Function ) => void ): void; + afterDestroy( fn : ( instance : TInstance, options : Object, fn? : Function ) => void ): void; + afterDelete( name : string, fn : ( instance : TInstance, options : Object, fn? : Function ) => void ): void; + afterDelete( fn : ( instance : TInstance, options : Object, fn? : Function ) => void ): void; + + /** + * A hook that is run before updating a single instance + * + * @param name + * @param fn A callback function that is called with instance, options + */ + beforeUpdate( name : string, + fn : ( instance : TInstance, options : Object, fn? : Function ) => void ): void; + beforeUpdate( fn : ( instance : TInstance, options : Object, fn? : Function ) => void ): void; + + /** + * A hook that is run after updating a single instance + * + * @param name + * @param fn A callback function that is called with instance, options + */ + afterUpdate( name : string, fn : ( instance : TInstance, options : Object, fn? : Function ) => void ): void; + afterUpdate( fn : ( instance : TInstance, options : Object, fn? : Function ) => void ): void; + + /** + * A hook that is run before creating instances in bulk + * + * @param name + * @param fn A callback function that is called with instances, options + */ + beforeBulkCreate( name : string, + fn : ( instances : Array, options : Object, fn? : Function ) => void ): void; + beforeBulkCreate( fn : ( instances : Array, options : Object, fn? : Function ) => void ): void; + + /** + * A hook that is run after creating instances in bulk + * + * @param name + * @param fn A callback function that is called with instances, options + * @name afterBulkCreate + */ + afterBulkCreate( name : string, + fn : ( instances : Array, options : Object, fn? : Function ) => void ): void; + afterBulkCreate( fn : ( instances : Array, options : Object, fn? : Function ) => void ): void; + + /** + * A hook that is run before destroying instances in bulk + * + * @param name + * @param fn A callback function that is called with options + * + * @alias beforeBulkDelete + */ + beforeBulkDestroy( name : string, fn : ( options : Object, fn? : Function ) => void ): void; + beforeBulkDestroy( fn : ( options : Object, fn? : Function ) => void ): void; + beforeBulkDelete( name : string, fn : ( options : Object, fn? : Function ) => void ): void; + beforeBulkDelete( fn : ( options : Object, fn? : Function ) => void ): void; + + /** + * A hook that is run after destroying instances in bulk + * + * @param name + * @param fn A callback function that is called with options + * + * @alias afterBulkDelete + */ + afterBulkDestroy( name : string, fn : ( options : Object, fn? : Function ) => void ): void; + afterBulkDestroy( fn : ( options : Object, fn? : Function ) => void ): void; + afterBulkDelete( name : string, fn : ( options : Object, fn? : Function ) => void ): void; + afterBulkDelete( fn : ( options : Object, fn? : Function ) => void ): void; + + /** + * A hook that is run after updating instances in bulk + * + * @param name + * @param fn A callback function that is called with options + */ + beforeBulkUpdate( name : string, fn : ( options : Object, fn? : Function ) => void ): void; + beforeBulkUpdate( fn : ( options : Object, fn? : Function ) => void ): void; + + /** + * A hook that is run after updating instances in bulk + * + * @param name + * @param fn A callback function that is called with options + */ + afterBulkUpdate( name : string, fn : ( options : Object, fn? : Function ) => void ): void; + afterBulkUpdate( fn : ( options : Object, fn? : Function ) => void ): void; + + /** + * A hook that is run before a find (select) query + * + * @param name + * @param fn A callback function that is called with options + */ + beforeFind( name : string, fn : ( options : Object, fn? : Function ) => void ): void; + beforeFind( fn : ( options : Object, fn? : Function ) => void ): void; + + /** + * A hook that is run before a find (select) query, after any { include: {all: ...} } options are expanded + * + * @param name + * @param fn A callback function that is called with options + */ + beforeFindAfterExpandIncludeAll( name : string, + fn : ( options : Object, fn? : Function ) => void ): void; + beforeFindAfterExpandIncludeAll( fn : ( options : Object, fn? : Function ) => void ): void; + + /** + * A hook that is run before a find (select) query, after all option parsing is complete + * + * @param name + * @param fn A callback function that is called with options + */ + beforeFindAfterOptions( name : string, fn : ( options : Object, fn? : Function ) => void ): void; + beforeFindAfterOptions( fn : ( options : Object, fn? : Function ) => void ): void; + + /** + * A hook that is run after a find (select) query + * + * @param name + * @param fn A callback function that is called with instance(s), options + */ + afterFind( name : string, + fn : ( instancesOrInstance : Array | TInstance, options : Object, + fn? : Function ) => void ): void; + afterFind( fn : ( instancesOrInstance : Array | TInstance, options : Object, + fn? : Function ) => void ): void; + + /** + * A hook that is run before a define call + * + * @param name + * @param fn A callback function that is called with attributes, options + */ + beforeDefine( name : string, fn : ( attributes : DefineAttributes, options : Object ) => void ): void; + beforeDefine( fn : ( attributes : DefineAttributes, options : Object ) => void ): void; + + /** + * A hook that is run after a define call + * + * @param name + * @param fn A callback function that is called with factory + */ + afterDefine( name : string, fn : ( model : Model ) => void ): void; + afterDefine( fn : ( model : Model ) => void ): void; + + /** + * A hook that is run before Sequelize() call + * + * @param name + * @param fn A callback function that is called with config, options + */ + beforeInit( name : string, fn : ( config : Object, options : Object ) => void ): void; + beforeInit( fn : ( config : Object, options : Object ) => void ): void; + + /** + * A hook that is run after Sequelize() call + * + * @param name + * @param fn A callback function that is called with sequelize + */ + afterInit( name : string, fn : ( sequelize : Sequelize ) => void ): void; + afterInit( fn : ( sequelize : Sequelize ) => void ): void; + + } + + // + // Instance + // ~~~~~~~~~~ + // + // https://github.com/sequelize/sequelize/blob/v3.4.1/lib/instance.js + // + + /** + * Options used for Instance.increment method + */ + interface InstanceIncrementDecrementOptions { + + /** + * The number to increment by + * + * Defaults to 1 + */ + by? : number; + + /** + * A function that gets executed while running the query to log the sql. + */ + logging? : boolean | Function; + + /** + * Transaction to run query under + */ + transaction? : Transaction; + + /** + * A hash of attributes to describe your search. See above for examples. + */ + where? : WhereOptions | Array; + + } + + /** + * Options used for Instance.restore method + */ + interface InstanceRestoreOptions { + + /** + * A function that gets executed while running the query to log the sql. + */ + logging? : boolean | Function; + + /** + * Transaction to run query under + */ + transaction? : Transaction; + + } + + /** + * Options used for Instance.destroy method + */ + interface InstanceDestroyOptions { + + /** + * If set to true, paranoid models will actually be deleted + */ + force? : boolean; + + /** + * A function that gets executed while running the query to log the sql. + */ + logging? : boolean | Function; + + /** + * Transaction to run the query in + */ + transaction? : Transaction; + + } + + /** + * Options used for Instance.update method + */ + interface InstanceUpdateOptions extends InstanceSaveOptions, InstanceSetOptions { + + /** + * A hash of attributes to describe your search. See above for examples. + */ + where? : WhereOptions | Array; + + } + + /** + * Options used for Instance.set method + */ + interface InstanceSetOptions { + + /** + * If set to true, field and virtual setters will be ignored + */ + raw? : boolean; + + /** + * Clear all previously set data values + */ + reset? : boolean; + + } + + /** + * Options used for Instance.save method + */ + interface InstanceSaveOptions { + + /** + * An optional array of strings, representing database columns. If fields is provided, only those columns + * will be validated and saved. + */ + fields? : Array; + + /** + * If true, the updatedAt timestamp will not be updated. + * + * Defaults to false + */ + silent? : boolean; + + /** + * If false, validations won't be run. + * + * Defaults to true + */ + validate? : boolean; + + /** + * A function that gets executed while running the query to log the sql. + */ + logging? : boolean | Function; + + /** + * Transaction to run the query in + */ + transaction? : Transaction; + + } + + /** + * This class represents an single instance, a database row. You might see it referred to as both Instance and + * instance. You should not instantiate the Instance class directly, instead you access it using the finder and + * creation methods on the model. + * + * Instance instances operate with the concept of a `dataValues` property, which stores the actual values + * represented by the instance. By default, the values from dataValues can also be accessed directly from the + * Instance, that is: + * ```js + * instance.field + * // is the same as + * instance.get('field') + * // is the same as + * instance.getDataValue('field') + * ``` + * However, if getters and/or setters are defined for `field` they will be invoked, instead of returning the + * value from `dataValues`. Accessing properties directly or using `get` is preferred for regular use, + * `getDataValue` should only be used for custom getters. + * + * @see Sequelize.define for more information about getters and setters + */ + interface Instance { + + /** + * Returns true if this instance has not yet been persisted to the database + */ + isNewRecord : boolean; + + /** + * Returns the Model the instance was created from. + * + * @see Model + */ + Model : Model; + + /** + * A reference to the sequelize instance + */ + sequelize : Sequelize; + + /** + * Get an object representing the query for this instance, use with `options.where` + */ + where() : Object; + + /** + * Get the value of the underlying data value + */ + getDataValue( key : string ) : any; + + /** + * Update the underlying data value + */ + setDataValue( key : string, value : any ) : void; + + /** + * If no key is given, returns all values of the instance, also invoking virtual getters. + * + * If key is given and a field or virtual getter is present for the key it will call that getter - else it + * will return the value for key. + * + * @param options.plain If set to true, included instances will be returned as plain objects + */ + get( key : string, options? : { plain? : boolean, clone? : boolean } ) : any; + get( options? : { plain? : boolean, clone? : boolean } ) : Object; + + /** + * Set is used to update values on the instance (the sequelize representation of the instance that is, + * remember that nothing will be persisted before you actually call `save`). In its most basic form `set` + * will update a value stored in the underlying `dataValues` object. However, if a custom setter function + * is defined for the key, that function will be called instead. To bypass the setter, you can pass `raw: + * true` in the options object. + * + * If set is called with an object, it will loop over the object, and call set recursively for each key, + * value pair. If you set raw to true, the underlying dataValues will either be set directly to the object + * passed, or used to extend dataValues, if dataValues already contain values. + * + * When set is called, the previous value of the field is stored and sets a changed flag(see `changed`). + * + * Set can also be used to build instances for associations, if you have values for those. + * When using set with associations you need to make sure the property key matches the alias of the + * association while also making sure that the proper include options have been set (from .build() or + * .find()) + * + * If called with a dot.seperated key on a JSON/JSONB attribute it will set the value nested and flag the + * entire object as changed. + * + * @param options.raw If set to true, field and virtual setters will be ignored + * @param options.reset Clear all previously set data values + */ + set( key : string, value : any, options? : InstanceSetOptions ) : TInstance; + set( keys : Object, options? : InstanceSetOptions ) : TInstance; + setAttributes( key : string, value : any, options? : InstanceSetOptions ) : TInstance; + setAttributes( keys : Object, options? : InstanceSetOptions ) : TInstance; + + /** + * If changed is called with a string it will return a boolean indicating whether the value of that key in + * `dataValues` is different from the value in `_previousDataValues`. + * + * If changed is called without an argument, it will return an array of keys that have changed. + * + * If changed is called without an argument and no keys have changed, it will return `false`. + */ + changed( key : string ) : boolean; + changed() : boolean | Array; + + /** + * Returns the previous value for key from `_previousDataValues`. + */ + previous( key : string ) : any; + + /** + * Validate this instance, and if the validation passes, persist it to the database. + * + * On success, the callback will be called with this instance. On validation error, the callback will be + * called with an instance of `Sequelize.ValidationError`. This error will have a property for each of the + * fields for which validation failed, with the error message for that field. + */ + save( options? : InstanceSaveOptions ) : Promise; + + /** + * Refresh the current instance in-place, i.e. update the object with current data from the DB and return + * the same object. This is different from doing a `find(Instance.id)`, because that would create and + * return a new instance. With this method, all references to the Instance are updated with the new data + * and no new objects are created. + */ + reload( options? : FindOptions ) : Promise; + + /** + * Validate the attribute of this instance according to validation rules set in the model definition. + * + * Emits null if and only if validation successful; otherwise an Error instance containing + * { field name : [error msgs] } entries. + * + * @param options.skip An array of strings. All properties that are in this array will not be validated + */ + validate( options? : { skip?: Array } ) : Promise; + + /** + * This is the same as calling `set` and then calling `save`. + */ + update( key : string, value : any, options? : InstanceUpdateOptions ) : Promise; + update( keys : Object, options? : InstanceUpdateOptions ) : Promise; + updateAttributes( key : string, value : any, options? : InstanceUpdateOptions ) : Promise; + updateAttributes( keys : Object, options? : InstanceUpdateOptions ) : Promise; + + /** + * Destroy the row corresponding to this instance. Depending on your setting for paranoid, the row will + * either be completely deleted, or have its deletedAt timestamp set to the current time. + */ + destroy( options? : InstanceDestroyOptions ) : Promise; + + /** + * Restore the row corresponding to this instance. Only available for paranoid models. + */ + restore( options? : InstanceRestoreOptions ) : Promise; + + /** + * Increment the value of one or more columns. This is done in the database, which means it does not use + * the values currently stored on the Instance. The increment is done using a + * ```sql + * SET column = column + X + * ``` + * query. To get the correct value after an increment into the Instance you should do a reload. + * + *```js + * instance.increment('number') // increment number by 1 + * instance.increment(['number', 'count'], { by: 2 }) // increment number and count by 2 + * instance.increment({ answer: 42, tries: 1}, { by: 2 }) // increment answer by 42, and tries by 1. + * // `by` is ignored, since each column has its own + * // value + * ``` + * + * @param fields If a string is provided, that column is incremented by the value of `by` given in options. + * If an array is provided, the same is true for each column. + * If and object is provided, each column is incremented by the value given. + */ + increment( fields : string | Array | Object, + options? : InstanceIncrementDecrementOptions ) : Promise; + + /** + * Decrement the value of one or more columns. This is done in the database, which means it does not use + * the values currently stored on the Instance. The decrement is done using a + * ```sql + * SET column = column - X + * ``` + * query. To get the correct value after an decrement into the Instance you should do a reload. + * + * ```js + * instance.decrement('number') // decrement number by 1 + * instance.decrement(['number', 'count'], { by: 2 }) // decrement number and count by 2 + * instance.decrement({ answer: 42, tries: 1}, { by: 2 }) // decrement answer by 42, and tries by 1. + * // `by` is ignored, since each column has its own + * // value + * ``` + * + * @param fields If a string is provided, that column is decremented by the value of `by` given in options. + * If an array is provided, the same is true for each column. + * If and object is provided, each column is decremented by the value given + */ + decrement( fields : string | Array | Object, + options? : InstanceIncrementDecrementOptions ) : Promise; + + /** + * Check whether all values of this and `other` Instance are the same + */ + equals( other : Instance ) : boolean; + + /** + * Check if this is eqaul to one of `others` by calling equals + */ + equalsOneOf( others : Array> ) : boolean; + + /** + * Convert the instance to a JSON representation. Proxies to calling `get` with no keys. This means get all + * values gotten from the DB, and apply all custom getters. + */ + toJSON() : Object; + + } + + // + // Model + // ~~~~~~~ + // + // https://github.com/sequelize/sequelize/blob/v3.4.1/lib/model.js + // + + /** + * Options to pass to Model on drop + */ + interface DropOptions { + + /** + * Also drop all objects depending on this table, such as views. Only works in postgres + */ + cascade?: boolean; + + /** + * A function that gets executed while running the query to log the sql. + */ + logging?: boolean | Function; + + } + + /** + * Schema Options provided for applying a schema to a model + */ + interface SchemaOptions { + + /** + * The character(s) that separates the schema name from the table name + */ + schemaDelimeter? : string, + + /** + * A function that gets executed while running the query to log the sql. + */ + logging? : Function | boolean + + } + + /** + * Scope Options for Model.scope + */ + interface ScopeOptions { + + /** + * The scope(s) to apply. Scopes can either be passed as consecutive arguments, or as an array of arguments. + * To apply simple scopes and scope functions with no arguments, pass them as strings. For scope function, + * pass an object, with a `method` property. The value can either be a string, if the method does not take + * any arguments, or an array, where the first element is the name of the method, and consecutive elements + * are arguments to that method. Pass null to remove all scopes, including the default. + */ + method : string | Array; + + } + + /** + * Where Complex nested query + */ + interface WhereNested { + $and : Array; + $or : Array; + } + + /** + * Nested where Postgre Statement + */ + interface WherePGStatement { + $any : Array; + $all : Array; + } + + /** + * Where Geometry Options + */ + interface WhereGeometryOptions { + type: string; + coordinates: Array | number>; + } + + /** + * Logic of where statement + */ + interface WhereLogic { + $ne : string | number | WhereLogic; + $in : Array | literal; + $not : boolean | string | number | WhereOptions; + $notIn : Array | literal; + $gte : number | string | Date; + $gt : number | string | Date; + $lte : number | string | Date; + $lt : number | string | Date; + $like : string | WherePGStatement; + $iLike : string | WherePGStatement; + $ilike : string | WherePGStatement; + $notLike : string | WherePGStatement; + $notILike : string | WherePGStatement; + $between : [number, number]; + ".." : [number, number]; + $notBetween: [number, number]; + "!.." : [number, number]; + $overlap : [number, number]; + "&&" : [number, number]; + $contains: any; + "@>": any; + $contained: any; + "<@": any; + } + + /** + * A hash of attributes to describe your search. See above for examples. + * + * We did put Object in the end, because there where query might be a JSON Blob. It cripples a bit the + * typesafety, but there is no way to pass the tests if we just remove it. + */ + interface WhereOptions { + [field: string]: string | number | WhereLogic | WhereOptions | col | and | or | WhereGeometryOptions | Array | Object; + } + + /** + * Through options for Include Options + */ + interface IncludeThroughOptions { + + /** + * Filter on the join model for belongsToMany relations + */ + where? : WhereOptions; + + /** + * A list of attributes to select from the join model for belongsToMany relations + */ + attributes? : Array; + + } + + /** + * Association Object for Include Options + */ + interface IncludeAssociation { + source: Model; + target: Model; + identifier: string; + } + + /** + * Complex include options + */ + interface IncludeOptions { + + /** + * The model you want to eagerly load + */ + model? : Model; + + /** + * The alias of the relation, in case the model you want to eagerly load is aliassed. For `hasOne` / + * `belongsTo`, this should be the singular name, and for `hasMany`, it should be the plural + */ + as? : string; + + /** + * The association you want to eagerly load. (This can be used instead of providing a model/as pair) + */ + association? : IncludeAssociation; + + /** + * Where clauses to apply to the child models. Note that this converts the eager load to an inner join, + * unless you explicitly set `required: false` + */ + where? : WhereOptions; + + /** + * A list of attributes to select from the child model + */ + attributes? : Array; + + /** + * If true, converts to an inner join, which means that the parent model will only be loaded if it has any + * matching children. True if `include.where` is set, false otherwise. + */ + required? : boolean; + + /** + * Through Options + */ + through? : IncludeThroughOptions; + + /** + * Load further nested related models + */ + include? : Array | IncludeOptions>; + + } + + /** + * Options that are passed to any model creating a SELECT query + * + * A hash of options to describe the scope of the search + */ + interface FindOptions { + + /** + * A hash of attributes to describe your search. See above for examples. + */ + where? : WhereOptions | Array; + + /** + * A list of the attributes that you want to select. To rename an attribute, you can pass an array, with + * two elements - the first is the name of the attribute in the DB (or some kind of expression such as + * `Sequelize.literal`, `Sequelize.fn` and so on), and the second is the name you want the attribute to + * have in the returned instance + */ + attributes? : Array; + + /** + * If true, only non-deleted records will be returned. If false, both deleted and non-deleted records will + * be returned. Only applies if `options.paranoid` is true for the model. + */ + paranoid?: boolean; + + /** + * A list of associations to eagerly load using a left join. Supported is either + * `{ include: [ Model1, Model2, ...]}` or `{ include: [{ model: Model1, as: 'Alias' }]}`. + * If your association are set up with an `as` (eg. `X.hasMany(Y, { as: 'Z }`, you need to specify Z in + * the as attribute when eager loading Y). + */ + include?: Array | IncludeOptions>; + + /** + * Specifies an ordering. If a string is provided, it will be escaped. Using an array, you can provide + * several columns / functions to order by. Each element can be further wrapped in a two-element array. The + * first element is the column / function to order by, the second is the direction. For example: + * `order: [['name', 'DESC']]`. In this way the column will be escaped, but the direction will not. + */ + order?: string | col | literal | Array | { model : Model, as? : string}> | Array | { model : Model, as? : string}>>; + + /** + * Limit the results + */ + limit?: number; + + /** + * Skip the results; + */ + offset?: number; + + /** + * Transaction to run query under + */ + transaction? : Transaction; + + /** + * Lock the selected rows. Possible options are transaction.LOCK.UPDATE and transaction.LOCK.SHARE. + * Postgres also supports transaction.LOCK.KEY_SHARE, transaction.LOCK.NO_KEY_UPDATE and specific model + * locks with joins. See [transaction.LOCK for an example](transaction#lock) + */ + lock? : string | { level: string, of: Model }; + + /** + * Return raw result. See sequelize.query for more information. + */ + raw? : boolean; + + /** + * A function that gets executed while running the query to log the sql. + */ + logging? : boolean | Function; + + /** + * having ?!? + */ + having? : WhereOptions; + + } + + /** + * Options for Model.count method + */ + interface CountOptions { + + /** + * A hash of search attributes. + */ + where? : WhereOptions | Array; + + /** + * Include options. See `find` for details + */ + include?: Array | IncludeOptions>; + + /** + * Apply COUNT(DISTINCT(col)) + */ + distinct? : boolean; + + /** + * Used in conjustion with `group` + */ + attributes? : Array; + + /** + * For creating complex counts. Will return multiple rows as needed. + * + * TODO: Check? + */ + group? : Object; + + /** + * A function that gets executed while running the query to log the sql. + */ + logging? : boolean | Function; + + } + + /** + * Options for Model.build method + */ + interface BuildOptions { + + /** + * If set to true, values will ignore field and virtual setters. + */ + raw? : boolean; + + /** + * Is this record new + */ + isNewRecord? : boolean; + + /** + * an array of include options - Used to build prefetched/included model instances. See `set` + * + * TODO: See set + */ + include? : Array | IncludeOptions>; + + } + + /** + * Options for Model.create method + */ + interface CreateOptions extends BuildOptions { + + /** + * If set, only columns matching those in fields will be saved + */ + fields? : Array; + + /** + * On Duplicate + */ + onDuplicate? : string; + + /** + * Transaction to run query under + */ + transaction? : Transaction; + + /** + * A function that gets executed while running the query to log the sql. + */ + logging? : boolean | Function; + + } + + /** + * Options for Model.findOrInitialize method + */ + interface FindOrInitializeOptions { + + /** + * A hash of search attributes. + */ + where : string | WhereOptions; + + /** + * Default values to use if building a new instance + */ + defaults? : TAttributes; + + /** + * Transaction to run query under + */ + transaction? : Transaction; + + /** + * A function that gets executed while running the query to log the sql. + */ + logging? : boolean | Function; + + } + + /** + * Options for Model.upsert method + */ + interface UpsertOptions { + + /** + * Run validations before the row is inserted + */ + validate? : boolean; + + /** + * The fields to insert / update. Defaults to all fields + */ + fields? : Array; + + /** + * A function that gets executed while running the query to log the sql. + */ + logging? : boolean | Function; + + } + + /** + * Options for Model.bulkCreate method + */ + interface BulkCreateOptions { + + /** + * Fields to insert (defaults to all fields) + */ + fields? : Array; + + /** + * Should each row be subject to validation before it is inserted. The whole insert will fail if one row + * fails validation + */ + validate? : boolean; + + /** + * Run before / after bulk create hooks? + */ + hooks? : boolean; + + /** + * Run before / after create hooks for each individual Instance? BulkCreate hooks will still be run if + * options.hooks is true. + */ + individualHooks? : boolean; + + /** + * Ignore duplicate values for primary keys? (not supported by postgres) + * + * Defaults to false + */ + ignoreDuplicates? : boolean; + + /** + * Fields to update if row key already exists (on duplicate key update)? (only supported by mysql & + * mariadb). By default, all fields are updated. + */ + updateOnDuplicate? : Array; + + /** + * Transaction to run query under + */ + transaction? : Transaction; + + /** + * A function that gets executed while running the query to log the sql. + */ + logging? : boolean | Function; + + } + + /** + * The options passed to Model.destroy in addition to truncate + */ + interface TruncateOptions { + + /** + * Transaction to run query under + */ + transaction? : Transaction; + + /** + * Only used in conjuction with TRUNCATE. Truncates all tables that have foreign-key references to the + * named table, or to any tables added to the group due to CASCADE. + * + * Defaults to false; + */ + cascade? : boolean; + + /** + * A function that gets executed while running the query to log the sql. + */ + logging? : boolean | Function; + + } + + /** + * Options used for Model.destroy + */ + interface DestroyOptions extends TruncateOptions { + + /** + * Filter the destroy + */ + where? : WhereOptions; + + /** + * Run before / after bulk destroy hooks? + */ + hooks? : boolean; + + /** + * If set to true, destroy will SELECT all records matching the where parameter and will execute before / + * after destroy hooks on each row + */ + individualHooks? : boolean; + + /** + * How many rows to delete + */ + limit? : number; + + /** + * Delete instead of setting deletedAt to current timestamp (only applicable if `paranoid` is enabled) + */ + force? : boolean; + + /** + * If set to true, dialects that support it will use TRUNCATE instead of DELETE FROM. If a table is + * truncated the where and limit options are ignored + */ + truncate? : boolean; + + } + + /** + * Options for Model.restore + */ + interface RestoreOptions { + + /** + * Filter the restore + */ + where? : WhereOptions; + + /** + * Run before / after bulk restore hooks? + */ + hooks? : boolean; + + /** + * If set to true, restore will find all records within the where parameter and will execute before / after + * bulkRestore hooks on each row + */ + individualHooks? : boolean; + + /** + * How many rows to undelete + */ + limit? : number; + + /** + * A function that gets executed while running the query to log the sql. + */ + logging? : boolean | Function; + + /** + * Transaction to run query under + */ + transaction? : Transaction; + + } + + /** + * Options used for Model.update + */ + interface UpdateOptions { + + /** + * Options to describe the scope of the search. + */ + where: WhereOptions; + + /** + * Fields to update (defaults to all fields) + */ + fields? : Array; + + /** + * Should each row be subject to validation before it is inserted. The whole insert will fail if one row + * fails validation. + * + * Defaults to true + */ + validate? : boolean; + + /** + * Run before / after bulk update hooks? + * + * Defaults to true + */ + hooks? : boolean; + + /** + * Whether or not to update the side effects of any virtual setters. + * + * Defaults to true + */ + sideEffects? : boolean; + + /** + * Run before / after update hooks?. If true, this will execute a SELECT followed by individual UPDATEs. + * A select is needed, because the row data needs to be passed to the hooks + * + * Defaults to false + */ + individualHooks? : boolean; + + /** + * Return the affected rows (only for postgres) + */ + returning? : boolean; + + /** + * How many rows to update (only for mysql and mariadb) + */ + limit? : number; + + /** + * A function that gets executed while running the query to log the sql. + */ + logging? : boolean | Function; + + /** + * Transaction to run query under + */ + transaction? : Transaction; + + } + + /** + * Options used for Model.aggregate + */ + interface AggregateOptions extends QueryOptions { + + /** + * A hash of search attributes. + */ + where?: WhereOptions; + + /** + * The type of the result. If `field` is a field in this Model, the default will be the type of that field, + * otherwise defaults to float. + */ + dataType? : DataTypeAbstract | string; + + /** + * Applies DISTINCT to the field being aggregated over + */ + distinct? : boolean; + + } + + /** + * A Model represents a table in the database. Sometimes you might also see it referred to as model, or simply + * as factory. This class should _not_ be instantiated directly, it is created using `sequelize.define`, and + * already created models can be loaded using `sequelize.import` + */ + interface Model extends Hooks, Associations { + + /** + * The Instance class + */ + Instance() : Instance; + + /** + * Remove attribute from model definition + * + * @param attribute + */ + removeAttribute( attribute : string ) : void; + + /** + * Sync this Model to the DB, that is create the table. Upon success, the callback will be called with the + * model instance (this) + */ + sync( options? : SyncOptions ) : Promise>; + + /** + * Drop the table represented by this Model * - * @param emitterOrKlass - * @param method - * @param params * @param options */ - add(emitterOrKlass: any, method?: string, params?: any, options?: any): QueryChainer; + drop( options? : DropOptions ) : Promise; /** - * Run the query chainer. In reality, this means, wait for all the added emitters to finish, since the queries - * began executing as soon as you invoked their methods. - */ - run(): EventEmitter; - - /** - * Run the chainer serially, so that each query waits for the previous one to finish before it starts. + * Apply a schema to this model. For postgres, this will actually place the schema in front of the table + * name + * - `"schema"."tableName"`, while the schema will be prepended to the table name for mysql and + * sqlite - `'schema.tablename'`. * - * @param options @see QueryChainerRunSeriallyOptions + * @param schema The name of the schema + * @param options */ - runSerially(options?: QueryChainerRunSeriallyOptions): EventEmitter; + schema( schema : string, options? : SchemaOptions ) : Model; + + /** + * Get the tablename of the model, taking schema into account. The method will return The name as a string + * if the model has no schema, or an object with `tableName`, `schema` and `delimiter` properties. + * + * @param options The hash of options from any query. You can use one model to access tables with matching + * schemas by overriding `getTableName` and using custom key/values to alter the name of the table. + * (eg. + * subscribers_1, subscribers_2) + * @param options.logging=false A function that gets executed while running the query to log the sql. + */ + getTableName( options? : { logging : Function } ) : string | Object; + + /** + * Apply a scope created in `define` to the model. First let's look at how to create scopes: + * ```js + * var Model = sequelize.define('model', attributes, { + * defaultScope: { + * where: { + * username: 'dan' + * }, + * limit: 12 + * }, + * scopes: { + * isALie: { + * where: { + * stuff: 'cake' + * } + * }, + * complexFunction: function(email, accessLevel) { + * return { + * where: { + * email: { + * $like: email + * }, + * accesss_level { + * $gte: accessLevel + * } + * } + * } + * } + * } + * }) + * ``` + * Now, since you defined a default scope, every time you do Model.find, the default scope is appended to + * your query. Here's a couple of examples: + * ```js + * Model.findAll() // WHERE username = 'dan' + * Model.findAll({ where: { age: { gt: 12 } } }) // WHERE age > 12 AND username = 'dan' + * ``` + * + * To invoke scope functions you can do: + * ```js + * Model.scope({ method: ['complexFunction' 'dan@sequelize.com', 42]}).findAll() + * // WHERE email like 'dan@sequelize.com%' AND access_level >= 42 + * ``` + * + * @return Model A reference to the model, with the scope(s) applied. Calling scope again on the returned + * model will clear the previous scope. + */ + scope( options? : string | Array | ScopeOptions | WhereOptions ) : Model; + + /** + * Search for multiple instances. + * + * __Simple search using AND and =__ + * ```js + * Model.findAll({ + * where: { + * attr1: 42, + * attr2: 'cake' + * } + * }) + * ``` + * ```sql + * WHERE attr1 = 42 AND attr2 = 'cake' + *``` + * + * __Using greater than, less than etc.__ + * ```js + * + * Model.findAll({ + * where: { + * attr1: { + * gt: 50 + * }, + * attr2: { + * lte: 45 + * }, + * attr3: { + * in: [1,2,3] + * }, + * attr4: { + * ne: 5 + * } + * } + * }) + * ``` + * ```sql + * WHERE attr1 > 50 AND attr2 <= 45 AND attr3 IN (1,2,3) AND attr4 != 5 + * ``` + * Possible options are: `$ne, $in, $not, $notIn, $gte, $gt, $lte, $lt, $like, $ilike/$iLike, $notLike, + * $notILike, '..'/$between, '!..'/$notBetween, '&&'/$overlap, '@>'/$contains, '<@'/$contained` + * + * __Queries using OR__ + * ```js + * Model.findAll({ + * where: Sequelize.and( + * { name: 'a project' }, + * Sequelize.or( + * { id: [1,2,3] }, + * { id: { gt: 10 } } + * ) + * ) + * }) + * ``` + * ```sql + * WHERE name = 'a project' AND (id` IN (1,2,3) OR id > 10) + * ``` + * + * The success listener is called with an array of instances if the query succeeds. + * + * @see {Sequelize#query} + */ + findAll( options? : FindOptions ) : Promise>; + all( optionz? : FindOptions ) : Promise>; + + /** + * Search for a single instance by its primary key. This applies LIMIT 1, so the listener will + * always be called with a single instance. + */ + findById( identifier? : number | string, options? : FindOptions ) : Promise; + findByPrimary( identifier? : number | string, options? : FindOptions ) : Promise; + + /** + * Search for a single instance. This applies LIMIT 1, so the listener will always be called with a single + * instance. + */ + findOne( options? : FindOptions ) : Promise; + find( optionz? : FindOptions ) : Promise; + + /** + * Run an aggregation method on the specified field + * + * @param field The field to aggregate over. Can be a field name or * + * @param aggregateFunction The function to use for aggregation, e.g. sum, max etc. + * @param options Query options. See sequelize.query for full options + * @return Returns the aggregate result cast to `options.dataType`, unless `options.plain` is false, in + * which case the complete data result is returned. + */ + aggregate( field : string, aggregateFunction : Function, options? : AggregateOptions ) : Promise; + + /** + * Count the number of records matching the provided where clause. + * + * If you provide an `include` option, the number of matching associations will be counted instead. + */ + count( options? : CountOptions ) : Promise; + + /** + * Find all the rows matching your query, within a specified offset / limit, and get the total number of + * rows matching your query. This is very usefull for paging + * + * ```js + * Model.findAndCountAll({ + * where: ..., + * limit: 12, + * offset: 12 + * }).then(function (result) { + * ... + * }) + * ``` + * In the above example, `result.rows` will contain rows 13 through 24, while `result.count` will return + * the + * total number of rows that matched your query. + * + * When you add includes, only those which are required (either because they have a where clause, or + * because + * `required` is explicitly set to true on the include) will be added to the count part. + * + * Suppose you want to find all users who have a profile attached: + * ```js + * User.findAndCountAll({ + * include: [ + * { model: Profile, required: true} + * ], + * limit 3 + * }); + * ``` + * Because the include for `Profile` has `required` set it will result in an inner join, and only the users + * who have a profile will be counted. If we remove `required` from the include, both users with and + * without + * profiles will be counted + */ + findAndCount( options? : FindOptions ) : Promise<{ rows : Array, count : number }>; + findAndCountAll( options? : FindOptions ) : Promise<{ rows : Array, count : number }>; + + /** + * Find the maximum value of field + */ + max( field : string, options? : AggregateOptions ) : Promise; + + /** + * Find the minimum value of field + */ + min( field : string, options? : AggregateOptions ) : Promise; + + /** + * Find the sum of field + */ + sum( field : string, options? : AggregateOptions ) : Promise; + + /** + * Builds a new model instance. Values is an object of key value pairs, must be defined but can be empty. + */ + build( record? : TAttributes, options? : BuildOptions ) : TInstance; + + /** + * Undocumented bulkBuild + */ + bulkBuild( records : Array, options? : BuildOptions ) : Array; + + /** + * Builds a new model instance and calls save on it. + */ + create( values? : TAttributes, options? : CreateOptions ) : Promise; + + /** + * Find a row that matches the query, or build (but don't save) the row if none is found. + * The successfull result of the promise will be (instance, initialized) - Make sure to use .spread() + */ + findOrInitialize( options : FindOrInitializeOptions ) : Promise; + findOrBuild( options : FindOrInitializeOptions ) : Promise; + + /** + * Find a row that matches the query, or build and save the row if none is found + * The successful result of the promise will be (instance, created) - Make sure to use .spread() + * + * If no transaction is passed in the `options` object, a new transaction will be created internally, to + * prevent the race condition where a matching row is created by another connection after the find but + * before the insert call. However, it is not always possible to handle this case in SQLite, specifically + * if one transaction inserts and another tries to select before the first one has comitted. In this case, + * an instance of sequelize.TimeoutError will be thrown instead. If a transaction is created, a savepoint + * will be created instead, and any unique constraint violation will be handled internally. + */ + findOrCreate( options : FindOrInitializeOptions ) : Promise; + + /** + * Insert or update a single row. An update will be executed if a row which matches the supplied values on + * either the primary key or a unique key is found. Note that the unique index must be defined in your + * sequelize model and not just in the table. Otherwise you may experience a unique constraint violation, + * because sequelize fails to identify the row that should be updated. + * + * **Implementation details:** + * + * * MySQL - Implemented as a single query `INSERT values ON DUPLICATE KEY UPDATE values` + * * PostgreSQL - Implemented as a temporary function with exception handling: INSERT EXCEPTION WHEN + * unique_constraint UPDATE + * * SQLite - Implemented as two queries `INSERT; UPDATE`. This means that the update is executed + * regardless + * of whether the row already existed or not + * + * **Note** that SQLite returns undefined for created, no matter if the row was created or updated. This is + * because SQLite always runs INSERT OR IGNORE + UPDATE, in a single query, so there is no way to know + * whether the row was inserted or not. + */ + upsert( values : TAttributes, options? : UpsertOptions ) : Promise; + insertOrUpdate( values : TAttributes, options? : UpsertOptions ) : Promise; + + /** + * Create and insert multiple instances in bulk. + * + * The success handler is passed an array of instances, but please notice that these may not completely + * represent the state of the rows in the DB. This is because MySQL and SQLite do not make it easy to + * obtain + * back automatically generated IDs and other default values in a way that can be mapped to multiple + * records. To obtain Instances for the newly created values, you will need to query for them again. + * + * @param records List of objects (key/value pairs) to create instances from + */ + bulkCreate( records : Array, options? : BulkCreateOptions ) : Promise>; + + /** + * Truncate all instances of the model. This is a convenient method for Model.destroy({ truncate: true }). + */ + truncate( options? : TruncateOptions ) : Promise; + + /** + * Delete multiple instances, or set their deletedAt timestamp to the current time if `paranoid` is enabled. + * + * @return Promise The number of destroyed rows + */ + destroy( options? : DestroyOptions ) : Promise; + + /** + * Restore multiple instances if `paranoid` is enabled. + */ + restore( options? : RestoreOptions ) : Promise; + + /** + * Update multiple instances that match the where options. The promise returns an array with one or two + * elements. The first element is always the number of affected rows, while the second element is the actual + * affected rows (only supported in postgres with `options.returning` true.) + */ + update( values : TAttributes, options : UpdateOptions ) : Promise<[number, Array]>; + + /** + * Run a describe query on the table. The result will be return to the listener as a hash of attributes and + * their types. + */ + describe() : Promise; + + /** + * Unscope the model + */ + unscoped() : Model; + } + // + // Query Interface + // ~~~~~~~~~~~~~~~~~ + // + // https://github.com/sequelize/sequelize/blob/v3.4.1/lib/query-interface.js + // + + /** + * Most of the methods accept options and use only the logger property of the options. That's why the most used + * interface type for options in a method is separated here as another interface. + */ + interface QueryInterfaceOptions { + + /** + * A function that gets executed while running the query to log the sql. + */ + logging? : boolean | Function; + + } + + /** + * The interface that Sequelize uses to talk to all databases. + * + * This interface is available through sequelize.QueryInterface. It should not be commonly used, but it's + * referenced anyway, so it can be used. + */ interface QueryInterface { /** * Returns the dialect-specific sql generator. + * + * We don't have a definition for the QueryGenerator, because I doubt it is commonly in use separately. */ - QueryGenerator: QueryGenerator; + QueryGenerator: any; /** * Queries the schema (table list). * * @param schema The schema to query. Applies only to Postgres. */ - createSchema(schema?: string): EventEmitter; + createSchema( schema? : string, options? : QueryInterfaceOptions ): Promise; /** * Drops the specified schema (table). * - * @param schema The name of the table to drop. + * @param schema The schema to query. Applies only to Postgres. */ - dropSchema(schema: string): EventEmitter; + dropSchema( schema? : string, options? : QueryInterfaceOptions ): Promise; /** * Drops all tables. */ - dropAllSchemas(): EventEmitter; + dropAllSchemas( options? : QueryInterfaceOptions ): Promise; /** * Queries all table names in the database. * * @param options */ - showAllSchemas(options?: QueryOptions): EventEmitter; + showAllSchemas( options? : QueryOptions ): Promise; + + /** + * Return database version + */ + databaseVersion( options? : QueryInterfaceOptions ) : Promise; /** * Creates a table with specified attributes. + * * @param tableName Name of table to create * @param attributes Hash of attributes, key is attribute name, value is data type * @param options Query options. - * - * @return The return type will be a Promise when dialect is Postgres and an EventEmitter for MySQL and SQLite. */ - createTable(tableName: string, attributes: any, options?: QueryOptions): any; + createTable( tableName : string | { schema? : string, tableName? : string }, attributes : DefineAttributes, + options? : QueryOptions ): Promise; /** * Drops the specified table. @@ -1019,562 +2823,793 @@ declare module "sequelize" * @param tableName Table name. * @param options Query options, particularly "force". */ - dropTable(tableName: string, options?: QueryOptions): EventEmitter; - dropAllTables(options?: QueryOptions): EventEmitter; - dropAllEnums(options?: QueryOptions): EventEmitter; - renameTable(before: string, after: string): EventEmitter; - showAllTables(options?: QueryOptions): EventEmitter; - describeTable(tableName: string, options?: QueryOptions): EventEmitter; - addColumn(tableName: string, attributeName: any, dataTypeOrOptions?: any): EventEmitter; - removeColumn(tableName: string, attributeName: string): EventEmitter; - changeColumn(tableName: string, attributeName: string, dataTypeOrOptions: any): EventEmitter; - renameColumn(tableName: string, attrNameBefore: string, attrNameAfter: string): EventEmitter; - addIndex(tableName: string, attributes: Array, options?: QueryOptions): EventEmitter; - showIndex(tableName: string, options?: QueryOptions): EventEmitter; - getForeignKeysForTables(tableNames: Array): EventEmitter; - removeIndex(tableName: string, attributes: Array): EventEmitter; - removeIndex(tableName: string, indexName: string): EventEmitter; - insert(dao: TModel, tableName: string, values: any, options?: QueryOptions): EventEmitter; - /** - * Inserts several records into the specified table. - * @param tableName Table to insert into. - * @param records Array of key/value pairs to insert as records. - * @param options Query options - * @param attributes For Postgres only, used to identify if an attribute is auto-increment and thus handled specially. - */ - bulkInsert(tableName: string, records: Array, options?: QueryOptions, attributes?: any): EventEmitter; + dropTable( tableName : string, options? : QueryOptions ): Promise; - update(dao: TModel, tableName: string, values: Array, where: any, options?: QueryOptions): EventEmitter; - bulkUpdate(tableName: string, values: Array, where: any, options?: QueryOptions, attributes?: any): EventEmitter; - delete(dao: TModel, tableName: string, where: any, options?: QueryOptions): EventEmitter; - bulkDelete(tableName: string, where: any, options?: QueryOptions): EventEmitter; - bulkDelete(tableName: string, where: any, options: QueryOptions, model: TModel): EventEmitter; - select(factory: TModel, tableName: string, scope?: any, queryOptions?: QueryOptions): EventEmitter; - increment(dao: TModel, tableName: string, values: Array, where: any, options?: QueryOptions): EventEmitter; - rawSelect(tableName: string, options: QueryOptions, attributeSelector: string, model: TModel): EventEmitter; /** - * Postgres only. Creates a trigger on specified table to call the specified function with supplied parameters. + * Drops all tables. * - * @param tableName - * @param triggerName - * @param timingType - * @param fireOnArray - * @param functionName - * @param functionParams - * @param optionsArray + * @param options */ - createTrigger(tableName: string, triggerName: string, timingType: string, fireOnArray: Array, functionName: string, functionParams: Array, optionsArray: Array): EventEmitter; + dropAllTables( options? : QueryOptions ): Promise; + + /** + * Drops all defined enums + * + * @param options + */ + dropAllEnums( options? : QueryOptions ): Promise; + + /** + * Renames a table + */ + renameTable( before : string, after : string, options? : QueryInterfaceOptions ) : Promise; + + /** + * Returns all tables + */ + showAllTables( options? : QueryOptions ) : Promise>; + + /** + * Describe a table + */ + describeTable( tableName : string | { schema? : string, tableName? : string }, + options? : string | { schema? : string, schemaDelimeter? : string, logging? : boolean | Function } ) : Promise; + + /** + * Adds a new column to a table + */ + addColumn( table : string, key : string, attribute : DefineAttributeColumnOptions | DataTypeAbstract, + options? : QueryInterfaceOptions ) : Promise; + + /** + * Removes a column from a table + */ + removeColumn( table : string, attribute : string, options? : QueryInterfaceOptions ) : Promise; + + /** + * Changes a column + */ + changeColumn( tableName : string | { schema? : string, tableName? : string }, attributeName : string, + dataTypeOrOptions? : string | DataTypeAbstract | DefineAttributeColumnOptions, + options? : QueryInterfaceOptions ) : Promise; + + /** + * Renames a column + */ + renameColumn( tableName : string | { schema? : string, tableName? : string }, attrNameBefore : string, + attrNameAfter : string, + options? : QueryInterfaceOptions ) : Promise; + + /** + * Adds a new index to a table + */ + addIndex( tableName : string | Object, attributes : Array, options? : QueryOptions, + rawTablename? : string ) : Promise; + + /** + * Shows the index of a table + */ + showIndex( tableName : string | Object, options? : QueryOptions ) : Promise; + + /** + * Put a name to an index + */ + nameIndexes( indexes : Array, rawTablename : string ) : Promise; + + /** + * Returns all foreign key constraints of a table + */ + getForeignKeysForTables( tableNames : string, options? : QueryInterfaceOptions ) : Promise; + + /** + * Removes an index of a table + */ + removeIndex( tableName : string, indexNameOrAttributes : Array | string, + options? : QueryInterfaceOptions ) : Promise; + + /** + * Inserts a new record + */ + insert( instance : Instance, tableName : string, values : Object, + options? : QueryOptions ) : Promise; + + /** + * Inserts or Updates a record in the database + */ + upsert( tableName : string, values : Object, updateValues : Object, model : Model, + options? : QueryOptions ) : Promise; + + /** + * Inserts multiple records at once + */ + bulkInsert( tableName : string, records : Array, options? : QueryOptions, + attributes? : Array | string ) : Promise; + + /** + * Updates a row + */ + update( instance : Instance, tableName : string, values : Object, identifier : Object, + options? : QueryOptions ) : Promise; + + /** + * Updates multiple rows at once + */ + bulkUpdate( tableName : string, values : Object, identifier : Object, options? : QueryOptions, + attributes? : Array | string ) : Promise; + + /** + * Deletes a row + */ + "delete"( instance : Instance, tableName : string, identifier : Object, + options? : QueryOptions ) : Promise; + + /** + * Deletes multiple rows at once + */ + bulkDelete( tableName : string, identifier : Object, options? : QueryOptions, + model? : Model ) : Promise; + + /** + * Returns selected rows + */ + select( model : Model, tableName : string, options? : QueryOptions ) : Promise>; + + /** + * Increments a row value + */ + increment( instance : Instance, tableName : string, values : Object, identifier : Object, + options? : QueryOptions ) : Promise; + + /** + * Selects raw without parsing the string into an object + */ + rawSelect( tableName : string, options : QueryOptions, attributeSelector : string | Array, + model? : Model ) : Promise>; + + /** + * Postgres only. Creates a trigger on specified table to call the specified function with supplied + * parameters. + */ + createTrigger( tableName : string, triggerName : string, timingType : string, fireOnArray : Array, + functionName : string, functionParams : Array, optionsArray : Array, + options? : QueryInterfaceOptions ): Promise; + /** * Postgres only. Drops the specified trigger. - * - * @param tableName - * @param triggerName */ - dropTrigger(tableName: string, triggerName: string): EventEmitter; - renameTrigger(tableName: string, oldTriggerName: string, newTriggerName: string): EventEmitter; - createFunction(functionName: string, params: Array, returnType: string, language: string, body: string, options?: QueryOptions): EventEmitter; - dropFunction(functionName: string, params: Array): EventEmitter; - renameFunction(oldFunctionName: string, params: Array, newFunctionName: string): EventEmitter; + dropTrigger( tableName : string, triggerName : string, options? : QueryInterfaceOptions ): Promise; + /** - * Escape an identifier (e.g. a table or attribute name). If force is true, - * the identifier will be quoted even if the `quoteIdentifiers` option is - * false. + * Postgres only. Renames a trigger */ - quoteIdentifier(identifier: string, force: boolean): EventEmitter; - quoteTable(tableName: string): EventEmitter; - quoteIdentifiers(identifiers: string, force: boolean): EventEmitter; - escape(value: string): EventEmitter; - setAutocommit(transaction: Transaction, value: boolean): EventEmitter; - setIsolationLevel(transaction: Transaction, value: string): EventEmitter; - startTransaction(transaction: Transaction, options?: QueryOptions): EventEmitter; - commitTransaction(transaction: Transaction, options?: QueryOptions): EventEmitter; - rollbackTransaction(transaction: Transaction, options?: QueryOptions): EventEmitter; + renameTrigger( tableName : string, oldTriggerName : string, newTriggerName : string, + options? : QueryInterfaceOptions ) : Promise; + + /** + * Postgres only. Create a function + */ + createFunction( functionName : string, params : Array, returnType : string, language : string, + body : string, options? : QueryOptions ) : Promise; + + /** + * Postgres only. Drops a function + */ + dropFunction( functionName : string, params : Array, + options? : QueryInterfaceOptions ) : Promise; + + /** + * Postgres only. Rename a function + */ + renameFunction( oldFunctionName : string, params : Array, newFunctionName : string, + options? : QueryInterfaceOptions ) : Promise; + + /** + * Escape an identifier (e.g. a table or attribute name). If force is true, the identifier will be quoted + * even if the `quoteIdentifiers` option is false. + */ + quoteIdentifier( identifier : string, force : boolean ) : string; + + /** + * Escape a table name + */ + quoteTable( identifier : string ) : string; + + /** + * Split an identifier into .-separated tokens and quote each part. If force is true, the identifier will be + * quoted even if the `quoteIdentifiers` option is false. + */ + quoteIdentifiers( identifiers : string, force : boolean ) : string; + + /** + * Escape a value (e.g. a string, number or date) + */ + escape( value? : string | number | Date ) : string; + + /** + * Set option for autocommit of a transaction + */ + setAutocommit( transaction : Transaction, value : boolean, options? : QueryOptions ) : Promise; + + /** + * Set the isolation level of a transaction + */ + setIsolationLevel( transaction : Transaction, value : string, options? : QueryOptions ) : Promise; + + /** + * Begin a new transaction + */ + startTransaction( transaction : Transaction, options? : QueryOptions ) : Promise; + + /** + * Defer constraints + */ + deferConstraints( transaction : Transaction, options? : QueryOptions ) : Promise; + + /** + * Commit an already started transaction + */ + commitTransaction( transaction : Transaction, options? : QueryOptions ) : Promise; + + /** + * Rollback ( revert ) a transaction that has'nt been commited + */ + rollbackTransaction( transaction : Transaction, options? : QueryOptions ) : Promise; + } - interface QueryGenerator { - createSchema(schemaName: string): string; - dropSchema(schemaName: string): string; - showSchemasQuery(): string; - addSchema(param: Model): Schema; - createTableQuery(tableName: string, attributes: Array, options?: CreateTableQueryOptions): string; - describeTableQuery(tableName: string, schema: string, schemaDelimiter: string): string; - dropTableQuery(tableName: string, options?: { cascade: string }): string; - renameTableQuery(before: string, after: string): string; - showTablesQuery(): string; - addColumnQuery(tableName: string, attributes: any): string; - removeColumnQuery(tableName: string, attributeName: string): string; - changeColumnQuery(tableName: string, attributes: any): string; - renameColumnQuery(tableName: string, attrNameBefore: string, attrNameAfter: string): string; - insertQuery(table: string, valueHash: any, modelAttributes: any): string; - bulkInsertQuery(tableName: string, attrValueHashes: any): string; - updateQuery(tableName: string, attrValueHash: any, where: any, options: InsertOptions, attributes: any): string; - deleteQuery(tableName: string, where: any, options: DestroyOptions): string; - deleteQuery(tableName: string, where: any, options: DestroyOptions, model: Model): string; - /** - * Creates a query to increment a value. Note "options" here is an additional hash of values to update. - * - * @param tableName - * @param attrValueHash - * @param where - * @param options - */ - incrementQuery(tableName: string, attrValueHash: any, where: any, options?: any): string; - addIndexQuery(tableName: string, attributes: Array, options?: IndexOptions): string; - /** - * Return indices for a table. Not options may be passed but is not used, so can be anything. - * @param tableName - * @param options - */ - showIndexQuery(tableName: string, options?: any): string; // options is actually not used - removeIndexQuery(tableName: string, indexNameOrAttributes: string): string; - removeIndexQuery(tableName: string, indexNameOrAttributes: Array): string; - attributesToSQL(attributes: Array): string; - findAutoIncrementField(factory: Model): Array; - quoteTable(param: any, as: boolean): string; - quote(obj: any, parent: any, force: boolean): string; - createTrigger(tableName: string, triggerName: string, timingType: string, fireOnArray: TriggerOptions, functionName: string, functionParams: Array): string; - dropTrigger(tableName: string, triggerName: string): string; - renameTrigger(tableName: string, oldTriggerName: string, newTriggerName: string): string; - createFunction(functionName: string, params: Array, returnType: string, language: string, body: string, options?: Array): string; - dropFunction(functionName: string, params: Array): string; - renameFunction(oldFunctionName: string, params: Array, newFunctionName: string): string; - quoteIdentifier(identifier: string, force?: boolean): string; - quoteIdentifiers(identifiers: string, force?: boolean): string; - /** - * Not documented, and reading through the code, I'm not sure what all the options available are for value/field. - * - * @param value - * @param field - */ - escape(value: any, field: any): string; - getForeignKeysQuery(tableName: string, schemaName: string): string; - dropForeignKeyQuery(tableName: string, foreignKey: string): string; - selectQuery(tableName: string, options: SelectOptions, model?: Model): string; - selectQuery(tableName: Array, options: SelectOptions, model?: Model): string; - selectQuery(tableName: Array>, options: SelectOptions, model?: Model): string; - setAutocommitQuery(value: boolean): string; - setIsolationLevelQuery(value: string): string; - /** - * Returns start transaction query. Options is not used. - * @param options - */ - startTransactionQuery(options?: any): string; - /** - * Returns start transaction query. Options is not used. - * @param options - */ - commitTransactionQuery(options?: any): string; - /** - * Returns start transaction query. Options is not used. - * @param options - */ - rollbackTransactionQuery(options?: any): string; - addLimitAndOffset(options: SelectOptions, query?: string): string; - getWhereConditions(smth: any, tableName: string, factory: Model, options?: any, prepend?: boolean): string; - prependTableNameToHash(tableName: string, hash?: any): string; - findAssociation(attribute: string, dao: Model): string; - getAssociationFilterDAO(filterStr: string, dao: Model): string; - isAssociationFilter(filterStr: string, dao: Model, options?: any): string; - getAssociationFilterColumn(filterStr: string, dao: Model, options?: { include: boolean }): string; - getConditionalJoins(options: { where?: any }, originalDao: Model): string; - arrayValue(value: Array, key: string, _key: string, factory?: any, logicResult?: any): string; - hashToWhereConditions(hash: any, dao: Model, options?: HashToWhereConditionsOption): string; - booleanValue(value: boolean): string; - } - - interface Schema { - tableName: string; - table: string; - name: string; - schema: string; - delimiter: string; - } + // + // Query Types + // ~~~~~~~~~~~~~ + // + // https://github.com/sequelize/sequelize/blob/v3.4.1/lib/query-types.js + // interface QueryTypes { - SELECT: string; - BULKUPDATE: string; - BULKDELETE: string; + SELECT: string // 'SELECT' + INSERT: string // 'INSERT' + UPDATE: string // 'UPDATE' + BULKUPDATE: string // 'BULKUPDATE' + BULKDELETE: string // 'BULKDELETE' + DELETE: string // 'DELETE' + UPSERT: string // 'UPSERT' + VERSION: string // 'VERSION' + SHOWTABLES: string // 'SHOWTABLES' + SHOWINDEXES: string // 'SHOWINDEXES' + DESCRIBE: string // 'DESCRIBE' + RAW: string // 'RAW' + FOREIGNKEYS: string // 'FOREIGNKEYS' } - interface ModelManager { - daos: Array>; - sequelize: Sequelize; - addDAO(dao: Model): Model; - removeDAO(dao: Model): void; - getDAO(daoName: string, options?: ModelMangerGetDaoOptions): Model; - all: Array>; + // + // Sequelize + // ~~~~~~~~~~~ + // + // https://github.com/sequelize/sequelize/blob/v3.4.1/lib/sequelize.js + // + + /** + * General column options + * + * @see Define + * @see AssociationForeignKeyOptions + */ + interface ColumnOptions { /** - * Iterate over DAOs in an order suitable for e.g. creating tables. Will - * take foreign key constraints into account so that dependencies are visited - * before dependents. - */ - forEachDAO(iterator: (dao: Model, name: string) => void, options?: ModelManagerForEachDaoOptions): void; - } - - interface TransactionManager { - sequelize: Sequelize; - connectorManagers: any; - getConnectorManager(uuid?: string): ConnectorManager; - releaseConnectionManager(uuid?: string): void; - - /** - * Execute a query on the DB, with the possibility to bypass all the sequelize goodness. - * - * @param sql SQL statement to execute. - * - * @param callee If callee is provided, the selected data will be used to build an instance of the DAO represented - * by the factory. Equivalent to calling Model.build with the values provided by the query. - * - * @param options Query options. - * - */ - query(sql: string, callee?: Model, options?: QueryOptions): EventEmitter; - - query(sql: string, callee?: Model, options?: QueryOptions): EventEmitter; - } - - interface ConnectorManager { - - /** - * Execute a query on the DB, with the possibility to bypass all the sequelize goodness. - * - * @param sql SQL statement to execute. - * - * @param callee If callee is provided, the selected data will be used to build an instance of the DAO represented - * by the factory. Equivalent to calling Model.build with the values provided by the query. - * - * @param options Query options. - * - */ - query(sql: string, callee?: Model, options?: QueryOptions): EventEmitter; - - afterTransactionSetup(callback: () => void): void; - connect(): void; - disconnect(): void; - reconnect(): void; - cleanup(): void; - } - - interface Migrator { - queryInterface: QueryInterface; - migrate(options?: MigratorOptions): EventEmitter; - getUndoneMigrations(callback: (err: Error, result: Array) => void): void; - findOrCreateMetaDAO(syncOptions?: SyncOptions): EventEmitter; - exec(filename: string, options?: MigratorExecOptions): EventEmitter; - getLastMigrationFromDatabase(): EventEmitter; - getLastMigrationIdFromDatabase(): EventEmitter; - getFormattedDateString(s: string): string; - stringToDate(s: string): Date; - saveSuccessfulMigration(from: Migration, to: Migration, callback: (metaData: MetaInstance) => void): void; - deleteUndoneMigration(from: Migration, to: Migration, callback: () => void): void; - execute(options?: MigrationExecuteOptions): EventEmitter; - isBefore(date: Date, options?: MigrationCompareOptions): boolean; - isAfter(date: Date, options?: MigrationCompareOptions): boolean; - - } - - interface Migration extends QueryInterface { - migrator: Migrator; - path: string; - filename: string; - migrationId: number; - date: Date; - queryInterface: QueryInterface; - migration: (err: Error, migration: Migration, dataTypes: any, callback: (err: Error) => void) => void; - - } - - interface EventEmitter extends EventEmitterT, NodeJS.EventEmitter { } - - interface EventEmitterT extends NodeJS.EventEmitter { - /** - * Create a new emitter instance. - * - * @param handler - */ - new (handler: (emitter: EventEmitterT) => void): EventEmitterT; - - /** - * Run the function that was passed when the emitter was instantiated. - */ - run(): EventEmitterT; - - /** - * Listen for success events. - * - * @param onSuccess - */ - success(onSuccess: (result: R) => void): EventEmitterT; - - /** - * Alias for success(handler). Listen for success events. - * - * @param onSuccess - */ - ok(onSuccess: (result: R) => void): EventEmitterT; - - /** - * Listen for error events. - * - * @param onError - */ - error(onError: (err: Error) => void): EventEmitterT; - - /** - * Alias for error(handler). Listen for error events. - * - * @param onError - */ - fail(onError: (err: Error) => void): EventEmitterT; - - /** - * Alias for error(handler). Listen for error events. - * - * @param onError - */ - failure(onError: (err: Error) => void): EventEmitterT; - - /** - * Listen for both success and error events. - * - * @param onDone - */ - done(onDone: (err: Error, result: R) => void): EventEmitterT; - - /** - * Alias for done(handler). Listen for both success and error events. - * - * @param onDone - */ - complete(onDone: (err: Error, result: R) => void): EventEmitterT; - - /** - * Attach a function that is called every time the function that created this emitter executes a query. - * - * @param onSQL - */ - sql(onSQL: (sql: string) => void): EventEmitterT; - - /** - * Proxy every event of this event emitter to another one. - * - * @param emitter The event emitter that should receive the events. - * @param options Contains an array of the events to proxy. Defaults to sql, error and success - */ - proxy(emitter: EventEmitterT, options?: ProxyOptions): EventEmitterT; - - - } - - interface Options { - /** - * The dialect you of the database you are connecting to. One of mysql, postgres, sqlite and mariadb. - * Default is mysql. - */ - dialect?: string; - - /** - * If specified, load the dialect library from this path. For example, if you want to use pg.js instead of pg when - * connecting to a pg database, you should specify 'pg.js' here - */ - dialectModulePath?: string; - - /** - * The host of the relational database. Default 'localhost'. - */ - host?: string; - - /** - * Integer The port of the relational database. - */ - port?: number; - - /** - * The protocol of the relational database. Default 'tcp'. - */ - protocol?: string; - - /** - * Default options for model definitions. See sequelize.define for options. - */ - define?: DefineOptions; - - /** - * Default options for sequelize.query - */ - query?: QueryOptions; - - /** - * Default options for sequelize.sync - */ - sync?: SyncOptions; - - /** - * The timezone used when converting a date from the database into a javascript date. The timezone is also used to - * SET TIMEZONE when connecting to the server, to ensure that the result of NOW, CURRENT_TIMESTAMP and other time - * related functions have in the right timezone. For best cross platform performance use the format +/-HH:MM. - * Default '+00:00'. - */ - timezone?: string; - - /** - * Logging options. Function used to log. Default is console.log. Signature is (message:string) => void. - * - * Set to "false" to disable logging. - */ - logging?: any; - - /** logging=console.log] Function A function that gets executed everytime Sequelize would log something. - * A flag that defines if null values should be passed to SQL queries or not. - */ - omitNull?: boolean; - - /** - * Boolean Queue queries, so that only maxConcurrentQueries number of queries are executing at once. If false, all - * queries will be executed immediately. - */ - queue?: boolean; - - /** - * The maximum number of queries that should be executed at once if queue is true. - */ - maxConcurrentQueries?: number; - - /** - * A flag that defines if native library shall be used or not. Currently only has an effect for postgres - */ - native?: boolean; - - /** - * Use read / write replication. To enable replication, pass an object, with two properties, read and write. Write - * should be an object (a single server for handling writes), and read an array of object (several servers to - * handle reads). Each read/write server can have the following properties?: host, port, username, password, database - */ - replication?: ReplicationOptions; - - /** - * Connection pool options. - * - */ - pool?: PoolOptions; - - /** - * Set to false to make table names and attributes case-insensitive on Postgres and skip double quoting of them. - * Default true. - */ - quoteIdentifiers?: boolean; - - /** - * Language. Default "en". - */ - language?: string; - } - - interface PoolOptions { - maxConnections?: number; - - minConnections?: number; - - /** - * The maximum time, in milliseconds, that a connection can be idle before being released. - */ - maxIdleTime?: number; - - /** - * A function that validates a connection. Called with client. The default function checks that client is an - * object, and that its state is not disconnected. - * - * Note, this is not documented, and after reading code I'm not sure what client's type is. - */ - validateConnection?: (client?: any) => boolean; - } - - interface AttributeOptions { - /** - * A string or a data type - */ - type?: string; - - /** - * If false, the column will have a NOT NULL constraint, and a not null validation will be run before an instance - * is saved. + * If false, the column will have a NOT NULL constraint, and a not null validation will be run before an + * instance is saved. */ allowNull?: boolean; /** - * A literal default value, a javascript function, or an SQL function (see sequelize.fn) + * If set, sequelize will map the attribute name to a different name in the database + */ + field? : string; + + /** + * A literal default value, a JavaScript function, or an SQL function (see `sequelize.fn`) */ defaultValue?: any; + } + + /** + * References options for the column's attributes + * + * @see AttributeColumnOptions + */ + interface DefineAttributeColumnReferencesOptions { + + /** + * If this column references another table, provide it here as a Model, or a string + */ + model?: Model; + + /** + * The column of the foreign table that this column references + */ + key? : string; + + /** + * When to check for the foreign key constraing + * + * PostgreSQL only + */ + deferrable? : Deferrable; + + } + + /** + * Column options for the model schema attributes + * + * @see Attributes + */ + interface DefineAttributeColumnOptions extends ColumnOptions { + + /** + * A string or a data type + */ + type: string | DataTypeAbstract; + /** * If true, the column will get a unique constraint. If a string is provided, the column will be part of a - * composite unique index. If multiple columns have the same string, they will be part of the same unique index. + * composite unique index. If multiple columns have the same string, they will be part of the same unique + * index */ - unique?: any; + unique?: boolean | string | { name: string, msg: string }; + /** + * Primary key flag + */ primaryKey?: boolean; /** - * If set, sequelize will map the attribute name to a different name in the database. + * Is this field an auto increment field */ - field?: string; - autoIncrement?: boolean; + /** + * Comment for the database + */ comment?: string; /** - * If this column references another table, provide it here as a Model, or a string. + * An object with reference configurations */ - references?: any; - - /** - * The column of the foreign table that this column references. Default 'id'. - */ - referencesKey?: string; + references? : DefineAttributeColumnReferencesOptions; /** * What should happen when the referenced key is updated. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or - * NO ACTION. + * NO ACTION */ - onUpdate?: string; + onUpdate? : string; /** * What should happen when the referenced key is deleted. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or - * NO ACTION. + * NO ACTION */ - onDelete?: string; + onDelete? : string; /** - * Provide a custom getter for this column. Use this.getDataValue(String) to manipulate the underlying values. + * Provide a custom getter for this column. Use `this.getDataValue(String)` to manipulate the underlying + * values. */ - get?: () => any; + get? : () => any; /** - * Provide a custom setter for this column. Use this.setDataValue(String, Value) to manipulate the underlying values. + * Provide a custom setter for this column. Use `this.setDataValue(String, Value)` to manipulate the + * underlying values. */ - set?: (value?: any) => void; + set? : ( val : any ) => void; /** - * An object of validations to execute for this column every time the model is saved. Can be either the name of a - * validation provided by validator.js, a validation function provided by extending validator.js (see the - * DAOValidator property for more details), or a custom validation function. Custom validation functions are called - * with the value of the field, and can possibly take a second callback argument, to signal that they are - * asynchronous. If the validator is sync, it should throw in the case of a failed validation, it it is async, - * the callback should be called with the error text. + * An object of validations to execute for this column every time the model is saved. Can be either the + * name of a validation provided by validator.js, a validation function provided by extending validator.js + * (see the + * `DAOValidator` property for more details), or a custom validation function. Custom validation functions + * are called with the value of the field, and can possibly take a second callback argument, to signal that + * they are asynchronous. If the validator is sync, it should throw in the case of a failed validation, it + * it is async, the callback should be called with the error text. */ - validate?: any; + validate? : DefineValidateOptions; + + /** + * Usage in object notation + * + * ```js + * sequelize.define('model', { + * states: { + * type: Sequelize.ENUM, + * values: ['active', 'pending', 'deleted'] + * } + * }) + * ``` + */ + values? : Array; + } - interface ForeignKeyAttributeOptions extends AttributeOptions { + /** + * Interface for Attributes provided for a column + * + * @see Sequelize.define + */ + interface DefineAttributes { + /** - * The name of the foreign key in the target table. Defaults to the name of source + primary key of source. + * The description of a database column */ - fieldName: string; + [name : string] : string | DataTypeAbstract | DefineAttributeColumnOptions; + } - interface DefineOptions { + /** + * Interface for query options + * + * @see Options + */ + interface QueryOptions { + + /** + * If true, sequelize will not try to format the results of the query, or build an instance of a model from + * the result + */ + raw?: boolean; + + /** + * The transaction that the query should be executed under + */ + transaction?: Transaction; + + /** + * The type of query you are executing. The query type affects how results are formatted before they are + * passed back. The type is a string, but `Sequelize.QueryTypes` is provided as convenience shortcuts. + */ + type?: string; + + /** + * If true, transforms objects with `.` separated property names into nested objects using + * [dottie.js](https://github.com/mickhansen/dottie.js). For example { 'user.username': 'john' } becomes + * { user: { username: 'john' }}. When `nest` is true, the query type is assumed to be `'SELECT'`, + * unless otherwise specified + * + * Defaults to false + */ + nest?: boolean; + + /** + * Sets the query type to `SELECT` and return a single row + */ + plain?: boolean; + + /** + * Either an object of named parameter replacements in the format `:param` or an array of unnamed + * replacements to replace `?` in your SQL. + */ + replacements? : Object | Array; + + /** + * Force the query to use the write pool, regardless of the query type. + * + * Defaults to false + */ + useMaster? : boolean; + + /** + * A function that gets executed while running the query to log the sql. + */ + logging? : Function + + /** + * A sequelize instance used to build the return instance + */ + instance? : Instance; + + /** + * A sequelize model used to build the returned model instances (used to be called callee) + */ + model? : Model; + + // TODO: force, cascade + + } + + /** + * Model validations, allow you to specify format/content/inheritance validations for each attribute of the + * model. + * + * Validations are automatically run on create, update and save. You can also call validate() to manually + * validate an instance. + * + * The validations are implemented by validator.js. + */ + interface DefineValidateOptions { + + /** + * is: ["^[a-z]+$",'i'] // will only allow letters + * is: /^[a-z]+$/i // same as the previous example using real RegExp + */ + is?: string | Array | RegExp | { msg: string, args : string | Array | RegExp }; + + /** + * not: ["[a-z]",'i'] // will not allow letters + */ + not?: string | Array | RegExp | { msg: string, args : string | Array | RegExp }; + + /** + * checks for email format (foo@bar.com) + */ + isEmail?: boolean | { msg: string }; + + /** + * checks for url format (http://foo.com) + */ + isUrl?: boolean | { msg: string }; + + /** + * checks for IPv4 (129.89.23.1) or IPv6 format + */ + isIP?: boolean | { msg: string }; + + /** + * checks for IPv4 (129.89.23.1) + */ + isIPv4?: boolean | { msg: string }; + + /** + * checks for IPv6 format + */ + isIPv6?: boolean | { msg: string }; + + /** + * will only allow letters + */ + isAlpha?: boolean | { msg: string }; + + /** + * will only allow alphanumeric characters, so "_abc" will fail + */ + isAlphanumeric?: boolean | { msg: string }; + + /** + * will only allow numbers + */ + isNumeric?: boolean | { msg: string }; + + /** + * checks for valid integers + */ + isInt?: boolean | { msg: string }; + + /** + * checks for valid floating point numbers + */ + isFloat?: boolean | { msg: string }; + + /** + * checks for any numbers + */ + isDecimal?: boolean | { msg: string }; + + /** + * checks for lowercase + */ + isLowercase?: boolean | { msg: string }; + + /** + * checks for uppercase + */ + isUppercase?: boolean | { msg: string }; + + /** + * won't allow null + */ + notNull?: boolean | { msg: string }; + + /** + * only allows null + */ + isNull?: boolean | { msg: string }; + + /** + * don't allow empty strings + */ + notEmpty?: boolean | { msg: string }; + + /** + * only allow a specific value + */ + equals? : string | { msg: string }; + + /** + * force specific substrings + */ + contains? : string | { msg: string }; + + /** + * check the value is not one of these + */ + notIn? : Array> | { msg: string, args: Array> }; + + /** + * check the value is one of these + */ + isIn? : Array> | { msg: string, args: Array> }; + + /** + * don't allow specific substrings + */ + notContains? : Array | string | { msg: string, args: Array | string }; + + /** + * only allow values with length between 2 and 10 + */ + len?: [number, number] | { msg: string, args: [number, number] }; + + /** + * only allow uuids + */ + isUUID?: number | { msg: string, args: number }; + + /** + * only allow date strings + */ + isDate?: boolean | { msg: string, args: boolean }; + + /** + * only allow date strings after a specific date + */ + isAfter?: string | { msg: string, args: string }; + + /** + * only allow date strings before a specific date + */ + isBefore?: string | { msg: string, args: string }; + + /** + * only allow values + */ + max?: number | { msg: string, args: number }; + + /** + * only allow values >= 23 + */ + min?: number | { msg: string, args: number }; + + /** + * only allow arrays + */ + isArray?: boolean | { msg: string, args: boolean }; + + /** + * check for valid credit card numbers + */ + isCreditCard?: boolean | { msg: string, args: boolean }; + + /** + * custom validations are also possible + * + * Implementation notes : + * + * We can't enforce any other method to be a function, so : + * + * ```typescript + * [name: string] : ( value : any ) => boolean; + * ``` + * + * doesn't work in combination with the properties above + * + * @see https://github.com/Microsoft/TypeScript/issues/1889 + */ + [name: string] : any; + + } + + /** + * Interface for indexes property in DefineOptions + * + * @see DefineOptions + */ + interface DefineIndexesOptions { + + /** + * The name of the index. Defaults to model name + _ + fields concatenated + */ + name? : string, + + /** + * Index type. Only used by mysql. One of `UNIQUE`, `FULLTEXT` and `SPATIAL` + */ + index? : string, + + /** + * The method to create the index by (`USING` statement in SQL). BTREE and HASH are supported by mysql and + * postgres, and postgres additionally supports GIST and GIN. + */ + method? : string, + + /** + * Should the index by unique? Can also be triggered by setting type to `UNIQUE` + * + * Defaults to false + */ + unique? : boolean, + + /** + * PostgreSQL will build the index without taking any write locks. Postgres only + * + * Defaults to false + */ + concurrently? : boolean, + + /** + * An array of the fields to index. Each field can either be a string containing the name of the field, + * a sequelize object (e.g `sequelize.fn`), or an object with the following attributes: `attribute` + * (field name), `length` (create a prefix index of length chars), `order` (the direction the column + * should be sorted in), `collate` (the collation (sort order) for the column) + */ + fields? : Array + + } + + /** + * Interface for name property in DefineOptions + * + * @see DefineOptions + */ + interface DefineNameOptions { + + /** + * Singular model name + */ + singular? : string, + + /** + * Plural model name + */ + plural? : string, + + } + + /** + * Interface for getterMethods in DefineOptions + * + * @see DefineOptions + */ + interface DefineGetterMethodsOptions { + [name: string] : () => any; + } + + /** + * Interface for setterMethods in DefineOptions + * + * @see DefineOptions + */ + interface DefineSetterMethodsOptions { + [name: string] : ( val : any ) => void; + } + + /** + * Interface for Define Scope Options + * + * @see DefineOptions + */ + interface DefineScopeOptions { + + /** + * Name of the scope and it's query + */ + [scopeName: string] : FindOptions | Function; + + } + + /** + * Options for model definition + * + * @see Sequelize.define + */ + interface DefineOptions { + /** * Define the default search scope to use for this model. Scopes have the same form as the options passed to * find / findAll. @@ -1582,10 +3617,10 @@ declare module "sequelize" defaultScope?: FindOptions; /** - * More scopes, defined in the same way as defaultScope above. See Model.scope for more information about how - * scopes are defined, and what you can do with them + * More scopes, defined in the same way as defaultScope above. See `Model.scope` for more information about + * how scopes are defined, and what you can do with them */ - scopes?: any; + scopes?: DefineScopeOptions; /** * Don't persits null values. This means that all columns with null values will not be saved. @@ -1614,1174 +3649,1233 @@ declare module "sequelize" underscoredAll?: boolean; /** - * If freezeTableName is true, sequelize will not try to alter the DAO name to get the table name. Otherwise, the - * dao name will be pluralized. Default false. + * If freezeTableName is true, sequelize will not try to alter the DAO name to get the table name. + * Otherwise, the dao name will be pluralized. Default false. */ freezeTableName?: boolean; /** - * Override the name of the createdAt column if a string is provided, or disable it if false. Timestamps must be true. + * An object with two attributes, `singular` and `plural`, which are used when this model is associated to + * others. */ - createdAt?: any; + name?: DefineNameOptions; /** - * Override the name of the updatedAt column if a string is provided, or disable it if false. Timestamps must be true. + * Indexes for the provided database table */ - updatedAt?: any; + indexes? : Array; /** - * Override the name of the deletedAt column if a string is provided, or disable it if false. Timestamps must be true. + * Override the name of the createdAt column if a string is provided, or disable it if false. Timestamps + * must be true. Not affected by underscored setting. */ - deletedAt?: any; + createdAt? : string | boolean; /** - * Defaults to pluralized DAO name, unless freezeTableName is true, in which case it uses DAO name verbatim. + * Override the name of the deletedAt column if a string is provided, or disable it if false. Timestamps + * must be true. Not affected by underscored setting. */ - tableName?: string; + deletedAt? : string | boolean; /** - * Provide getter functions that work like those defined per column. If you provide a getter method with the same - * name as a column, it will be used to access the value of that column. If you provide a name that does not match - * a column, this function will act as a virtual getter, that can fetch multiple other values. + * Override the name of the updatedAt column if a string is provided, or disable it if false. Timestamps + * must be true. Not affected by underscored setting. */ - getterMethods?: any; + updatedAt? : string | boolean; /** - * Provide setter functions that work like those defined per column. If you provide a setter method with the same - * name as a column, it will be used to update the value of that column. If you provide a name that does not match - * a column, this function will act as a virtual setter, that can act on and set other values, but will not be - * persisted + * Defaults to pluralized model name, unless freezeTableName is true, in which case it uses model name + * verbatim */ - setterMethods?: any; + tableName? : string; /** - * Provide functions that are added to each instance (DAO). + * Provide getter functions that work like those defined per column. If you provide a getter method with + * the + * same name as a column, it will be used to access the value of that column. If you provide a name that + * does not match a column, this function will act as a virtual getter, that can fetch multiple other + * values */ - instanceMethods?: any; + getterMethods? : DefineGetterMethodsOptions; /** - * Provide functions that are added to the model (Model). + * Provide setter functions that work like those defined per column. If you provide a setter method with + * the + * same name as a column, it will be used to update the value of that column. If you provide a name that + * does not match a column, this function will act as a virtual setter, that can act on and set other + * values, but will not be persisted */ - classMethods?: any; + setterMethods? : DefineSetterMethodsOptions; /** - * Default 'public'. + * Provide functions that are added to each instance (DAO). If you override methods provided by sequelize, + * you can access the original method using `this.constructor.super_.prototype`, e.g. + * `this.constructor.super_.prototype.toJSON.apply(this, arguments)` */ - schema?: string; - schemaDelimiter?: string; - engine?: string; - charset?: string; - comment?: string; - collate?: string; - whereCollection?: any; - language?: string; + instanceMethods? : Object; /** - * An object of hook function that are called before and after certain lifecycle events. The possible hooks are?: - * beforeValidate, afterValidate, beforeBulkCreate, beforeBulkDestroy, beforeBulkUpdate, beforeCreate, - * beforeDestroy, beforeUpdate, afterCreate, afterDestroy, afterUpdate, afterBulkCreate, afterBulkDestory and - * afterBulkUpdate. See Hooks for more information about hook functions and their signatures. Each property can - * either be a function, or an array of functions. + * Provide functions that are added to the model (Model). If you override methods provided by sequelize, + * you can access the original method using `this.constructor.prototype`, e.g. + * `this.constructor.prototype.find.apply(this, arguments)` */ - hooks?: Hooks; + classMethods? : Object; + + schema? : string; /** - * An object of model wide validations. Validations have access to all model values via this. If the validator - * function takes an argument, it is assumed to be async, and is called with a callback that accepts an optional - * error. + * You can also change the database engine, e.g. to MyISAM. InnoDB is the default. */ - validate?: any; + engine? : string; + + charset? : string; /** - * + * Finaly you can specify a comment for the table in MySQL and PG */ - indexes?: Array; - } + comment? : string; - interface DefineIndexOptions { - /** - * The name of the index. Defaults to model name + _ + fields concatenated. - */ - name?: string; - - /** - * Index type. Only used by mysql. One of UNIQUE, FULLTEXT and SPATIAL. - */ - type: string; - - /** - * The method to create the index by (USING statement in SQL). BTREE and HASH are supported by mysql and postgres, - * and postgres additionally supports GIST and GIN. - */ - method: string; - - /** - * Should the index by unique? Can also be triggered by setting type to UNIQUE. Default false (unless type = "UNIQUE", - * then true). - */ - unique?: boolean; - - /** - * PostgreSQL will build the index without taking any write locks. Postgres only. Default false. - */ - concurrently?: boolean; + collate? : string; /** - * An array of the fields to index. Each field can either be a string containing the name of the field, or an object - * with the following attributes: attribute (field name), length (create a prefix index of length chars), order (the - * direction the column should be sorted in), collate (the collation (sort order) for the column) + * Set the initial AUTO_INCREMENT value for the table in MySQL. */ - fields: Array; - } + initialAutoIncrement? : string; - interface QueryOptions { /** - * If true, sequelize will not try to format the results of the query, or build an instance of a model from the - * result. + * An object of hook function that are called before and after certain lifecycle events. + * The possible hooks are: beforeValidate, afterValidate, beforeBulkCreate, beforeBulkDestroy, + * beforeBulkUpdate, beforeCreate, beforeDestroy, beforeUpdate, afterCreate, afterDestroy, afterUpdate, + * afterBulkCreate, afterBulkDestory and afterBulkUpdate. See Hooks for more information about hook + * functions and their signatures. Each property can either be a function, or an array of functions. */ - raw?: boolean; + hooks? : HooksDefineOptions; /** - * The transaction that the query should be executed under. + * An object of model wide validations. Validations have access to all model values via `this`. If the + * validator function takes an argument, it is asumed to be async, and is called with a callback that + * accepts an optional error. */ - transaction?: Transaction; + validate? : DefineValidateOptions; - /** - * The type of query you are executing. The query type affects how results are formatted before they are passed - * back. If no type is provided sequelize will try to guess the right type based on the sql, and fall back to - * SELECT. The type is a string, but Sequelize.QueryTypes is provided is convenience shortcuts. Current options - * are SELECT, BULKUPDATE and BULKDELETE. - * - * Default is SELECT. - */ - type?: string; - - /** - * Lock the selected rows in either share or update mode. Possible options are transaction.LOCK.UPDATE and - * transaction.LOCK.SHARE. See transaction.LOCK for an example. - */ - lock?: string; - - /** - * For aggregate function calls, the type of the result. If field is a field in this Model, the default will be the - * type of that field, otherwise defaults to float. - */ - dataType?: any; - - /** - * A function that logs sql queries, or false for no logging. - */ - logging?: any; - - /** - * If plain is true, then sequelize will only return the first record of the result set. In case of false it will - * all records. - */ - plain?: boolean; } + /** + * Sync Options + * + * @see Sequelize.sync + */ interface SyncOptions { + /** - * If force is true, each DAO will do DROP TABLE IF EXISTS ..., before it tries to create its own table. - * Default false. + * If force is true, each DAO will do DROP TABLE IF EXISTS ..., before it tries to create its own table */ force?: boolean; /** - * A function that logs sql queries, or false for no logging. + * Match a regex against the database name before syncing, a safety check for cases where force: true is + * used in tests but not live code */ - logging?: any; + match?: RegExp; /** - * The schema that the tables should be created in. This can be overriden for each table in sequelize.define. - * Default 'public'. + * A function that logs sql queries, or false for no logging + */ + logging?: Function | boolean; + + /** + * The schema that the tables should be created in. This can be overriden for each table in sequelize.define */ schema?: string; + } + interface SetOptions { } + + /** + * Connection Pool options + * + * @see Options + */ + interface PoolOptions { + + /** + * Maximum connections of the pool + */ + maxConnections?: number; + + /** + * Minimum connections of the pool + */ + minConnections?: number; + + /** + * The maximum time, in milliseconds, that a connection can be idle before being released. + */ + maxIdleTime?: number; + + /** + * A function that validates a connection. Called with client. The default function checks that client is an + * object, and that its state is not disconnected. + */ + validateConnection?: ( client? : any ) => boolean; + + } + + /** + * Interface for replication Options in the sequelize constructor + * + * @see Options + */ interface ReplicationOptions { - read?: Array; - write?: Server; + + read?: { + host?: string, + port?: string | number, + username?: string, + password?: string, + database?: string + } + + write?: { + host?: string, + port?: string | number, + username?: string, + password?: string, + database?: string + } + } - interface Server { - host?: string; - port?: number; - database?: string; - username?: string; - password?: string; - } + /** + * Options for the constructor of Sequelize main class + */ + interface Options { - interface DropOptions { /** - * Also drop all objects depending on this table, such as views. Only works in postgres. + * The dialect of the database you are connecting to. One of mysql, postgres, sqlite, mariadb and mssql. * - * Default false. + * Defaults to 'mysql' */ - cascade?: boolean; - } - - interface SchemaOptions { - /** - * The character(s) that separates the schema name from the table name. Default '.'. - */ - schemaDelimiter?: string; - } - - interface FindOptions { - /** - * A hash of attributes to describe your search. - */ - where?: any; + dialect?: string; /** - * A list of the attributes that you want to select. To rename an attribute, you can pass an array, with two - * elements - the first is the name of the attribute in the DB (or some kind of expression such as - * Sequelize.literal, Sequelize.fn and so on), and the second is the name you want the attribute to have in the - * returned instance + * If specified, load the dialect library from this path. For example, if you want to use pg.js instead of + * pg when connecting to a pg database, you should specify 'pg.js' here */ - attributes?: Array; + dialectModulePath?: string; /** - * A list of associations to eagerly load. Supported is either { include?: [ Model1, Model2, ...] } or { include?: - * [ { model?: Model1, as?: 'Alias' } ] }. If your association are set up with an as (eg. X.hasMany(Y, { as?: 'Z }, - * you need to specify Z in the as attribute when eager loading Y). When using the object form, you can also - * specify attributes to specify what columns to load, where to limit the relations, and include to load further - * nested relations + * An object of additional options, which are passed directly to the connection library */ - include?: any; - - /** - * Specifies an ordering. If a string is provided, it will be esacped. Using an array, you can provide several - * columns / functions to order by. Each element can be further wrapped in a two-element array. The first element - * is the column / function to order by, the second is the direction. For example?: order?: [['name', 'DESC']]. In - * this way the column will be escaped, but the direction will not. - */ - order?: any; - - limit?: number; - - offset?: number; - } - - interface BuildOptions { - /** - * If set to true, values will ignore field and virtual setters. Default false. - */ - raw?: boolean; - - /** - * Default true. - */ - isNewRecord?: boolean; - - /** - * Default true. - */ - isDirty?: boolean; - - /** - * an array of include options - Used to build prefetched/included model instances. See set. - */ - include?: Array; - } - - interface CopyOptions extends BuildOptions { - /** - * If set, only columns matching those in fields will be saved. - */ - fields?: Array; + dialectOptions? : Object; /** + * Only used by sqlite. * + * Defaults to ':memory:' */ - transaction?: Transaction; - } + storage? : string; - interface FindOrCreateOptions extends FindOptions, QueryOptions { + /** + * The host of the relational database. + * + * Defaults to 'localhost' + */ + host? : string; + + /** + * The port of the relational database. + */ + port? : number; + + /** + * The protocol of the relational database. + * + * Defaults to 'tcp' + */ + protocol? : string; + + /** + * Default options for model definitions. See sequelize.define for options + */ + define? : DefineOptions; + + /** + * Default options for sequelize.query + */ + query? : QueryOptions; + + /** + * Default options for sequelize.set + */ + set? : SetOptions; + + /** + * Default options for sequelize.sync + */ + sync? : SyncOptions; + + /** + * The timezone used when converting a date from the database into a JavaScript date. The timezone is also + * used to SET TIMEZONE when connecting to the server, to ensure that the result of NOW, CURRENT_TIMESTAMP + * and other time related functions have in the right timezone. For best cross platform performance use the + * format + * +/-HH:MM. Will also accept string versions of timezones used by moment.js (e.g. 'America/Los_Angeles'); + * this is useful to capture daylight savings time changes. + * + * Defaults to '+00:00' + */ + timezone? : string; + + /** + * A function that gets executed everytime Sequelize would log something. + * + * Defaults to console.log + */ + logging? : boolean | Function; + + /** + * A flag that defines if null values should be passed to SQL queries or not. + * + * Defaults to false + */ + omitNull? : boolean; + + /** + * A flag that defines if native library shall be used or not. Currently only has an effect for postgres + * + * Defaults to false + */ + native? : boolean; + + /** + * Use read / write replication. To enable replication, pass an object, with two properties, read and write. + * Write should be an object (a single server for handling writes), and read an array of object (several + * servers to handle reads). Each read/write server can have the following properties: `host`, `port`, + * `username`, `password`, `database` + * + * Defaults to false + */ + replication? : ReplicationOptions; + + /** + * Connection pool options + */ + pool? : PoolOptions; + + /** + * Set to `false` to make table names and attributes case-insensitive on Postgres and skip double quoting of + * them. + * + * Defaults to true + */ + quoteIdentifiers? : boolean; + + /** + * Set the default transaction isolation level. See `Sequelize.Transaction.ISOLATION_LEVELS` for possible + * options. + * + * Defaults to 'REPEATABLE_READ' + */ + isolationLevel? : string; } - interface BulkCreateOptions { - /** - * Fields to insert (defaults to all fields). - */ - fields?: Array; + /** + * Sequelize methods that are available both for the static and the instance class of Sequelize + */ + interface SequelizeStaticAndInstance extends Errors { /** - * Should each row be subject to validation before it is inserted. The whole insert will fail if one row fails - * validation. Default false. + * A reference to sequelize utilities. Most users will not need to use these utils directly. However, you + * might want to use `Sequelize.Utils._`, which is a reference to the lodash library, if you don't already + * have it imported in your project. */ - validate?: boolean; + Utils: Utils; /** - * Run before / after create hooks for each individual Instance? BulkCreate hooks will still be run. Default false; + * A modified version of bluebird promises, that allows listening for sql events */ - hooks?: boolean; + Promise: typeof Promise; /** - * Ignore duplicate values for primary keys? (not supported by postgres). Default false. + * Available query types for use with `sequelize.query` */ - ignoreDuplicates?: boolean; + QueryTypes: QueryTypes; + + /** + * Exposes the validator.js object, so you can extend it with custom validation functions. + * The validator is exposed both on the instance, and on the constructor. + */ + Validator: Validator; + + /** + * A Model represents a table in the database. Sometimes you might also see it referred to as model, or + * simply as factory. This class should not be instantiated directly, it is created using sequelize.define, + * and already created models can be loaded using sequelize.import + */ + Model: Model; + + /** + * A reference to the sequelize transaction class. Use this to access isolationLevels when creating a + * transaction + */ + Transaction : TransactionStatic; + + /** + * A reference to the deferrable collection. Use this to access the different deferrable options. + */ + Deferrable : Deferrable; + + /** + * A reference to the sequelize instance class. + */ + Instance : Instance; + + /** + * Creates a object representing a database function. This can be used in search queries, both in where and + * order parts, and as default values in column definitions. If you want to refer to columns in your + * function, you should use `sequelize.col`, so that the columns are properly interpreted as columns and + * not a strings. + * + * Convert a user's username to upper case + * ```js + * instance.updateAttributes({ + * username: self.sequelize.fn('upper', self.sequelize.col('username')) + * }) + * ``` + * @param fn The function you want to call + * @param args All further arguments will be passed as arguments to the function + */ + fn( fn : string, ...args : any[] ) : fn; + + /** + * Creates a object representing a column in the DB. This is often useful in conjunction with + * `sequelize.fn`, since raw string arguments to fn will be escaped. + * + * @param col The name of the column + */ + col( col : string ) : col; + + /** + * Creates a object representing a call to the cast function. + * + * @param val The value to cast + * @param type The type to cast it to + */ + cast( val : any, type : string ) : cast; + + /** + * Creates a object representing a literal, i.e. something that will not be escaped. + * + * @param val + */ + literal( val : any ) : literal; + asIs( val : any ) : literal; + + /** + * An AND query + * + * @param args Each argument will be joined by AND + */ + and( ...args : Array ) : and; + + /** + * An OR query + * + * @param args Each argument will be joined by OR + */ + or( ...args : Array ) : or; + + /** + * Creates an object representing nested where conditions for postgres's json data-type. + * + * @param conditionsOrPath A hash containing strings/numbers or other nested hash, a string using dot + * notation or a string using postgres json syntax. + * @param value An optional value to compare against. Produces a string of the form " = + * ''". + */ + json( conditionsOrPath : string | Object, value? : string | number | boolean ) : json; + + /** + * A way of specifying attr = condition. + * + * The attr can either be an object taken from `Model.rawAttributes` (for example `Model.rawAttributes.id` + * or + * `Model.rawAttributes.name`). The attribute should be defined in your model definition. The attribute can + * also be an object from one of the sequelize utility functions (`sequelize.fn`, `sequelize.col` etc.) + * + * For string attributes, use the regular `{ where: { attr: something }}` syntax. If you don't want your + * string to be escaped, use `sequelize.literal`. + * + * @param attr The attribute, which can be either an attribute object from `Model.rawAttributes` or a + * sequelize object, for example an instance of `sequelize.fn`. For simple string attributes, use the + * POJO syntax + * @param comparator Comparator + * @param logic The condition. Can be both a simply type, or a further condition (`.or`, `.and`, `.literal` + * etc.) + */ + where( attr : Object, comparator : string, logic : string | Object ) : where; + where( attr : Object, logic : string | Object ) : where; + condition( attr : Object, logic : string | Object ) : where; + } - interface DestroyOptions { - /** - * If set to true, destroy will find all records within the where parameter and will execute before-/ after - * bulkDestroy hooks on each row. - */ - hooks?: boolean; + /** + * Sequelize methods available only for the static class ( basically this is the constructor and some extends ) + */ + interface SequelizeStatic extends SequelizeStaticAndInstance, DataTypes { /** - * How many rows to delete + * Instantiate sequelize with name of database, username and password + * + * #### Example usage + * + * ```javascript + * // without password and options + * var sequelize = new Sequelize('database', 'username') + * + * // without options + * var sequelize = new Sequelize('database', 'username', 'password') + * + * // without password / with blank password + * var sequelize = new Sequelize('database', 'username', null, {}) + * + * // with password and options + * var sequelize = new Sequelize('my_database', 'john', 'doe', {}) + * + * // with uri (see below) + * var sequelize = new Sequelize('mysql://localhost:3306/database', {}) + * ``` + * + * @param database The name of the database + * @param username The username which is used to authenticate against the + * database. + * @param password The password which is used to authenticate against the + * database. + * @param options An object with options. */ - limit?: number; + new ( database : string, username : string, password : string, options? : Options ) : Sequelize; + new ( database : string, username : string, options? : Options ) : Sequelize; /** - * If set to true, dialects that support it will use TRUNCATE instead of DELETE FROM. If a table is truncated the - * where and limit options are ignored. + * Instantiate sequelize with an URI + * @name Sequelize + * @constructor + * + * @param uri A full database URI + * @param options See above for possible options */ - truncate?: boolean; + new ( uri : string, options? : Options ) : Sequelize; + } - interface DestroyInstanceOptions { + interface QueryOptionsTransactionRequired { } + + /** + * This is the main class, the entry point to sequelize. To use it, you just need to + * import sequelize: + * + * ```js + * var Sequelize = require('sequelize'); + * ``` + * + * In addition to sequelize, the connection library for the dialect you want to use + * should also be installed in your project. You don't need to import it however, as + * sequelize will take care of that. + */ + interface Sequelize extends SequelizeStaticAndInstance, Hooks { + /** - * If set to true, paranoid models will actually be deleted. + * A reference to Sequelize constructor from sequelize. Useful for accessing DataTypes, Errors etc. */ - force: boolean; + Sequelize: SequelizeStatic; + + /** + * Returns the specified dialect. + */ + getDialect() : string; + + /** + * Returns an instance of QueryInterface. + */ + getQueryInterface(): QueryInterface; + + /** + * Define a new model, representing a table in the DB. + * + * The table columns are define by the hash that is given as the second argument. Each attribute of the + * hash + * represents a column. A short table definition might look like this: + * + * ```js + * sequelize.define('modelName', { + * columnA: { + * type: Sequelize.BOOLEAN, + * validate: { + * is: ["[a-z]",'i'], // will only allow letters + * max: 23, // only allow values <= 23 + * isIn: { + * args: [['en', 'zh']], + * msg: "Must be English or Chinese" + * } + * }, + * field: 'column_a' + * // Other attributes here + * }, + * columnB: Sequelize.STRING, + * columnC: 'MY VERY OWN COLUMN TYPE' + * }) + * + * sequelize.models.modelName // The model will now be available in models under the name given to define + * ``` + * + * As shown above, column definitions can be either strings, a reference to one of the datatypes that are + * predefined on the Sequelize constructor, or an object that allows you to specify both the type of the + * column, and other attributes such as default values, foreign key constraints and custom setters and + * getters. + * + * For a list of possible data types, see + * http://docs.sequelizejs.com/en/latest/docs/models-definition/#data-types + * + * For more about getters and setters, see + * http://docs.sequelizejs.com/en/latest/docs/models-definition/#getters-setters + * + * For more about instance and class methods, see + * http://docs.sequelizejs.com/en/latest/docs/models-definition/#expansion-of-models + * + * For more about validation, see + * http://docs.sequelizejs.com/en/latest/docs/models-definition/#validations + * + * @param modelName The name of the model. The model will be stored in `sequelize.models` under this name + * @param attributes An object, where each attribute is a column of the table. Each column can be either a + * DataType, a string or a type-description object, with the properties described below: + * @param options These options are merged with the default define options provided to the Sequelize + * constructor + */ + define( modelName : string, attributes : DefineAttributes, + options? : DefineOptions ) : Model; + + /** + * Fetch a Model which is already defined + * + * @param modelName The name of a model defined with Sequelize.define + */ + model( modelName : string ) : Model; + + /** + * Checks whether a model with the given name is defined + * + * @param modelName The name of a model defined with Sequelize.define + */ + isDefined( modelName : string ) : boolean; + + /** + * Imports a model defined in another file + * + * Imported models are cached, so multiple calls to import with the same path will not load the file + * multiple times + * + * See https://github.com/sequelize/sequelize/blob/master/examples/using-multiple-model-files/Task.js for a + * short example of how to define your models in separate files so that they can be imported by + * sequelize.import + * + * @param path The path to the file that holds the model you want to import. If the part is relative, it + * will be resolved relatively to the calling file + */ + import( path : string ) : Model; + + /** + * Execute a query on the DB, with the posibility to bypass all the sequelize goodness. + * + * By default, the function will return two arguments: an array of results, and a metadata object, + * containing number of affected rows etc. Use `.spread` to access the results. + * + * If you are running a type of query where you don't need the metadata, for example a `SELECT` query, you + * can pass in a query type to make sequelize format the results: + * + * ```js + * sequelize.query('SELECT...').spread(function (results, metadata) { + * // Raw query - use spread + * }); + * + * sequelize.query('SELECT...', { type: sequelize.QueryTypes.SELECT }).then(function (results) { + * // SELECT query - use then + * }) + * ``` + * + * @param sql + * @param options Query options + */ + query( sql : string | { query: string, values: Array }, options? : QueryOptions ) : Promise; + + /** + * Execute a query which would set an environment or user variable. The variables are set per connection, + * so this function needs a transaction. + * + * Only works for MySQL. + * + * @param variables Object with multiple variables. + * @param options Query options. + */ + set( variables : Object, options : QueryOptionsTransactionRequired ) : Promise; + + /** + * Escape value. + * + * @param value Value that needs to be escaped + */ + escape( value : string ) : string; + + /** + * Create a new database schema. + * + * Note,that this is a schema in the + * [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html), + * not a database table. In mysql and sqlite, this command will do nothing. + * + * @param schema Name of the schema + * @param options Options supplied + * @param options.logging A function that logs sql queries, or false for no logging + */ + createSchema( schema : string, options : { logging? : boolean | Function } ) : Promise; + + /** + * Show all defined schemas + * + * Note,that this is a schema in the + * [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html), + * not a database table. In mysql and sqlite, this will show all tables. + * + * @param options Options supplied + * @param options.logging A function that logs sql queries, or false for no logging + */ + showAllSchemas( options : { logging? : boolean | Function } ) : Promise; + + /** + * Drop a single schema + * + * Note,that this is a schema in the + * [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html), + * not a database table. In mysql and sqlite, this drop a table matching the schema name + * + * @param schema Name of the schema + * @param options Options supplied + * @param options.logging A function that logs sql queries, or false for no logging + */ + dropSchema( schema : string, options : { logging? : boolean | Function } ) : Promise; + + /** + * Drop all schemas + * + * Note,that this is a schema in the + * [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html), + * not a database table. In mysql and sqlite, this is the equivalent of drop all tables. + * + * @param options Options supplied + * @param options.logging A function that logs sql queries, or false for no logging + */ + dropAllSchemas( options : { logging? : boolean | Function } ) : Promise; + + /** + * Sync all defined models to the DB. + * + * @param options Sync Options + */ + sync( options? : SyncOptions ) : Promise; + + /** + * Truncate all tables defined through the sequelize models. This is done + * by calling Model.truncate() on each model. + * + * @param {object} [options] The options passed to Model.destroy in addition to truncate + * @param {Boolean|function} [options.transaction] + * @param {Boolean|function} [options.logging] A function that logs sql queries, or false for no logging + */ + truncate( options? : DestroyOptions ) : Promise; + + /** + * Drop all tables defined through this sequelize instance. This is done by calling Model.drop on each model + * @see {Model#drop} for options + * + * @param options The options passed to each call to Model.drop + */ + drop( options? : DropOptions ) : Promise; + + /** + * Test the connection by trying to authenticate + * + * @param options Query Options for authentication + */ + authenticate( options? : QueryOptions ) : Promise; + validate( options? : QueryOptions ) : Promise; + + /** + * Start a transaction. When using transactions, you should pass the transaction in the options argument + * in order for the query to happen under that transaction + * + * ```js + * sequelize.transaction().then(function (t) { + * return User.find(..., { transaction: t}).then(function (user) { + * return user.updateAttributes(..., { transaction: t}); + * }) + * .then(t.commit.bind(t)) + * .catch(t.rollback.bind(t)); + * }) + * ``` + * + * A syntax for automatically committing or rolling back based on the promise chain resolution is also + * supported: + * + * ```js + * sequelize.transaction(function (t) { // Note that we use a callback rather than a promise.then() + * return User.find(..., { transaction: t}).then(function (user) { + * return user.updateAttributes(..., { transaction: t}); + * }); + * }).then(function () { + * // Commited + * }).catch(function (err) { + * // Rolled back + * console.error(err); + * }); + * ``` + * + * If you have [CLS](https://github.com/othiym23/node-continuation-local-storage) enabled, the transaction + * will automatically be passed to any query that runs witin the callback. To enable CLS, add it do your + * project, create a namespace and set it on the sequelize constructor: + * + * ```js + * var cls = require('continuation-local-storage'), + * ns = cls.createNamespace('....'); + * var Sequelize = require('sequelize'); + * Sequelize.cls = ns; + * ``` + * Note, that CLS is enabled for all sequelize instances, and all instances will share the same namespace + * + * @param options Transaction Options + * @param autoCallback Callback for the transaction + */ + transaction( options : TransactionOptions, + autoCallback : ( t : Transaction ) => Promise ) : Promise; + transaction( autoCallback : ( t : Transaction ) => Promise ) : Promise; + transaction() : Promise; + + /** + * Close all connections used by this sequelize instance, and free all references so the instance can be + * garbage collected. + * + * Normally this is done on process exit, so you only need to call this method if you are creating multiple + * instances, and want to garbage collect some of them. + */ + close() : void; + + /** + * Returns the database version + */ + databaseVersion() : Promise; + } - interface InsertOptions { - limit?: number; - returning?: string; - allowNull?: string; + // + // Validator + // ~~~~~~~~~~~ + + /** + * Validator Interface + */ + interface Validator extends IValidatorStatic { + + notEmpty( str : string ) : boolean; + len( str : string, min : number, max : number ) : boolean; + isUrl( str : string ) : boolean; + isIPv6( str : string ) : boolean + isIPv4( str : string ) : boolean + notIn( str : string, values : Array ) : boolean; + regex( str : string, pattern : string, modifiers : string ) : boolean; + notRegex( str : string, pattern : string, modifiers : string ) : boolean; + isDecimal( str : string ) : boolean; + min( str : string, val : number ) : boolean; + max( str : string, val : number ) : boolean; + not( str : string, pattern : string, modifiers : string ) : boolean; + contains( str : string, element : Array ) : boolean; + notContains( str : string, element : Array ) : boolean; + is( str : string, pattern : string, modifiers : string ) : boolean; + } - interface UpdateOptions { - /** - * Should each row be subject to validation before it is inserted. The whole insert will fail if one row fails - * validation. Default true. - */ - validate?: boolean; + // + // Transaction + // ~~~~~~~~~~~~~ + // + // https://github.com/sequelize/sequelize/blob/v3.4.1/lib/transaction.js + // + + /** + * The transaction object is used to identify a running transaction. It is created by calling + * `Sequelize.transaction()`. + * + * To run a query under a transaction, you should pass the transaction in the options object. + */ + interface Transaction { /** - * Run before / after bulkUpdate hooks? Default false. + * Possible options for row locking. Used in conjuction with `find` calls: + * + * @see TransactionStatic */ - hooks?: boolean; + LOCK : TransactionLock; /** - * How many rows to update (only for mysql and mariadb). + * Commit the transaction */ - limit?: number; + commit() : Transaction; + + /** + * Rollback (abort) the transaction + */ + rollback() : Transaction; + } - interface SetOptions { - /** - * If set to true, field and virtual setters will be ignored. Default false. - */ - raw?: boolean; + /** + * The transaction static object + * + * @see Transaction + */ + interface TransactionStatic { /** - * Clear all previously set data values. Default false. + * Isolations levels can be set per-transaction by passing `options.isolationLevel` to + * `sequelize.transaction`. Default to `REPEATABLE_READ` but you can override the default isolation level + * by passing + * `options.isolationLevel` in `new Sequelize`. + * + * The possible isolations levels to use when starting a transaction: + * + * ```js + * { + * READ_UNCOMMITTED: "READ UNCOMMITTED", + * READ_COMMITTED: "READ COMMITTED", + * REPEATABLE_READ: "REPEATABLE READ", + * SERIALIZABLE: "SERIALIZABLE" + * } + * ``` + * + * Pass in the desired level as the first argument: + * + * ```js + * return sequelize.transaction({ + * isolationLevel: Sequelize.Transaction.SERIALIZABLE + * }, function (t) { + * + * // your transactions + * + * }).then(function(result) { + * // transaction has been committed. Do something after the commit if required. + * }).catch(function(err) { + * // do something with the err. + * }); + * ``` + * + * @see ISOLATION_LEVELS */ - reset?: boolean; + ISOLATION_LEVELS : TransactionIsolationLevels; + + /** + * Possible options for row locking. Used in conjuction with `find` calls: + * + * ```js + * t1 // is a transaction + * t1.LOCK.UPDATE, + * t1.LOCK.SHARE, + * t1.LOCK.KEY_SHARE, // Postgres 9.3+ only + * t1.LOCK.NO_KEY_UPDATE // Postgres 9.3+ only + * ``` + * + * Usage: + * ```js + * t1 // is a transaction + * Model.findAll({ + * where: ..., + * transaction: t1, + * lock: t1.LOCK... + * }); + * ``` + * + * Postgres also supports specific locks while eager loading by using OF: + * ```js + * UserModel.findAll({ + * where: ..., + * include: [TaskModel, ...], + * transaction: t1, + * lock: { + * level: t1.LOCK..., + * of: UserModel + * } + * }); + * ``` + * UserModel will be locked but TaskModel won't! + */ + LOCK : TransactionLock; - include?: any; } - interface SaveOptions { - /** - * An alternative way of setting which fields should be persisted. - */ - fields?: any; - - /** - * If true, the updatedAt timestamp will not be updated. Default false. - */ - silent?: boolean; - - transaction?: Transaction; + /** + * Isolations levels can be set per-transaction by passing `options.isolationLevel` to `sequelize.transaction`. + * Default to `REPEATABLE_READ` but you can override the default isolation level by passing + * `options.isolationLevel` in `new Sequelize`. + */ + interface TransactionIsolationLevels { + READ_UNCOMMITTED: string; // 'READ UNCOMMITTED' + READ_COMMITTED: string; // 'READ COMMITTED' + REPEATABLE_READ: string; // 'REPEATABLE READ' + SERIALIZABLE: string; // 'SERIALIZABLE' } - interface ValidateOptions { - /** - * An array of strings. All properties that are in this array will not be validated. - */ - skip: Array; - } - - interface IncrementOptions { - /** - * The number to increment by. Default 1. - */ - by?: number; - - transaction?: Transaction; - } - - interface IndexOptions { - indicesType?: string; - indexType?: string; - indexName?: string; - parser?: any; - } - - interface ProxyOptions { - /** - * An array of the events to proxy. Defaults to sql, error and success. - */ - events: Array; - } - - interface AssociationOptions { - /** - * Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For - * example if User.hasOne(Profile, {onDelete: 'cascade', hooks:true}), the before-/afterDestroy hooks for profile - * will be called when a user is deleted. Otherwise the profile will be deleted without invoking any hooks. - * Default false. - */ - hooks?: boolean; - - /** - * The name of the table that is used to join source and target in n:m associations. Can also be a sequelize model - * if you want to define the junction table yourself and add extra attributes to it. - */ - through?: any; - - /** - * The alias of this model. If you create multiple associations between the same tables, you should provide an - * alias to be able to distinguish between them. If you provide an alias when creating the assocition, you should - * provide the same alias when eager loading and when getting assocated models. Defaults to the singularized - * version of target.name - */ - as?: string; - - /** - * The foreignKey can be either a string name of the foreign key in the target table, - * or can be an object defining the foreign key and its options. Note foreignKey is not fully - * typed since TypeScript does not support union types--it can be either a string or an - * options object. String name defaults to the name of source + primary key of source. - * - * @see ForeignKeyAttributeOptions. - */ - foreignKey?: any; - - /** - * What should happen when the referenced key is deleted. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or - * NO ACTION. Default SET NULL. - */ - onDelete?: string; - - /** - * What should happen when the referenced key is updated. One of CASCADE, RESTRICT, SET DEFAULT, SET NULL or - * NO ACTION. Default CASCADE. - */ - onUpdate?: string; - - /** - * Should on update and on delete constraints be enabled on the foreign key. - */ - constraints?: boolean; - } - - interface TriggerOptions { - insert?: Array; - update?: Array; - delete?: Array; - truncate?: Array; - } - - interface TriggerParam { - type: string; - direction?: string; - name?: string; - } - - interface SelectOptions { - limit?: number; - offset?: number; - attributes?: Array; - hasIncludeWhere?: boolean; - hasIncludeRequired?: boolean; - hasMultiAssociation?: boolean; - tableAs?: string; - table?: string; - include?: Array; - includeIgnoreAttributes?: boolean; - where?: any; - /** - * String field name or array of strings of field names. - */ - group?: any; - having?: any; - order?: any; - lock?: string; - } - - interface HashToWhereConditionsOption { - include?: boolean; - keysEscaped?: boolean; - } - - interface ModelMangerGetDaoOptions { - attribute: string; - } - - interface ModelManagerForEachDaoOptions { - /** - * Default true. - */ - reverse: boolean; - } - - interface MigratorOptions { - /** - * A flag that defines if the migrator should get instantiated or not.. - */ - force: boolean; - } - - interface FindAndCountResult { - /** - * The matching model instances. - */ - rows?: Array; - - /** - * The total number of rows. This may be more than the rows returned if a limit and/or offset was supplied. - */ - count?: number; - } - - interface Col { - /** - * Column name. - */ - col: string; - } - - interface Cast { - /** - * The value to cast. - */ - val: any; - - /** - * The type to cast it to. - */ - type: string; - } - - interface Literal { - val: any; - } - - interface And { - /** - * Each argument (string or object) will be joined by AND. - */ - args: Array; - } - - interface Or { - /** - * Each argument (string or object) will be joined by OR. - */ - args: Array; - } - - interface Where { - /** - * The attribute. - */ - attribute: string; - - /** - * The condition. Can be both a simply type, or a further condition (.or, .and, .literal etc.). - */ - logic: any; + /** + * Possible options for row locking. Used in conjuction with `find` calls: + */ + interface TransactionLock { + UPDATE: string; // 'UPDATE' + SHARE: string; // 'SHARE' + KEY_SHARE: string; // 'KEY SHARE' + NO_KEY_UPDATE: string; // 'NO KEY UPDATE' } + /** + * Options provided when the transaction is created + * + * @see sequelize.transaction() + */ interface TransactionOptions { - /** - * - */ + autocommit?: boolean; /** - * One of: 'READ UNCOMMITTED', 'READ COMMITTED', 'REPEATABLE READ', 'SERIALIZABLE'. Default 'REPEATABLE READ'. + * See `Sequelize.Transaction.ISOLATION_LEVELS` for possible options */ isolationLevel?: string; + + /** + * A function that gets executed while running the query to log the sql. + */ + logging?: Function; + } - interface QueryChainerRunSeriallyOptions { - /** - * If set to true, all pending emitters will be skipped if a previous emitter failed. Default false. - */ - skipOnError: boolean; + // + // Utils + // ~~~~~~~ + + interface fn { + clone : fnStatic; } - interface CreateTableQueryOptions { - comment?: string; - uniqueKeys?: Array; - charset?: string; + interface fnStatic { + /** + * @param fn The function you want to call + * @param args All further arguments will be passed as arguments to the function + */ + new ( fn : string, ...args : Array ) : fn; } - interface MigratorExecOptions { - before?: (migrator: Migrator) => void; - after?: (migrator: Migrator) => void; - success?: (migrator: Migrator) => void; + interface col { + col: string; } - interface MigrationExecuteOptions { - method: string; + interface colStatic { + /** + * Creates a object representing a column in the DB. This is often useful in conjunction with + * `sequelize.fn`, since raw string arguments to fn will be escaped. + * @see {Sequelize#fn} + * + * @param col The name of the column + */ + new ( col : string ) : col; } - interface MigrationCompareOptions { - /** - * Default false. - */ - withoutEquals: boolean; + interface cast { + val: any; + type: string; } - interface Promise { + interface castStatic { /** - * Listen for events, event emitter style. Mostly for backwards compatibility with EventEmitter. + * Creates a object representing a call to the cast function. * - * @param evt Event - * @param fct Handler + * @param val The value to cast + * @param type The type to cast it to */ - on(evt: string, fct: () => void): void; - - /** - * Emit an event from the emitter. - * - * @param type The type of event. - * @param value All other arguments will be passed to the event listeners. - */ - emit(type: string, ...value: Array): void; - - /** - * Listen for success events. - */ - success(onSuccess: () => void): Promise; - - /** - * Alias for success(handler). Listen for success events. - */ - ok(onSuccess: () => void): Promise; - - /** - * Listen for error events. - * - * @param onError Error handler. - */ - error(onError: (err?: Error) => void): Promise; - - /** - * Alias for error(handler). Listen for error events. - * - * @param onError Error handler. - */ - fail(onError: (err?: Error) => void): Promise; - - /** - * Alias for error(handler). Listen for error events. - * - * @param onError Error handler. - */ - failure(onError: (err?: Error) => void): Promise; - - /** - * Listen for both success and error events.. - */ - done(handler: (err: Error, result?: any) => void): Promise; - - /** - * Alias for done(handler). Listen for both success and error events.. - */ - complete(handler: (err: Error, result?: any) => void): Promise; - - /** - * Attach a function that is called every time the function that created this emitter executes a query. - * - * @param onSQL - */ - sql(onSQL: (sql: string) => void): Promise; - - /** - * Proxy every event of this promise to another one. - * - * @param promise The promise that should receive the events. - * @param options Contains an array of the events to proxy. Defaults to sql, error and success - */ - proxy(promise: Promise, options?: ProxyOptions): Promise; - - - /** - * Attach listeners to the emitter, promise style. - * - * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). - * Note that this function will always only be called with one argument, as per - * the promises/A spec. For functions that emit multiple arguments - * (e.g. findOrCreate) @see spread - * @param onRejected - */ - then(onFulfilled?: (result?: any) => void, onRejected?: (result?: any) => void): Promise; - - /** - * Attach listeners to the emitter, promise style. - * - * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). - * Note that this function will always only be called with one argument, as per - * the promises/A spec. For functions that emit multiple arguments - * (e.g. findOrCreate) @see spread - * @param onRejected - */ - then(onFulfilled?: (result?: any) => Promise, onRejected?: (result?: any) => Promise): Promise; - - /** - * Attach listeners to the emitter, promise style. - * - * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). - * Note that this function will always only be called with one argument, as per - * the promises/A spec. For functions that emit multiple arguments - * (e.g. findOrCreate) @see spread - * @param onRejected - */ - then(onFulfilled?: (result?: any) => PromiseT, onRejected?: (result?: any) => PromiseT): PromiseT; - - /** - * Attach listeners to the emitter, promise style. - * - * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). - * Note that this function will always only be called with one argument, as per - * the promises/A spec. For functions that emit multiple arguments - * (e.g. findOrCreate) @see spread - * @param onRejected - */ - then(onFulfilled?: (result?: any) => PromiseT, onRejected?: (result?: any) => void): PromiseT; - - /** - * Attach listeners to the emitter, promise style. - * - * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). - * Note that this function will always only be called with one argument, as per - * the promises/A spec. For functions that emit multiple arguments - * (e.g. findOrCreate) @see spread - * @param onRejected - */ - then(onFulfilled?: (result?: any) => void, onRejected?: (result?: any) => PromiseT): PromiseT; - - /** - * Attach listeners to the emitter, promise style. - * - * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). - * Note that this function will always only be called with one argument, as per - * the promises/A spec. For functions that emit multiple arguments - * (e.g. findOrCreate) @see spread - * @param onRejected - */ - then(onFulfilled?: (result?: any) => PromiseT, onRejected?: (result?: any) => PromiseT): Promise; - - /** - * Attach listeners to the emitter, promise style. This listener will recieve all arguments emitted by the emitter, - * as opposed to then which will only recieve the first argument. - * - * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). - * @param onRejected - */ - spread(onFulfilled?: (...results: Array) => Promise, onRejected?: (...results: Array) => Promise): Promise; - - /** - * Attach listeners to the emitter, promise style. This listener will recieve all arguments emitted by the emitter, - * as opposed to then which will only recieve the first argument. - * - * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). - * @param onRejected - */ - spread(onFulfilled?: (...results: Array) => void, onRejected?: (...results: Array) => void): Promise; - - /** - * Attach listeners to the emitter, promise style. This listener will recieve all arguments emitted by the emitter, - * as opposed to then which will only recieve the first argument. - * - * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). - * @param onRejected - */ - spread(onFulfilled?: (...results: Array) => Promise, onRejected?: (...results: Array) => void): Promise; - - /** - * Attach listeners to the emitter, promise style. This listener will recieve all arguments emitted by the emitter, - * as opposed to then which will only recieve the first argument. - * - * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). - * @param onRejected - */ - spread(onFulfilled?: (...results: Array) => void, onRejected?: (...results: Array) => Promise): Promise; - - /** - * Attach listeners to the emitter, promise style. This listener will recieve all arguments emitted by the emitter, - * as opposed to then which will only recieve the first argument. - * - * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). - * @param onRejected - */ - spread(onFulfilled?: (...results: Array) => PromiseT, onRejected?: (...results: Array) => PromiseT): PromiseT; - - /** - * Attach listeners to the emitter, promise style. This listener will recieve all arguments emitted by the emitter, - * as opposed to then which will only recieve the first argument. - * - * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). - * @param onRejected - */ - spread(onFulfilled?: (...results: Array) => void, onRejected?: (...results: Array) => PromiseT): PromiseT; - - /** - * Attach listeners to the emitter, promise style. This listener will recieve all arguments emitted by the emitter, - * as opposed to then which will only recieve the first argument. - * - * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). - * @param onRejected - */ - spread(onFulfilled?: (...results: Array) => PromiseT, onRejected?: (...results: Array) => void): PromiseT; - - /** - * Attach listeners to the emitter, promise style. This listener will recieve all arguments emitted by the emitter, - * as opposed to then which will only recieve the first argument. - * - * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). - * @param onRejected - */ - spread(onFulfilled?: (...results: Array) => PromiseT, onRejected?: (...results: Array) => PromiseT): Promise; - - /** - * Shorthand for then(null, onRejected) - */ - catch(onRejected: (result?: any) => Promise): Promise; - - /** - * Shorthand for then(null, onRejected) - */ - catch(onRejected: (result?: any) => PromiseT): PromiseT; - - /** - * Shorthand for then(null, onRejected) - */ - catch(onRejected: (result?: any) => void): Promise; + new ( val : any, type : string ) : cast; } - interface PromiseT extends Promise { + interface literal { + val: any; + } + + interface literalStatic { /** - * Listen for events, event emitter style. Mostly for backwards compatibility with EventEmitter. + * Creates a object representing a literal, i.e. something that will not be escaped. * - * @param evt Event - * @param fct Handler + * @param val */ - on(evt: string, fct: (t: T) => void): void; + new ( val : any ) : literal; + } + interface and { + args: Array; + } + + interface andStatic { /** - * Emit an event from the emitter. + * An AND query * - * @param type The type of event. - * @param value All other arguments will be passed to the event listeners. + * @param args Each argument will be joined by AND */ - emit(type: string, ...value: Array): void; + new ( ...args : Array ) : and; + } - /** - * Listen for success events. - */ - success(onSuccess: (t: T) => void): PromiseT; + interface or { + args: Array; + } + interface orStatic { /** - * Alias for success(handler). Listen for success events. - */ - ok(onSuccess: (t: T) => void): PromiseT; - - /** - * Listen for both success and error events.. - */ - done(handler: (err: Error, result: T) => void): PromiseT; - - /** - * Alias for done(handler). Listen for both success and error events.. - */ - complete(handler: (err: Error, result: T) => void): PromiseT; - - /** - * Attach a function that is called every time the function that created this emitter executes a query. + * An OR query + * @see {Model#find} * - * @param onSQL + * @param args Each argument will be joined by OR */ - sql(onSQL: (sql: string) => void): PromiseT; + new ( ...args : Array ) : or; + } + interface json { + conditions?: Object; + path? : string; + value? : string | number | boolean; + } + + interface jsonStatic { /** - * Proxy every event of this promise to another one. + * Creates an object representing nested where conditions for postgres's json data-type. + * @see {Model#find} * - * @param promise The promise that should receive the events. - * @param options Contains an array of the events to proxy. Defaults to sql, error and success + * @method json + * @param conditionsOrPath A hash containing strings/numbers or other nested hash, a string using dot + * notation or a string using postgres json syntax. + * @param value An optional value to compare against. Produces a string of the form " = + * ''". */ - proxy(promise: PromiseT, options?: ProxyOptions): PromiseT; + new ( conditionsOrPath : string | Object, value? : string | number | boolean ) : json; + } - /** - * Attach listeners to the emitter, promise style. - * - * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). - * Note that this function will always only be called with one argument, as per - * the promises/A spec. For functions that emit multiple arguments - * (e.g. findOrCreate) @see spread - * @param onRejected - */ - then(onFulfilled?: (result?: T) => void, onRejected?: (result?: T) => void): Promise; + interface where { + attribute : Object; + comparator? : string; + logic : string | Object; + } + interface whereStatic { /** - * Attach listeners to the emitter, promise style. - * - * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). - * Note that this function will always only be called with one argument, as per - * the promises/A spec. For functions that emit multiple arguments - * (e.g. findOrCreate) @see spread - * @param onRejected + * A way of specifying attr = condition. + * + * The attr can either be an object taken from `Model.rawAttributes` (for example `Model.rawAttributes.id` + * or + * `Model.rawAttributes.name`). The attribute should be defined in your model definition. The attribute can + * also be an object from one of the sequelize utility functions (`sequelize.fn`, `sequelize.col` etc.) + * + * For string attributes, use the regular `{ where: { attr: something }}` syntax. If you don't want your + * string to be escaped, use `sequelize.literal`. + * + * @param attr The attribute, which can be either an attribute object from `Model.rawAttributes` or a + * sequelize object, for example an instance of `sequelize.fn`. For simple string attributes, use the + * POJO syntax + * @param comparator Comparator + * @param logic The condition. Can be both a simply type, or a further condition (`.or`, `.and`, `.literal` + * etc.) */ - then(onFulfilled?: (result?: T) => Promise, onRejected?: (result?: T) => Promise): Promise; + new ( attr : Object, comparator : string, logic : string | Object ) : where; + new ( attr : Object, logic : string | Object ) : where; + } - /** - * Attach listeners to the emitter, promise style. - * - * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). - * Note that this function will always only be called with one argument, as per - * the promises/A spec. For functions that emit multiple arguments - * (e.g. findOrCreate) @see spread - * @param onRejected - */ - then(onFulfilled?: (result?: T) => PromiseT, onRejected?: (result?: T) => PromiseT): PromiseT; + interface SequelizeLoDash extends _.LoDashStatic { + camelizeIf( str : string, condition : boolean ): string; + underscoredIf( str : string, condition : boolean ): string; /** - * Attach listeners to the emitter, promise style. - * - * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). - * Note that this function will always only be called with one argument, as per - * the promises/A spec. For functions that emit multiple arguments - * (e.g. findOrCreate) @see spread - * @param onRejected + * * Returns an array with some falsy values removed. The values null, "", undefined and NaN are considered + * falsey. + * + * @param arr Array to compact. */ - then(onFulfilled?: (result?: T) => PromiseT, onRejected?: (result?: T) => void): PromiseT; + compactLite( arr : Array ): Array; + matchesDots( dots : string | Array, value : Object ) : ( item : Object ) => boolean; - /** - * Attach listeners to the emitter, promise style. - * - * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). - * Note that this function will always only be called with one argument, as per - * the promises/A spec. For functions that emit multiple arguments - * (e.g. findOrCreate) @see spread - * @param onRejected - */ - then(onFulfilled?: (result?: T) => void, onRejected?: (result?: T) => PromiseT): PromiseT; - - /** - * Attach listeners to the emitter, promise style. - * - * @param onFulfilled The function to call if the promise is fulfilled (if the emitter emits success). - * Note that this function will always only be called with one argument, as per - * the promises/A spec. For functions that emit multiple arguments - * (e.g. findOrCreate) @see spread - * @param onRejected - */ - then(onFulfilled?: (result?: T) => PromiseT, onRejected?: (result?: T) => PromiseT): Promise; - - /** - * Shorthand for then(null, onRejected) - */ - catch(onRejected: (result?: T) => Promise): Promise; - - /** - * Shorthand for then(null, onRejected) - */ - catch(onRejected: (result?: T) => PromiseT): PromiseT; - - /** - * Shorthand for then(null, onRejected) - */ - catch(onRejected: (result?: T) => void): Promise; } interface Utils { - _: Lodash; - /** - * Formats a string to parse and interpolate values into the string based on the optionally provided SQL dialect. - * @param arr Array where first element is string with placeholders and remaining attributes are values to replace placeholders. - * @param dialect SQL Dialect. - */ - format(arr: Array, dialect?: string): string; - - /** - * Formats a SQL string replacing named placeholders with values from the parameters object with matching key names. - * - * @param sql String to format. - * @param parameters Key/value hash with values to replace in string. - * @param dialect SQL Dialect - */ - formatNamedParameters(sql: string, parameters: any, dialect?: string): string; - - injectScope(scope: string, merge: boolean): any; - - smartWhere(whereArg: any, dialect: string): any; - - compileSmartWhere(obj: any, dialect: string): Array; - - getWhereLogic(logic: string, val?: any): string; - - isHash(obj: any): boolean; - - hasChanged(attrValue: any, value: any): boolean; - - argsArePrimaryKeys(args: Array, primaryKeys: any): boolean; - - /** - * Consistently combines two table names such that the alphabetically first name always comes first when combined. - * - * @param table1 - * @param table2 - */ - combineTableNames(table1: string, table2: string): string; - - singularize(s: string, language?: string): string; - - pluralize(s: string, language: string): string; + _ : SequelizeLoDash; /** * Same concept as _.merge, but don't overwrite properties that have already been assigned */ - mergeDefaults: typeof _.merge; + mergeDefaults : typeof _.merge; - lowercaseFirst(str: string): string; + lowercaseFirst( str : string ): string; + uppercaseFirst( str : string ): string; + spliceStr( str : string, index : number, count : number, add : string ): string; + camelize( str : string ): string; + format( arr : Array, dialect? : string ): string; + formatNamedParameters( sql : string, parameters : any, dialect? : string ): string; + cloneDeep( obj : T, fn? : ( value : T ) => any ) : T; + mapOptionFieldNames( options : T, Model : Model ) : T; + mapValueFieldNames( dataValues : Object, fields : Array, Model : Model ) : Object; + argsArePrimaryKeys( args : Array, primaryKeys : Object ) : boolean; + canTreatArrayAsAnd( arr : Array ) : boolean; + combineTableNames( tableName1 : string, tableName2 : string ): string; + singularize( s : string ): string; + pluralize( s : string ): string; + removeCommentsFromFunctionString( s : string ): string; + toDefaultValue( value : DataTypeAbstract ): any; + toDefaultValue( value : () => DataTypeAbstract ): any; - uppercaseFirst(str: string): string; + /** + * Determine if the default value provided exists and can be described + * in a db schema using the DEFAULT directive. + */ + defaultValueSchemable( value : any ) : boolean; - spliceStr(str: string, index: number, count: number, add: string): string; - - camelize(str: string): string; - - removeCommentsFromFunctionString(s: string): string; - - toDefaultValue(value: any): any; - - defaultValueSchemable(value: any): boolean; - setAttributes(hash: any, identifier: string, instance: any, prefix: string): any; - removeNullValuesFromHash(hash: any, omitNull: boolean, options: any): any; - firstValueOfHash(obj: any): any; - inherit(subClass: any, superClass: any): any; + removeNullValuesFromHash( hash : Object, omitNull? : boolean, options? : Object ): any; + inherit( subClass : Object, superClass : Object ): Object; stack(): string; - now(dialect: string): Date; + sliceArgs( args : Array, begin? : number ) : Array; + now( dialect : string ): Date; + tick( f : Function ): void; + addTicks( s : string, tickChar? : string ): string; + removeTicks( s : string, tickChar? : string ): string; - /** - * Runs provided function on next tick, depending on environment. - * - * @param f - */ - tick(f: Function): void; + fn: fnStatic; + col: colStatic; + cast: castStatic; + literal: literalStatic; + and: andStatic; + or: orStatic; + json: jsonStatic; + where: whereStatic; - /** - * Surrounds a string with tick marks while removing all existing tick marks from the string. - * @param s String to tick - * @param tickChar Tick mark. Default ` - */ - addTicks(s: string, tickChar?: string): string; - - removeTicks(s: string, tickChar?: string): string; - - generateUUID(): string; - - validateParameter(value: any, expectation: any): boolean; - - CustomEventEmitter: EventEmitter; - Promise: Promise; - QueryChainer: QueryChainer; - Lingo: any; // external project, no definitions yet} - } - - interface Lodash extends _.LoDashStatic { - camelizeIf(str: string, condition: boolean): string; - camelizeIf(str: string, condition: any): string; - underscoredIf(str: string, condition: boolean): string; - underscoredIf(str: string, condition: any): string; - /** - * * Returns an array with some falsy values removed. The values null, "", undefined and NaN are considered falsey. - * - * @param arr Array to compact. - */ - compactLite(arr: Array): Array; - } - - interface MetaPojo { - from: string; - to: string; - } - interface MetaInstance extends MetaPojo, Model { + validateParameter( value : Object, expectation : Object, options? : Object ) : boolean; + formatReferences( obj : Object ) : Object; + Promise : typeof Promise; } - interface DataTypeStringBase { - BINARY: DataTypeString; - } - interface DataTypeNumberBase { - UNSIGNED: boolean; - ZEROFILL: boolean; - } - - interface DataTypeString extends DataTypeStringBase { - } - interface DataTypeChar extends DataTypeStringBase { - } - interface DataTypeInteger extends DataTypeNumberBase { - } - interface DataTypeBigInt extends DataTypeNumberBase { - } - interface DataTypeFloat extends DataTypeNumberBase { - } - interface DataTypeBlob { - } - interface DataTypeDecimal { - PRECISION: number; - SCALE: number; - } - - interface DataTypeVirtual { - } - interface DataTypeEnum { - (...values: Array): DataTypeEnum; - } - interface DataTypeArray { - } - interface DataTypeHstore { - } - - interface DataTypes { - STRING: DataTypeString; - CHAR: DataTypeChar; - TEXT: string; - INTEGER: DataTypeInteger; - BIGINT: DataTypeBigInt; - DATE: string; - BOOLEAN: string; - FLOAT: DataTypeFloat; - NOW: string; - BLOB: DataTypeBlob; - DECIMAL: DataTypeDecimal; - UUID: string; - UUIDV1: string; - UUIDV4: string; - VIRTUAL: DataTypeVirtual; - NONE: DataTypeVirtual; - ENUM: DataTypeEnum; - ARRAY: DataTypeArray; - HSTORE: DataTypeHstore; - } } - var sequelize: sequelize.SequelizeStatic; + var sequelize : sequelize.SequelizeStatic; export = sequelize; + } + From e33745b6ad27ee629cd47aa984f10478238e7ba6 Mon Sep 17 00:00:00 2001 From: Ivan Drinchev Date: Thu, 6 Aug 2015 20:28:53 +0200 Subject: [PATCH 041/345] Fixed tests for sequelize --- sequelize/sequelize-test.ts | 32 ++++++++++++++++---------------- sequelize/sequelize.d.ts | 6 +++--- 2 files changed, 19 insertions(+), 19 deletions(-) diff --git a/sequelize/sequelize-test.ts b/sequelize/sequelize-test.ts index ebc8cc0ce..e5656c76e 100644 --- a/sequelize/sequelize-test.ts +++ b/sequelize/sequelize-test.ts @@ -19,7 +19,7 @@ var Task = s.define( 'task', {} ); var Group = s.define( 'group', {} ); var Comment = s.define( 'comment', {} ); var Post = s.define( 'post', {} ); -var t = null; +var t : Sequelize.Transaction = null; s.transaction().then( ( a ) => t = a ); // @@ -319,11 +319,11 @@ new s.ConnectionTimedOutError( new Error( 'original connection error message' ) // https://github.com/sequelize/sequelize/blob/v3.4.1/test/integration/hooks.test.js // -User.addHook( 'afterCreate', function( instance, options, next ) { next(); } ); -User.addHook( 'afterCreate', 'myHook', function( instance, options, next ) { next(); } ); -s.addHook( 'beforeInit', function( config, options ) { } ); -User.hook( 'afterCreate', 'myHook', function( instance, options, next ) { next(); } ); -User.hook( 'afterCreate', 'myHook', function( instance, options, next ) { next(); } ); +User.addHook( 'afterCreate', function( instance : Sequelize.Instance, options : Object, next : Function ) { next(); } ); +User.addHook( 'afterCreate', 'myHook', function( instance : Sequelize.Instance, options : Object, next : Function) { next(); } ); +s.addHook( 'beforeInit', function( config : Object, options : Object ) { } ); +User.hook( 'afterCreate', 'myHook', function( instance : Sequelize.Instance, options : Object, next : Function) { next(); } ); +User.hook( 'afterCreate', 'myHook', function( instance : Sequelize.Instance, options : Object, next : Function ) { next(); } ); User.removeHook( 'afterCreate', 'myHook' ); @@ -477,10 +477,10 @@ user.update( { username : 'userman' }, { silent : true } ); user.update( { username : 'yolo' }, { logging : function() { } } ); user.update( { username : 'bar' }, { where : { username : 'foo' }, transaction : t } ).then( ( p ) => p ); user.updateAttributes( { a : 3 } ).then( ( p ) => p ); -user.updateAttributes( { a : 3 }, { fields : ['secretValue'], logging : function( sql ) {} } ); +user.updateAttributes( { a : 3 }, { fields : ['secretValue'], logging : function( ) {} } ); user.destroy().then( ( p ) => p ); -user.destroy( { logging : function( sql ) {} } ); +user.destroy( { logging : function( ) {} } ); user.destroy( { transaction : t } ).then( ( p ) => p ); user.restore(); @@ -519,7 +519,7 @@ User.sync( { force : true, logging : function() { } } ); User.drop(); User.schema( 'special' ); -User.schema( 'special' ).create( { age : 3 }, { logging : function( UserSpecial ) {} } ); +User.schema( 'special' ).create( { age : 3 }, { logging : function( ) {} } ); User.getTableName(); @@ -570,7 +570,7 @@ User.findById( 'a string' ); User.findOne( { where : { username : 'foo' } } ); User.findOne( { where : { id : 1 }, attributes : ['id', ['username', 'name']] } ); User.findOne( { where : { id : 1 }, attributes : ['id'] } ); -User.findOne( { where : { username : 'foo' }, logging : function( sql ) { } } ); +User.findOne( { where : { username : 'foo' }, logging : function( ) { } } ); User.findOne( { limit : 10 } ); User.findOne( { include : [1] } ); User.findOne( { where : { title : 'homework' }, include : [User] } ); @@ -601,15 +601,15 @@ User.findAndCountAll( { offset : 5, limit : 1, include : [User, { model : User, User.max( 'age', { transaction : t } ); User.max( 'age' ); -User.max( 'age', { logging : function( sql ) { } } ); +User.max( 'age', { logging : function( ) { } } ); User.min( 'age', { transaction : t } ); User.min( 'age' ); -User.min( 'age', { logging : function( sql ) { } } ); +User.min( 'age', { logging : function( ) { } } ); User.sum( 'order' ); User.sum( 'age', { where : { 'gender' : 'male' } } ); -User.sum( 'age', { logging : function( sql ) { } } ); +User.sum( 'age', { logging : function( ) { } } ); User.build( { username : 'John Wayne' } ).save(); User.build(); @@ -622,7 +622,7 @@ User.create( {}, { returning : true } ); User.create( { intVal : s.literal( 'CAST(1-2 AS' ) } ); User.create( { secretValue : s.fn( 'upper', 'sequelize' ) } ); User.create( { myvals : [1, 2, 3, 4], mystr : ['One', 'Two', 'Three', 'Four'] } ); -User.create( { name : 'Fluffy Bunny', smth : 'else' }, { logging : function( sql ) {} } ); +User.create( { name : 'Fluffy Bunny', smth : 'else' }, { logging : function( ) {} } ); User.create( {}, { fields : [] } ); User.create( { name : 'Yolo Bear', email : 'yolo@bear.com' }, { fields : ['name'] } ); User.create( { title : 'Chair', User : { first_name : 'Mick', last_name : 'Broadstone' } }, { include : [User] } ); @@ -637,7 +637,7 @@ User.findOrInitialize( { where : { username : 'foo' }, defaults : { foo : 'asd' User.findOrCreate( { where : { a : 'b' }, defaults : { json : { a : { b : 'c' }, d : [1, 2, 3] } } } ); User.findOrCreate( { where : { a : 'b' }, defaults : { json : 'a', data : 'b' } } ); User.findOrCreate( { where : { a : 'b' }, transaction : t, lock : t.LOCK.UPDATE } ); -User.findOrCreate( { where : { a : 'b' }, logging : function( sql ) { } } ); +User.findOrCreate( { where : { a : 'b' }, logging : function( ) { } } ); User.findOrCreate( { where : { username : 'Username' }, defaults : { data : 'some data' }, transaction : t } ); User.findOrCreate( { where : { objectId : 'asdasdasd' }, defaults : { username : 'gottlieb' } } ); User.findOrCreate( { where : { id : undefined }, defaults : { name : Math.random().toString() } } ); @@ -790,7 +790,7 @@ s.model( 'pp' ); s.query( '', { raw : true } ); s.query( '' ); s.query( '' ).then( function( res ) {} ); -s.query( '' ).spread( function( a ) {}, function( b ) {} ); +s.query( '' ).spread( function( ) {}, function( b ) {} ); s.query( { query : 'select ? as foo, ? as bar', values : [1, 2] }, { raw : true, replacements : [1, 2] } ); s.query( '', { raw : true, nest : false } ); s.query( 'select ? as foo, ? as bar', { type : this.sequelize.QueryTypes.SELECT, replacements : [1, 2] } ); diff --git a/sequelize/sequelize.d.ts b/sequelize/sequelize.d.ts index a97479d2b..4c2294e6f 100644 --- a/sequelize/sequelize.d.ts +++ b/sequelize/sequelize.d.ts @@ -5,9 +5,9 @@ // Based on original work by: samuelneff -/// -/// -/// +/// +/// +/// declare module "sequelize" { From 52854d5f1c46796481428d3ab7be722b6c47c869 Mon Sep 17 00:00:00 2001 From: Greg Smith Date: Mon, 10 Aug 2015 13:17:20 -0500 Subject: [PATCH 042/345] Update velocity-animate.d.ts for latest Velocity --- velocity-animate/velocity-animate-tests.ts | 59 +++++++++++ velocity-animate/velocity-animate.d.ts | 116 ++++++++++++++------- 2 files changed, 136 insertions(+), 39 deletions(-) diff --git a/velocity-animate/velocity-animate-tests.ts b/velocity-animate/velocity-animate-tests.ts index 96400d365..afcd8b563 100644 --- a/velocity-animate/velocity-animate-tests.ts +++ b/velocity-animate/velocity-animate-tests.ts @@ -293,3 +293,62 @@ function advanced_utility_function () { options: { duration: 1500 } }); } + +function ui_pack_sequence_running() { + var $element1: JQuery; + var $element2: JQuery; + var $element3: JQuery; + + $element1.velocity({ translateX: 100 }, 1000, function() { + $element2.velocity({ translateX: 200 }, 1000, function() { + $element3.velocity({ translateX: 300 }, 1000); + }); + }); + + var mySequence = [ + { e: $element1, p: { translateX: 100 }, o: { duration: 1000 } }, + { e: $element2, p: { translateX: 200 }, o: { duration: 1000 } }, + { e: $element3, p: { translateX: 300 }, o: { duration: 1000 } } + ]; + $.Velocity.RunSequence(mySequence); + + var mySequence2 = [ + { e: $element1, p: { translateX: 100 }, o: { duration: 1000 } }, + /* The call below will run at the same time as the first call. */ + { e: $element2, p: { translateX: 200 }, o: { duration: 1000, sequenceQueue: false } }, + /* As normal, the call below will run once the second call is complete. */ + { e: $element3, p: { translateX: 300 }, o: { duration: 1000 } } + ]; + $.Velocity.RunSequence(mySequence2); +} + +function ui_pack_registration() { + var $element: JQuery; + + $.Velocity.RegisterEffect("callout.pulse", { + defaultDuration: 900, + calls: [ + [ { scaleX: 1.1 }, 0.50 ], + [ { scaleX: 1 }, 0.50 ] + ] + }); + $element.velocity("callout.pulse"); + + $.Velocity + .RegisterEffect("transition.flipXIn", { + defaultDuration: 700, + calls: [ + [ { opacity: 1, rotateY: [ 0, -55 ] } ] + ] + }) + .RegisterEffect("transition.flipXOut", { + defaultDuration: 700, + calls: [ + [ { opacity: 0, rotateY: 55 } ] + ], + reset: { rotateY: 0 } + }); + $element + .velocity("transition.flipXIn") + .velocity("transition.flipXOut", { delay: 1000 }); +} diff --git a/velocity-animate/velocity-animate.d.ts b/velocity-animate/velocity-animate.d.ts index 6946da972..9a1f58aa0 100644 --- a/velocity-animate/velocity-animate.d.ts +++ b/velocity-animate/velocity-animate.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Velocity 0.0.22 +// Type definitions for Velocity 1.2.2 // Project: http://velocityjs.org/ // Definitions by: Greg Smith // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -6,14 +6,13 @@ /// interface JQuery { - velocity(options: {properties: Object; options: jquery.velocity.VelocityOptions}): JQuery; - velocity(properties: Object, options: jquery.velocity.VelocityOptions): JQuery; - velocity(properties: Object, duration?: number, easing?: string, complete?: jquery.velocity.ElementCallback): JQuery; - velocity(properties: Object, duration?: number, easing?: number[], complete?: jquery.velocity.ElementCallback): JQuery; - velocity(properties: Object, duration?: number, complete?: jquery.velocity.ElementCallback): JQuery; - velocity(properties: Object, easing?: string, complete?: jquery.velocity.ElementCallback): JQuery; - velocity(properties: Object, easing?: number[], complete?: jquery.velocity.ElementCallback): JQuery; - velocity(properties: Object, complete?: jquery.velocity.ElementCallback): JQuery; + velocity(name: string, options: jquery.velocity.RegisteredEffectOptions): JQuery; + velocity(options: {properties: jquery.velocity.Properties; options: jquery.velocity.Options}): JQuery; + velocity(properties: jquery.velocity.Properties, options: jquery.velocity.Options): JQuery; + velocity(properties: jquery.velocity.Properties, duration: number, easing: jquery.velocity.Easing, complete?: jquery.velocity.ElementCallback): JQuery; + velocity(properties: jquery.velocity.Properties, duration: number, complete?: jquery.velocity.ElementCallback): JQuery; + velocity(properties: jquery.velocity.Properties, easing: jquery.velocity.Easing, complete?: jquery.velocity.ElementCallback): JQuery; + velocity(properties: jquery.velocity.Properties, complete?: jquery.velocity.ElementCallback): JQuery; } interface JQueryStatic { @@ -21,42 +20,81 @@ interface JQueryStatic { } declare module jquery.velocity { - interface ElementCallback { - (elements: NodeListOf): void; + type Properties = Object; + type Easing = string|number[]; + type ElementCallback = (elements: NodeListOf) => void; + type ProgressCallback = (elements: NodeListOf, percentComplete: number, timeRemaining: number, timeStart: number) => void; + type EffectCall = + [Properties] | + [Properties, number] | + [Properties, EffectCallOptions] | + [Properties, number, EffectCallOptions]; + + interface EffectCallOptions { + delay?: any; + easing?: any; } - interface ProgressCallback { - (elements: NodeListOf, percentComplete: number, timeRemaining: number, timeStart: number): void; + interface Options { + queue?: string|boolean; + duration?: string|number; + easing?: Easing; + begin?: ElementCallback; + complete?: ElementCallback; + progress?: ProgressCallback; + display?: string|boolean; + loop?: number|boolean; + delay?: number|boolean; + mobileHA?: boolean; + _cacheValues?: boolean; + } + + interface RegisterEffectOptions { + defaultDuration?: number; + calls: EffectCall[]; + reset?: Object; + } + + interface RegisteredEffectOptions { + duration?: string|number; + begin?: ElementCallback; + complete?: ElementCallback; + display?: string; + delay?: number; + mobileHA?: boolean; + _cacheValues?: boolean; + stagger?: number; + drag?: boolean; + backwards?: boolean; + } + + interface SequenceCall { + e: HTMLElement|JQuery; + p: Properties; + o: SequenceOptions; + } + + interface SequenceOptions extends Options { + sequenceQueue?: boolean; } interface VelocityStatic { Sequences: any; - animate(options: {elements: NodeListOf; properties: Object; options: VelocityOptions}): void; - animate(elements: NodeListOf, properties: Object, options: VelocityOptions): void; - animate(element: HTMLElement, properties: Object, options: VelocityOptions): void; - /** - * Get a hook value. Hooks are the subvalues of multi-value CSS properties. - * It features the same API as $.css(). - */ - hook(element: HTMLElement|JQuery, cssKey: string): string; - /** - * Set a hook value. Hooks are the subvalues of multi-value CSS properties. - * It features the same API as $.css(). - */ - hook(element: HTMLElement|JQuery, cssKey: string, cssValue: string): void; - } + animate(options: {elements: NodeListOf; properties: Properties; options: Options}): any; + animate(elements: HTMLElement|NodeListOf, properties: Properties, options: Options): any; + RegisterEffect(name: string, options: RegisterEffectOptions): VelocityStatic; + RunSequence(sequence: SequenceCall[]): VelocityStatic; - interface VelocityOptions { - queue?: any; - duration?: any; - easing?: any; - begin?: ElementCallback; - complete?: ElementCallback; - progress?: ProgressCallback; - display?: any; - loop?: any; - delay?: any; - mobileHA?: boolean; - _cacheValues?: boolean; + /** + * Get a hook value. Hooks are the subvalues of multi-value CSS properties. + * It features the same API as $.css(). + */ + hook(element: HTMLElement|JQuery, cssKey: string): string; + + /** + * Set a hook value. Hooks are the subvalues of multi-value CSS properties. + * It features the same API as $.css(). + */ + hook(element: HTMLElement|JQuery, cssKey: string, cssValue: string): void; } } From d874adfcb6391e3345cf2f30088a43138a2aee05 Mon Sep 17 00:00:00 2001 From: almstrand Date: Wed, 12 Aug 2015 17:20:07 -0700 Subject: [PATCH 043/345] Correct enum THREE.MOUSE to include the only valid values {LEFT, MIDDLE, RIGHT}. Remove properties THREE.LEFT, THREE.MIDDLE, and THREE.RIGHT as those are not defined in the most recent version of Three.js (r71). --- threejs/three.d.ts | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/threejs/three.d.ts b/threejs/three.d.ts index 826d6332f..7942222b7 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -11,10 +11,7 @@ declare module THREE { export var REVISION: string; // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.button - export enum MOUSE { } - export var LEFT: MOUSE; - export var MIDDLE: MOUSE; - export var RIGHT: MOUSE; + export enum MOUSE {LEFT, MIDDLE, RIGHT} // GL STATE CONSTANTS export enum CullFace { } From 5d0102d544c46020090d8cea9fb6ec82e7997650 Mon Sep 17 00:00:00 2001 From: Almouro Date: Sat, 15 Aug 2015 20:20:49 +0200 Subject: [PATCH 044/345] Add ability to create element without using load --- cheerio/cheerio-tests.ts | 2 ++ cheerio/cheerio.d.ts | 19 +++++++++++++------ 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/cheerio/cheerio-tests.ts b/cheerio/cheerio-tests.ts index af671cd00..c02b1ed26 100644 --- a/cheerio/cheerio-tests.ts +++ b/cheerio/cheerio-tests.ts @@ -2,6 +2,8 @@ import cheerio = require("cheerio"); +cheerio(''); + var $ = cheerio.load(""); var $el = $('selector'); var $multiEl = $('seletor', 'selector', 'selector'); diff --git a/cheerio/cheerio.d.ts b/cheerio/cheerio.d.ts index fc8e5a70f..bbd47810f 100644 --- a/cheerio/cheerio.d.ts +++ b/cheerio/cheerio.d.ts @@ -172,11 +172,7 @@ interface CheerioOptionsInterface { normalizeWhitespace?: boolean; } -interface CheerioStatic { - // Document References - // Cheerio https://github.com/cheeriojs/cheerio - // JQuery http://api.jquery.com - +interface CheerioSelector { (selector: string): Cheerio; (selector: string, context: string): Cheerio; (selector: string, context: CheerioElement): Cheerio; @@ -187,7 +183,12 @@ interface CheerioStatic { (selector: string, context: CheerioElement[], root: string): Cheerio; (selector: string, context: Cheerio, root: string): Cheerio; (selector: any): Cheerio; +} +interface CheerioStatic extends CheerioSelector { + // Document References + // Cheerio https://github.com/cheeriojs/cheerio + // JQuery http://api.jquery.com xml(): string; root(): Cheerio; contains(container: CheerioElement, contained: CheerioElement): boolean; @@ -213,6 +214,12 @@ interface CheerioElement { root: CheerioElement; } +interface CheerioAPI extends CheerioSelector { + load(html: string, options?: CheerioOptionsInterface): CheerioStatic; +} + +declare var cheerio:CheerioAPI; + declare module "cheerio" { - export function load(html: string, options?: CheerioOptionsInterface): CheerioStatic; + export = CheerioAPI; } From 2004f8fc47187af24b8d5ba9ae96e6ebf81f6a35 Mon Sep 17 00:00:00 2001 From: Almouro Date: Sat, 15 Aug 2015 20:21:35 +0200 Subject: [PATCH 045/345] Updated definition and tests to reflect Cheerio doc --- cheerio/cheerio-tests.ts | 335 ++++++++++++++++++++++++++++++++------- cheerio/cheerio.d.ts | 46 +++++- 2 files changed, 322 insertions(+), 59 deletions(-) diff --git a/cheerio/cheerio-tests.ts b/cheerio/cheerio-tests.ts index c02b1ed26..6cc9e6485 100644 --- a/cheerio/cheerio-tests.ts +++ b/cheerio/cheerio-tests.ts @@ -1,67 +1,294 @@ /// -import cheerio = require("cheerio"); +import cheerio = require('cheerio'); -cheerio(''); +/* + * LOADING + */ +let html = +`
      +
    • Apple
    • +
    • Orange
    • +
    • Pear
    • + +
    `; -var $ = cheerio.load(""); -var $el = $('selector'); -var $multiEl = $('seletor', 'selector', 'selector'); +// Preferred Method +var $ = cheerio.load(html); +// Directly load element +cheerio(html); +cheerio('ul', html); +cheerio('li', 'ul', html); -$el.addClass("class").addClass("test"); -$el.hasClass("test"); -$el.removeClass("class").removeClass("test"); - -$el.attr('class'); -$el.attr('class', 'test'); -$el.removeAttr("class").removeAttr("test"); - -$el.find("ul").find("> li"); - -$el.parent().parent(); -$el.next().next(); -$el.prev().prev(); -$el.siblings().siblings(); - -$el.children().children(); -$el.children("li").children("a"); - -$el.children().each((index, element) => { - return $(element).find('t'); +$ = cheerio.load(html, { + normalizeWhitespace: true, + xmlMode: true }); -$el.children().map((index, element) => { - return $(element).find('t'); +$ = cheerio.load(html, { + normalizeWhitespace: true, + xmlMode: true, + decodeEntities: true, + lowercaseTags: true, + lowerCaseAttributeNames: true, + recognizeCDATA: true, + recognizeSelfClosing: true }); -$el.children().filter((index) => { - return $el.children().eq(index).find('t').length >= 0; -}); +/** + * Selectors + */ +var $el = $('.class'); +var $multiEl = $('selector', 'selector', 'selector'); -$el.filter('span').filter('li'); +/** + * Attributes + */ -$el.first().last().find('t'); - -$('div').eq(0).find('b'); - -$('#id').append("test html", "other html").find('a'); -$('#id').prepend("test html", "other html").find('a'); -$('#id').after("test html", "other html").find('a'); -$('#id').before("test html", "other html").find('a'); - -$el.remove('div').remove('a'); - -$('#id').replaceWith('some html').parent(); -$('#id').empty().parent(); - -$el.html(); -$el.html("").find('div'); - -$el.text(); -$el.text('some text'); - -$el.toArray(); -$el.clone().find('a').parent(); -$.root().find('a'); +// attr +$el.attr('id'); +$el.attr('id', 'favorite').html(); +// data $el.data(); +$el.data('apple-color'); +$el.data('kind', 'mac'); + +// val +$('input[type="text"]').val(); +$('input[type="text"]').val('test').html(); + +// removeAttr +$el.removeAttr('class').html(); + +// hasClass, addClass, removeClass, toggleClass +$el.addClass('class').addClass('test'); +$el.hasClass('test'); +$el.removeClass('class').removeClass('test'); +$el.addClass('red').removeClass().html(); +$el.toggleClass('fruit green red').html(); + +// is +$el.is('#id'); +$el.is($el); +$el.is(() => { + return true; +}); + +/** + * Forms + */ +// serializeArray +$('
    ').serializeArray(); + +/** + * Traversing + */ + // find +$el.find('li').length; +$el.find($('.apple')).length; + +// .parent([selector]) +$el.parent().attr('id'); +$el.parent('.class').attr('id'); + +// .parents([selector]) +$el.parents().length; +$el.parents('.class').length; + +// .parentsUntil([selector][,filter]) +$el.parentsUntil().length; +$el.parentsUntil('.class').length; + +// .closest(selector) +$el.closest(); +$el.closest('.class'); + +// .next([selector]) +$el.next().hasClass('class'); +$el.next('.class').hasClass('class'); + +// .nextAll([selector]) +$el.nextAll().length; +$el.nextAll('.class').length; + +// .nextUntil([selector], [filter]) +$el.nextUntil(); +$el.nextUntil('.class'); + +// .prev([selector]) +$el.prev().hasClass('class'); +$el.prev('.class').hasClass('class'); + +// .prevAll([selector]) +$el.prevAll().length; +$el.prevAll('.class').length; + +// .prevUntil([selector], [filter]) +$el.prevUntil(); +$el.prevUntil('.class'); + +// .slice( start, [end] ) +$el.slice(1).eq(0).text(); +$el.slice(1, 2).length; + +// .siblings([selector]) +$el.siblings().length; +$el.siblings('.class').length; + +// .children([selector]) +$el.children().length; +$el.children('.class').text(); + +// .contents() +$el.contents().length; + +// .each( function(index, element) ) +$el.each((i, el) => { + $(el).html(); +}); + +// .map( function(index, element) ) +$el.map((i, el) => { + return $(el).text(); +}).get().join(' '); + +// .filter +$ = cheerio.load(html); +$el.filter('.class').attr('class'); +$el.filter($('.class')).attr('class'); +$el.filter($('.class')[0]).attr('class'); + +$el.filter((i, el) => { + return $(el).attr('class') === 'class'; +}).attr('class'); + +// .not +$el.not('.class').length; +$el.not($('.class')).length; +$el.not($('.class')[0]).length; + +$el.not((i, el) => { + return $(el).attr('class') === 'class'; +}).length; + +// .has +$el.has('.class').attr('id'); +$el.has($el[0]).attr('id'); + +// .first() +$el.children().first().text(); + +// .last() +$el.children().last().text(); + +// .eq( i ) +$el.eq(0).text(); +$el.eq(-1).text(); + +// .get( [i] ) +$el.get(0).tagName; +$el.get().length; + +// .index() +// .index( selector ) +// .index( nodeOrSelection ) +$el.index(); +$el.index('li'); +$el.index($('#fruit, li')); + +// .end() +$el.eq(0).end().length; + +// .add +$el.add('.class').length + +// .addBack( [filter] ) +$el.eq(0).addBack().length +$el.eq(0).addBack('.class').length + +/** + * Manipulation + */ + +// .append( content, [content, ...] ) +$el.append('
  • Plum
  • ').html(); +$el.append('
  • Plum
  • ', '
  • Plum
  • ').html(); + +// .prepend( content, [content, ...] ) +$el.prepend('
  • Plum
  • ').html(); +$el.prepend('
  • Plum
  • ', '
  • Plum
  • ').html(); + +// .after( content, [content, ...] ) +$el.after('
  • Plum
  • ').html(); +$el.after('
  • Plum
  • ', '
  • Plum
  • ').html(); + +// .insertAfter( content ) +$('
  • Plum
  • ').insertAfter('.class').html(); + +// .before( content, [content, ...] ) +$el.before('
  • Plum
  • ').html(); +$el.before('
  • Plum
  • ', '
  • Plum
  • ').html(); + +// .insertBefore( content ) +$('
  • Plum
  • ').insertBefore('.class').html(); + +// .remove( [selector] ) +$el.remove().html(); +$el.remove('.class').html(); + +// .replaceWith( content ) +$el.replaceWith($('
  • Plum
  • ')).html(); + +// .empty() +$el.empty().html(); + +// .html( [htmlString] ) +$el.html(); +$el.html('
  • Mango
  • ').html(); + +// .text( [textString] ) +$el.text(); +$el.text('text'); + +// .wrap( content ) +// See https://github.com/cheeriojs/cheerio/issues/731 +// $el.wrap($('
    ')).html(); + +// .css +$el.css('width'); +$el.css(['width', 'height']); +$el.css('width', '50px'); + +/** + * Rendering + */ +$.html(); +$.html('.class'); +$.xml(); + +/** + * Miscellaneous + */ + +// .clone() #### +$el.clone().html(); + +/** + * Utilities + */ + +// $.root +$.root().append('
      ').html(); + +// $.contains( container, contained ) +$.contains($el[0], $el[0]); + +// $.parseHTML( data [, context ] [, keepScripts ] ) +$.parseHTML(html); +$.parseHTML(html, null, true); + +/** + * Not in doc + */ +$el.toArray(); diff --git a/cheerio/cheerio.d.ts b/cheerio/cheerio.d.ts index bbd47810f..840cceef5 100644 --- a/cheerio/cheerio.d.ts +++ b/cheerio/cheerio.d.ts @@ -17,12 +17,17 @@ interface Cheerio { attr(name: string, value: any): Cheerio; data(): any; + data(name: string): any; + data(name: string, value: any): any; val(): string; val(value: string): Cheerio; removeAttr(name: string): Cheerio; + has(selector: string): Cheerio; + has(element: CheerioElement): Cheerio; + hasClass(className: string): boolean; addClass(classNames: string): Cheerio; @@ -41,6 +46,9 @@ interface Cheerio { is(selection: Cheerio): boolean; is(func: (index: number, element: CheerioElement) => boolean): boolean; + // Form + serializeArray(): {name: string, value: string}[]; + // Traversing find(selector: string): Cheerio; @@ -52,10 +60,12 @@ interface Cheerio { parentsUntil(element: CheerioElement, filter?: string): Cheerio; parentsUntil(element: Cheerio, filter?: string): Cheerio; + closest(): Cheerio; closest(selector: string): Cheerio; next(selector?: string): Cheerio; nextAll(): Cheerio; + nextAll(selector: string): Cheerio; nextUntil(selector?: string, filter?: string): Cheerio; nextUntil(element: CheerioElement, filter?: string): Cheerio; @@ -63,6 +73,7 @@ interface Cheerio { prev(selector?: string): Cheerio; prevAll(): Cheerio; + prevAll(selector: string): Cheerio; prevUntil(selector?: string, filter?: string): Cheerio; prevUntil(element: CheerioElement, filter?: string): Cheerio; @@ -83,15 +94,24 @@ interface Cheerio { filter(selection: Cheerio): Cheerio; filter(element: CheerioElement): Cheerio; filter(elements: CheerioElement[]): Cheerio; - filter(func: (index: number) => boolean): Cheerio; + filter(func: (index: number, element: CheerioElement) => boolean): Cheerio; + + not(selector: string): Cheerio; + not(selection: Cheerio): Cheerio; + not(element: CheerioElement): Cheerio; + not(func: (index: number, element: CheerioElement) => boolean): Cheerio; first(): Cheerio; last(): Cheerio; eq(index: number): Cheerio; - get(): Document[]; - get(index: number): Document; + get(): CheerioElement[]; + get(index: number): CheerioElement; + + index(): number; + index(selector: string): number; + index(selection: Cheerio): number; end(): Cheerio; @@ -101,6 +121,9 @@ interface Cheerio { add(elements: CheerioElement[]): Cheerio; add(selection: Cheerio): Cheerio; + addBack():Cheerio; + addBack(filter: string):Cheerio; + // Manipulation append(content: string, ...contents: any[]): Cheerio; @@ -118,11 +141,19 @@ interface Cheerio { after(content: Document[], ...contents: any[]): Cheerio; after(content: Cheerio, ...contents: any[]): Cheerio; + insertAfter(content: string): Cheerio; + insertAfter(content: Document): Cheerio; + insertAfter(content: Cheerio): Cheerio; + before(content: string, ...contents: any[]): Cheerio; before(content: Document, ...contents: any[]): Cheerio; before(content: Document[], ...contents: any[]): Cheerio; before(content: Cheerio, ...contents: any[]): Cheerio; + insertBefore(content: string): Cheerio; + insertBefore(content: Document): Cheerio; + insertBefore(content: Cheerio): Cheerio; + remove(selector?: string): Cheerio; replaceWith(content: string): Cheerio; @@ -138,6 +169,11 @@ interface Cheerio { text(): string; text(text: string): Cheerio; + // See https://github.com/cheeriojs/cheerio/issues/731 + /*wrap(content: string): Cheerio; + wrap(content: Document): Cheerio; + wrap(content: Cheerio): Cheerio;*/ + css(propertyName: string): string; css(propertyNames: string[]): string[]; css(propertyName: string, value: string): Cheerio; @@ -203,7 +239,7 @@ interface CheerioStatic extends CheerioSelector { interface CheerioElement { // Document References // Node Console - + tagName: string; type: string; name: string; attribs: Object; @@ -221,5 +257,5 @@ interface CheerioAPI extends CheerioSelector { declare var cheerio:CheerioAPI; declare module "cheerio" { - export = CheerioAPI; + export = cheerio; } From 3e6f9cbd89c1e8df81a0ffb16cbc8bab965881ae Mon Sep 17 00:00:00 2001 From: Almouro Date: Sun, 16 Aug 2015 11:51:43 +0200 Subject: [PATCH 046/345] Support ES6 import syntax --- cheerio/cheerio-tests.ts | 2 +- cheerio/cheerio.d.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cheerio/cheerio-tests.ts b/cheerio/cheerio-tests.ts index 6cc9e6485..c41939a30 100644 --- a/cheerio/cheerio-tests.ts +++ b/cheerio/cheerio-tests.ts @@ -1,6 +1,6 @@ /// -import cheerio = require('cheerio'); +import cheerio from 'cheerio'; /* * LOADING diff --git a/cheerio/cheerio.d.ts b/cheerio/cheerio.d.ts index 840cceef5..8118d3366 100644 --- a/cheerio/cheerio.d.ts +++ b/cheerio/cheerio.d.ts @@ -257,5 +257,5 @@ interface CheerioAPI extends CheerioSelector { declare var cheerio:CheerioAPI; declare module "cheerio" { - export = cheerio; + export default cheerio; } From 81166431feac33c727dc0b02014b7265efa85c32 Mon Sep 17 00:00:00 2001 From: Almouro Date: Sun, 16 Aug 2015 12:12:43 +0200 Subject: [PATCH 047/345] Updated Cheerio Element definition according to doc --- cheerio/cheerio.d.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/cheerio/cheerio.d.ts b/cheerio/cheerio.d.ts index 8118d3366..57d526d1b 100644 --- a/cheerio/cheerio.d.ts +++ b/cheerio/cheerio.d.ts @@ -244,10 +244,15 @@ interface CheerioElement { name: string; attribs: Object; children: CheerioElement[]; + childNodes: CheerioElement[]; + lastChild: CheerioElement; next: CheerioElement; + nextSibling: CheerioElement; prev: CheerioElement; + previousSibling: CheerioElement; parent: CheerioElement; - root: CheerioElement; + parentNode: CheerioElement; + nodeValue: string; } interface CheerioAPI extends CheerioSelector { From d34aa2d731960f59d8fc6ebfd88679582369c2d7 Mon Sep 17 00:00:00 2001 From: rhysd Date: Mon, 17 Aug 2015 16:49:39 +0900 Subject: [PATCH 048/345] Added WebContents.print(), webContents.printToPDF() and aliases for BrowserWindow Added definitions for below APIs. - `WebContents.print([options])` https://github.com/atom/electron/blob/master/docs/api/browser-window.md#webcontentsprintoptions - `WebContents.printToPDF(options, callback)` https://github.com/atom/electron/blob/master/docs/api/browser-window.md#webcontentsprinttopdfoptions-callback - `BrowserWindow`'s aliases' https://github.com/atom/electron/blob/master/docs/api/browser-window.md#browserwindowprintoptions --- github-electron/github-electron-main-tests.ts | 29 ++++++++ github-electron/github-electron.d.ts | 73 +++++++++++++++++-- 2 files changed, 96 insertions(+), 6 deletions(-) diff --git a/github-electron/github-electron-main-tests.ts b/github-electron/github-electron-main-tests.ts index d353dfeb3..14480059c 100644 --- a/github-electron/github-electron-main-tests.ts +++ b/github-electron/github-electron-main-tests.ts @@ -51,6 +51,35 @@ app.on('ready', () => { // when you should delete the corresponding element. mainWindow = null; }); + + mainWindow.print({silent: true, printBackground: false}); + mainWindow.webContents.print({silent: true, printBackground: false}); + mainWindow.print(); + mainWindow.webContents.print(); + + mainWindow.print({silent: true, printBackground: false}); + mainWindow.webContents.print({silent: true, printBackground: false}); + mainWindow.print(); + mainWindow.webContents.print(); + + mainWindow.printToPDF({ + marginsType: 1, + pageSize: 'A3', + printBackground: true, + printSelectionOnly: true, + landscape: true, + }, (error: Error, data: Buffer) => {}); + + mainWindow.webContents.printToPDF({ + marginsType: 1, + pageSize: 'A3', + printBackground: true, + printSelectionOnly: true, + landscape: true, + }, (error: Error, data: Buffer) => {}); + + mainWindow.printToPDF({}, (err, data) => {}); + mainWindow.webContents.printToPDF({}, (err, data) => {}); }); // Desktop environment integration diff --git a/github-electron/github-electron.d.ts b/github-electron/github-electron.d.ts index 5df526bfc..5624b406b 100644 --- a/github-electron/github-electron.d.ts +++ b/github-electron/github-electron.d.ts @@ -377,17 +377,22 @@ declare module GitHubElectron { capturePage(rect: Rectangle, callback: (image: NativeImage) => void): void; capturePage(callback: (image: NativeImage) => void): void; /** - * Prints the window's web page. Calling window.print() in a web page is - * equivalent to calling BrowserWindow.print({silent: false, printBackground: false}). + * Same with webContents.print([options]) */ print(options?: { - /** - * When false, Electron will pick up system's default printer and default - * settings for printing. - */ silent?: boolean; printBackground?: boolean; }): void; + /** + * Same with webContents.printToPDF([options]) + */ + printToPDF(options: { + marginsType?: number; + pageSize?: string; + printBackground?: boolean; + printSelectionOnly?: boolean; + landscape?: boolean; + }, callback: (error: Error, data: Buffer) => void): void; /** * Same with webContents.loadUrl(url). */ @@ -659,6 +664,62 @@ declare module GitHubElectron { * @param isFulfilled Whether the JS promise is fulfilled. */ (isFulfilled: boolean) => void): void; + /** + * + * Prints window's web page. When silent is set to false, Electron will pick up system's default printer and default settings for printing. + * Calling window.print() in web page is equivalent to call WebContents.print({silent: false, printBackground: false}). + * Note: + * On Windows, the print API relies on pdf.dll. If your application doesn't need print feature, you can safely remove pdf.dll in saving binary size. + */ + print(options?: { + /** + * Don't ask user for print settings, defaults to false + */ + silent?: boolean; + /** + * Also prints the background color and image of the web page, defaults to false. + */ + printBackground: boolean; + }): void; + /** + * Prints windows' web page as PDF with Chromium's preview printing custom settings. + */ + printToPDF(options: { + /** + * Specify the type of margins to use. Default is 0. + * 0 - default + * 1 - none + * 2 - minimum + */ + marginsType?: number; + /** + * String - Specify page size of the generated PDF. Default is A4. + * A4 + * A3 + * Legal + * Letter + * Tabloid + */ + pageSize?: string; + /** + * Whether to print CSS backgrounds. Default is false. + */ + printBackground?: boolean; + /** + * Whether to print selection only. Default is false. + */ + printSelectionOnly?: boolean; + /** + * true for landscape, false for portrait. Default is false. + */ + landscape?: boolean; + }, + /** + * Callback function on completed converting to PDF. + * error Error + * data Buffer - PDF file content + */ + callback: (error: Error, data: Buffer) => void): void; /** * Send args.. to the web page via channel in asynchronous message, the web page * can handle it by listening to the channel event of ipc module. From 240061021b321a7729a660f518ea61037b37bdcb Mon Sep 17 00:00:00 2001 From: Oguzhan Ergin Date: Mon, 17 Aug 2015 15:34:22 +0300 Subject: [PATCH 049/345] Added fs-ext definitions --- fs-ext/fs-ext.d.ts | 102 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 fs-ext/fs-ext.d.ts diff --git a/fs-ext/fs-ext.d.ts b/fs-ext/fs-ext.d.ts new file mode 100644 index 000000000..00f63c5a0 --- /dev/null +++ b/fs-ext/fs-ext.d.ts @@ -0,0 +1,102 @@ +// Type definitions for fs-ext +// Project: https://github.com/baudehlo/node-fs-ext +// Definitions by: Oguzhan Ergin +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "fs-ext" { + export * from "fs"; + + /** + * Asynchronous flock(2). No arguments other than a possible error are passed to the callback. + * @param fd File Descriptor + * @param flags Flags can be 'sh', 'ex', 'shnb', 'exnb', 'un' and correspond to the various LOCK_SH, LOCK_EX, LOCK_SH|LOCK_NB, etc. + **/ + export function flock(fd: number, flags: string, callback: (err: Error) => void): void; + + /** + * Synchronous flock(2). Throws an exception on error. + * @param fd File Descriptor + * @param flags Flags can be 'sh', 'ex', 'shnb', 'exnb', 'un' and correspond to the various LOCK_SH, LOCK_EX, LOCK_SH|LOCK_NB, etc. + **/ + export function flockSync(fd: number, flags: string):void; + + /** + * Asynchronous fcntl(2). + * @param fd File Descriptor + * @param cmd The supported commands are: 'getfd' ( F_GETFD ) , 'setfd' ( F_SETFD ) + * Requiring this module adds FD_CLOEXEC to the constants module, for use with F_SETFD. + * @param arg arg + **/ + export function fcntl(fd: number, cmd: string, arg: number, callback: (err: Error, result: number) => void):void; + + /** + * Asynchronous fcntl(2). + * @param fd File Descriptor + * @param cmd The supported commands are: 'getfd' ( F_GETFD ) , 'setfd' ( F_SETFD ) + * Requiring this module adds FD_CLOEXEC to the constants module, for use with F_SETFD. + **/ + export function fcntl(fd: number, cmd: string, callback: (err: Error, result: number) => void):void; + + /** + * Synchronous fcntl(2). Throws an exception on error. + * @param fd File Descriptor + * @param cmd The supported commands are: 'getfd' ( F_GETFD ) , 'setfd' ( F_SETFD ) + * Requiring this module adds FD_CLOEXEC to the constants module, for use with F_SETFD. + * @param arg arg + * @return Returns flags + **/ + export function fcntlSync(fd: number, cmd: string, arg?: number): number; + + /** + * Asynchronous lseek(2). + * @param fd File Descriptor + * @param offset Offset + * @param whence + * Whence can be 0 (SEEK_SET) to set the new position in bytes to offset, 1 (SEEK_CUR) to set the new + * position to the current position plus offset bytes (can be negative), or 2 (SEEK_END) to set to the end + * of the file plus offset bytes (usually negative or zero to seek to the end of the file). + **/ + export function seek(fd: number, offset: number, whence: number, callback: (err: Error, currFilePos: number) => void): void; + + /** + * Synchronous lseek(2). Throws an exception on error. Returns current file position. + * @param fd File Descriptor + * @param offset Offset + * @param whence + * Whence can be 0 (SEEK_SET) to set the new position in bytes to offset, 1 (SEEK_CUR) to set the new + * position to the current position plus offset bytes (can be negative), or 2 (SEEK_END) to set to the end + * of the file plus offset bytes (usually negative or zero to seek to the end of the file). + * @returns Returns current file position. + **/ + export function seekSync(fd: number, offset: number, whence: number): number; + + /** + * Asynchronous utime(2). + * @param path File path + * @param atime + * Arguments atime and mtime are in seconds as for the system call.Note that the number value of Date() is in milliseconds, + * so to use the 'now' value with fs.utime() you would have to divide by 1000 first, e.g. Date.now()/1000 + * Just like for utime(2), the absence of the atime and mtime means 'now'. + * @param mtime + * Arguments atime and mtime are in seconds as for the system call.Note that the number value of Date() is in milliseconds, + * so to use the 'now' value with fs.utime() you would have to divide by 1000 first, e.g. Date.now()/1000 + * Just like for utime(2), the absence of the atime and mtime means 'now'. + **/ + export function utime(path: string, atime: number, mtime: number, callback: (err: Error) => void):void; + + /** + * Synchronous version of utime(). Throws an exception on error. + * @param path File path + * @param atime + * Arguments atime and mtime are in seconds as for the system call.Note that the number value of Date() is in milliseconds, + * so to use the 'now' value with fs.utime() you would have to divide by 1000 first, e.g. Date.now()/1000 + * Just like for utime(2), the absence of the atime and mtime means 'now'. + * @param mtime + * Arguments atime and mtime are in seconds as for the system call.Note that the number value of Date() is in milliseconds, + * so to use the 'now' value with fs.utime() you would have to divide by 1000 first, e.g. Date.now()/1000 + * Just like for utime(2), the absence of the atime and mtime means 'now'. + **/ + export function utimeSync(path: string, atime: number, mtime: number):void; +} From 20305aba6d1c61007cb1d3073fece0a818b99cf0 Mon Sep 17 00:00:00 2001 From: zenorbi Date: Mon, 17 Aug 2015 17:04:24 +0200 Subject: [PATCH 050/345] Added definition for node-apn --- apn/apn-test.ts | 146 +++++++++++++++++++ apn/apn.d.ts | 364 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 510 insertions(+) create mode 100644 apn/apn-test.ts create mode 100644 apn/apn.d.ts diff --git a/apn/apn-test.ts b/apn/apn-test.ts new file mode 100644 index 000000000..a9e2c21a7 --- /dev/null +++ b/apn/apn-test.ts @@ -0,0 +1,146 @@ +/// +import apn = require("apn"); + +//Hand made TypeScript tests +//========================== + +//Create with a hex string +var device1 = new apn.Device("ca11ab1e"); +//Create with a Buffer +var device2 = new apn.Device(new Buffer("ca55e77e")); + +//Create the notification +var notification = new apn.Notification(); +notification.alert = { + title: "The Title", + body: "This is the body", +}; +notification.badge = 5; +//Fluid api +notification.setAlertTitle("The Title") + .setAlertText("This is the body") + .setLaunchImage("LaunchImage"); + +//Establish the connection +var connection = new apn.Connection({ + cert: "path/to/cert.pem", + key: "path/to/cert.pem" +}); +//Testing some specialized event listeners +connection.on("error", (error) => { + console.log("push error", error.name, error.message); +}); +connection.on("transmissionError", (errorCode, notification, device) => { + console.log("push failed", errorCode, "notification", notification.alert, "device id: ", device.toString()); +}); + +//Send it using hex string +connection.pushNotification(notification, "ba5eba11"); +//Send it using Buffer +connection.pushNotification(notification, new Buffer("5ca1ab1e")); +//Send it using Device +connection.pushNotification(notification, device1); + +//Connecting to feedback service +var feedbackService = new apn.Feedback({ + cert: "path/to/cert.pem", + key: "path/to/cert.pem", + interval: 0 +}); +feedbackService.on("error", (error:Error) => { + console.log("push feedback error", error.name, error.message); +}); +function processFeedbackData(device:Buffer, time:number) { +} +feedbackService.on("feedback", (feedbackData) => { + feedbackData.forEach((data) => { + processFeedbackData(data.device, data.time); + }) +}); +feedbackService.start(); + + +//Original examples from apn package +//================================== + +//sending-to-multiple-devices.js +//------------------------------ + +var tokens = ["", ""]; + +if(tokens[0] === "") { + console.log("Please set token to a valid device token for the push notification service"); + process.exit(); +} + +// Create a connection to the service using mostly default parameters. + +var service = new apn.connection({ production: false }); + +service.on("connected", function() { + console.log("Connected"); +}); + +service.on("transmitted", function(notification, device) { + console.log("Notification transmitted to:" + device.token.toString("hex")); +}); + +service.on("transmissionError", function(errCode, notification, device) { + console.error("Notification caused error: " + errCode + " for device ", device, notification); + if (errCode === 8) { + console.log("A error code of 8 indicates that the device token is invalid. This could be for a number of reasons - are you using the correct environment? i.e. Production vs. Sandbox"); + } +}); + +service.on("timeout", function () { + console.log("Connection Timeout"); +}); + +service.on("disconnected", function() { + console.log("Disconnected from APNS"); +}); + +service.on("socketError", console.error); + + +// If you plan on sending identical paylods to many devices you can do something like this. +function pushNotificationToMany() { + console.log("Sending the same notification each of the devices with one call to pushNotification."); + var note = new apn.notification(); + note.setAlertText("Hello, from node-apn!"); + note.badge = 1; + + service.pushNotification(note, tokens); +} + +pushNotificationToMany(); + + +// If you have a list of devices for which you want to send a customised notification you can create one and send it to and individual device. +function pushSomeNotifications() { + console.log("Sending a tailored notification to %d devices", tokens.length); + tokens.forEach(function(token, i) { + var note = new apn.notification(); + note.setAlertText("Hello, from node-apn! You are number: " + i); + note.badge = i; + + service.pushNotification(note, token); + }); +} + +pushSomeNotifications(); + +//feedback.js +//----------- + +function handleFeedback(feedbackData:apn.FeedbackData[]) { + feedbackData.forEach(function(feedbackItem) { + console.log("Device: " + feedbackItem.device.toString("hex") + " has been unreachable, since: " + feedbackItem.time); + }); +} + +// Setup a connection to the feedback service using a custom interval (10 seconds) +var feedback = new apn.feedback({ production: false, interval: 10 }); + +feedback.on("feedback", handleFeedback); +feedback.on("feedbackError", console.error); diff --git a/apn/apn.d.ts b/apn/apn.d.ts new file mode 100644 index 000000000..ed38086ef --- /dev/null +++ b/apn/apn.d.ts @@ -0,0 +1,364 @@ +// Type definitions for node-apn +// Project: https://github.com/argon/node-apn +// Definitions by: Zenorbi +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +declare module "apn" { + import events = require("events"); + import net = require("net"); + export interface ConnectionOptions { + /** + * The filename of the connection certificate to load from disk, or a Buffer/String containing the certificate data. (Defaults to: `cert.pem`) + */ + cert?:string|Buffer; + /** + * The filename of the connection key to load from disk, or a Buffer/String containing the key data. (Defaults to: `key.pem`) + */ + key?:string|Buffer; + /** + * An array of trusted certificates. Each element should contain either a filename to load, or a Buffer/String (in PEM format) to be used directly. If this is omitted several well known "root" CAs will be used. - You may need to use this as some environments don't include the CA used by Apple (entrust_2048). + */ + ca?:(string|Buffer)[]; + /** + * File path for private key, certificate and CA certs in PFX or PKCS12 format, or a Buffer containing the PFX data. If supplied will always be used instead of certificate and key above. + */ + pfx?:string|Buffer; + /** + * The passphrase for the connection key, if required + */ + passphrase?:string; + /** + * Specifies which environment to connect to: Production (if true) or Sandbox - The hostname will be set automatically. (Defaults to NODE_ENV == "production", i.e. false unless the NODE_ENV environment variable is set accordingly) + */ + production?:boolean; + /** + * Enable when you are using a VoIP certificate to enable paylods up to 4096 bytes. + */ + voip?:boolean; + /** + * Gateway port (Defaults to: `2195`) + */ + port?:number; + /** + * Reject Unauthorized property to be passed through to tls.connect() (Defaults to `true`) + */ + rejectUnauthorized?:boolean; + /** + * Number of notifications to cache for error purposes (See "Handling Errors" below, (Defaults to: `1000`) + */ + cacheLength?:number; + /** + * Whether the cache should grow in response to messages being lost after errors. (Will still emit a 'cacheTooSmall' event) (Defaults to: `true`) + */ + autoAdjustCache?:boolean; + /** + * The maximum number of connections to create for sending messages. (Defaults to: `1`) + */ + maxConnections?:number; + /** + * The duration of time the module should wait, in milliseconds, when trying to establish a connection to Apple before failing. 0 = Disabled. {Defaults to: `10000`} + */ + connectTimeout?:number; + /** + * The duration the socket should stay alive with no activity in milliseconds. 0 = Disabled. (Defaults to: `3600000` - 1h) + */ + connectionTimeout?:number; + /** + * The maximum number of connection failures that will be tolerated before `apn` will "terminate". (Defaults to: 10) + */ + connectionRetryLimit?:number; + /** + * Whether to buffer notifications and resend them after failure. (Defaults to: `true`) + */ + buffersNotifications?:number; + /** + * Whether to aggresively empty the notification buffer while connected - if set to true node-apn may enter a tight loop under heavy load while delivering notifications. (Defaults to: `false`) + */ + fastMode?:boolean; + } + export class Connection extends events.EventEmitter { + constructor(options:ConnectionOptions); + /** + * This is the business end of the module. Create a `Notification` object and pass it in, along with a single recipient or an array of them and node-apn will take care of the rest, delivering the notification to each recipient. + * + * A "recipient" is either a `Device` object, a `String`, or a `Buffer` containing the device token. `Device` objects are used internally and will be created if necessary. Where applicable, all events will return a `Device` regardless of the type passed to this method. + */ + pushNotification(notification:Notification, recipient:Device|string|Buffer|(Device|string|Buffer)[]):void; + /** + * Used to manually adjust the "cacheLength" property in the options. This is ideal if you choose to use the `cacheTooSmall` event to tweak your environment. It is safe for increasing and reducing cache size. + */ + setCacheLength(newLength:number):void; + /** + * Indicate to node-apn that when the queue of pending notifications is fully drained that it should close all open connections. This will mean that if there are no other pending resources (open sockets, running timers, etc.) the application will terminate. If notifications are pushed after the connection has completely shutdown a new connection will be established and, if applicable, `shutdown` will need to be called again. + */ + shutdown():void; + /** + * Emitted when an error occurs during initialisation of the module, usually due to a problem with the keys and certificates. + */ + on(event: "error", listener: (error:Error) => void):Connection; + /** + * Emitted when the connection socket experiences an error. This may be useful for debugging but no action should be necessary. + */ + on(event: "socketError", listener: (error:Error) => void):Connection; + /** + * Emitted when a notification has been sent to Apple - not a guarantee that it has been accepted by Apple, an error relating to it may occur later on. A notification may also be "transmitted" several times if a preceding notification caused an error requiring retransmission. + */ + on(event: "transmitted", listener: (notification:Notification, decive:Device) => void):Connection; + /** + * Emitted when all pending notifications have been transmitted to Apple and the pending queue is empty. This may be called more than once if a notification error occurs and notifications must be re-sent. + */ + on(event: "completed", listener: () => void):Connection; + /** + * Emitted when Apple returns a notification as invalid but the notification has already been expunged from the cache - usually due to high throughput and indicates that notifications will be getting lost. The parameter is an estimate of how many notifications have been lost. You should experiment with increasing the cache size or enabling ```autoAdjustCache``` if you see this frequently. + * + * **Note**: With ```autoAdjustCache``` enabled this event will still be emitted when an adjustment is triggered. + */ + on(event: "cacheTooSmall", listener: (sizeDifference:number) => void):Connection; + /** + * Emitted when a connection to Apple is successfully established. The parameter indicates the number of open connections. No action is required as the connection is managed internally. + */ + on(event: "connected", listener: (openSockets:net.Socket[]) => void):Connection; + /** + * Emitted when the connection to Apple has been closed, this could be for numerous reasons, for example an error has occurred or the connection has timed out. The parameter is the same as for `connected` and again, no action is required. + */ + on(event: "disconnected", listener: (openSockets:net.Socket[]) => void):Connection; + /** + * Emitted when the connectionTimeout option has been specified and no activity has occurred on a socket for a specified duration. The socket will be closed immediately after this event and a `disconnected` event will also be emitted. + */ + on(event: "timeout", listener: () => void):Connection; + /** + * Emitted when a message has been received from Apple stating that a notification was invalid or if an internal error occurred before that notification could be pushed to Apple. If the notification is still in the cache it will be passed as the second argument, otherwise null. Where possible the associated `Device` object will be passed as a third parameter, however in cases where the token supplied to the module cannot be parsed into a `Buffer` the supplied value will be returned. + + * Error codes smaller than 512 correspond to those returned by Apple as per their [docs][errors]. Other errors are applicable to `node-apn` itself. Definitions can be found in `lib/errors.js`. + */ + on(event: "transmissionError", listener: (errorCode:number, notification:Notification, device:Device|Buffer) => void):Connection; + on(event: string, listener: Function):Connection; + } + export interface NotificationAlertOptions { + title?:string; + body:string; + "title-loc-key"?:string; + "title-loc-args"?:string[]; + "action-loc-key"?:string; + "loc-key"?:string; + "loc-args"?:string[]; + "launch-image"?:string; + } + export class Notification { + /** + * The maximum number of retries which should be performed when sending a notification if an error occurs. A value of 0 will only allow one attempt at sending (0 retries). Set to -1 to disable (default). + */ + public retryLimit:number; + /** + * The UNIX timestamp representing when the notification should expire. This does not contribute to the 2048 byte payload size limit. An expiry of 0 indicates that the notification expires immediately. + */ + public expiry:number; + /** + * From Apple's Documentation, Provide one of the following values: + * + * - 10 - The push message is sent immediately. (Default) + * > The push notification must trigger an alert, sound, or badge on the device. It is an error use this priority for a push that contains only the content-available key. + * - 5 - The push message is sent at a time that conserves power on the device receiving it. + */ + public priority:number; + /** + * The encoding to use when transmitting the notification to APNS, defaults to `utf8`. `utf16le` is also possible but as each character is represented by a minimum of 2 bytes, will at least halve the possible payload size. If in doubt leave as default. + */ + public encoding:string; + /** + * This object represents the root JSON object that you can add custom information for your application to. The properties below will only be added to the payload (under `aps`) when the notification is prepared for sending. + */ + public payload:any; + /** + * The value to specify for `payload.aps.badge` + */ + public badge:number; + /** + * The value to specify for `payload.aps.sound` + */ + public sound:string; + /** + * The value to specify for `payload.aps.alert` can be either a `String` or an `Object` as outlined by the payload documentation. + */ + public alert:string|NotificationAlertOptions; + /** + * Setting this to true will specify "content-available" in the payload when it is compiled. + */ + public newsstandAvailable:boolean; + /** + * Setting this to true will specify "content-available" in the payload when it is compiled. + */ + public contentAvailable:boolean; + /** + * The value to specify for the `mdm` field where applicable. + */ + public mdm:string|Object; + /** + * The value to specify for `payload.aps['url-args']`. This used for Safari Push NOtifications and should be an array of values in accordance with the Web Payload Documentation. + */ + public urlArgs:string[]; + /** + * When this parameter is set and `notification#trim()` is called it will attempt to truncate the string at the nearest space. + */ + public truncateAtWordEnd:boolean; + /** + * You can optionally pass in an object representing the payload, or configure properties on the returned object. + */ + constructor(payload?:any); + /** + * Set the `aps.alert` text body. This will use the most space-efficient means. + */ + setAlertText(alertText:string):Notification; + /** + * Set the `title` property of the `aps.alert` object - used with Safari Push Notifications + */ + setAlertTitle(alertTitle:string):Notification; + /** + * Set the `action` property of the `aps.alert` object - used with Safari Push Notifications + */ + setAlertAction(alertAction:string):Notification; + /** + * Set the `action-loc-key` property of the `aps.alert` object. + */ + setActionLocKey(key:string):Notification; + /** + * Set the `loc-key` property of the `aps.alert` object. + */ + setLocKey(key:string):Notification; + /** + * Set the `loc-args` property of the `aps.alert` object. + */ + setLocArgs(args:string[]):Notification; + /** + * Set the `launch-image` property of the `aps.alert` object. + */ + setLaunchImage(image:string):Notification; + /** + * Set the `mdm` property on the payload. + */ + setMDM(mdm:string|Object):Notification; + /** + * Set the `content-available` property of the `aps` object. + */ + setNewsstandAvailable(available:boolean):Notification; + /** + * Set the `content-available` property of the `aps` object. + */ + setContentAvailable(available:boolean):Notification; + /** + * Set the `url-args` property of the `aps` object. + */ + setUrlArgs(urlArgs:string[]):Notification; + /** + * Attempt to automatically trim the notification alert text body to meet the payload size limit of 2048 bytes. + */ + trim():number; + } + export class Device { + public token:Buffer; + /** + * `deviceToken` can be a `Buffer` or a `String` containing a "hex" representation of the token. Throws an error if the deviceToken supplied is invalid. + */ + constructor(deviceToken:string|Buffer); + } + + export interface FeedbackOptions { + /** + * The filename of the connection certificate to load from disk, or a Buffer/String containing the certificate data. (Defaults to: `cert.pem`) + */ + cert?:string|Buffer; + /** + * The filename of the connection key to load from disk, or a Buffer/String containing the key data. (Defaults to: `key.pem`) + */ + key?:string|Buffer; + /** + * An array of trusted certificates. Each element should contain either a filename to load, or a Buffer/String (in PEM format) to be used directly. If this is omitted several well known "root" CAs will be used. - You may need to use this as some environments don't include the CA used by Apple (entrust_2048). + */ + ca?:(string|Buffer)[]; + /** + * File path for private key, certificate and CA certs in PFX or PKCS12 format, or a Buffer containing the PFX data. If supplied will be used instead of certificate and key above. + */ + pfx?:string|Buffer; + /** + * The passphrase for the connection key, if required + */ + passphrase?:string; + /** + * Specifies which environment to connect to: Production (if true) or Sandbox - The hostname will be set automatically. (Defaults to NODE_ENV == "production", i.e. false unless the NODE_ENV environment variable is set accordingly) + */ + production?:boolean; + /** + * Feedback server port (Defaults to: `2196`) + */ + port?:number; + /** + * Sets the behaviour for triggering the `feedback` event. When `true` the event will be triggered once per connection with an array of timestamp and device token tuples. Otherwise a `feedback` event will be emitted once per token received. (Defaults to: true) + */ + batchFeedback?:boolean; + /** + * The maximum number of tokens to pass when emitting the event - a value of 0 will cause all tokens to be passed after connection is reset. After this number of tokens are received the `feedback` event will be emitted. (Only applies when `batchFeedback` is enabled) + */ + batchSize?:number; + /** + * How often to automatically poll the feedback service. Set to `0` to disable. (Defaults to: `3600`) + */ + interval?:number; + } + export interface FeedbackData { + time:number; + device:Buffer; + } + /** + * Connection to the Apple Push Notification Feedback Service and if `interval` isn't disabled automatically begins polling the service. Many of the options are the same as `apn.Connection()` + */ + export class Feedback { + constructor(options:FeedbackOptions); + /** + * Trigger a query of the feedback service. If `interval` is non-zero then this method will be called automatically. + */ + start():void; + /** + * You can cancel the interval by calling `feedback.cancel()`. If you do not wish to have the service automatically queried then set `interval` to 0 and use `feedback.start()` to manually invoke it one time. + */ + cancel():void; + /** + * Emitted when an error occurs initialising the module. Usually caused by failing to load the certificates. + */ + on(event: "error", listener: (error:Error) => void):Feedback; + /** + * Emitted when an error occurs receiving or processing the feedback and in the case of a socket error occurring. These errors are usually informational and node-apn will automatically recover. + */ + on(event: "feedbackError", listener: (error:Error) => void):Feedback; + /** + * Emitted when data has been received from the feedback service, typically once per connection. `feedbackData` is an array of objects, each containing the `time` returned by the server (epoch time) and the `device` a `Buffer` containing the device token. + */ + on(event: "feedback", listener: (feedbackData:FeedbackData[]) => void):Feedback; + on(event: string, listener: Function):Feedback; + } + + export enum Errors { + "noErrorsEncountered"= 0, + "processingError"= 1, + "missingDeviceToken"= 2, + "missingTopic"= 3, + "missingPayload"= 4, + "invalidTokenSize"= 5, + "invalidTopicSize"= 6, + "invalidPayloadSize"= 7, + "invalidToken"= 8, + "apnsShutdown"= 10, + "none"= 255, + "retryLimitExceeded"= 512, + "moduleInitialisationFailed"= 513, + "connectionRetryLimitExceeded"= 514, // When a connection is unable to be established. Usually because of a network / SSL error this will be emitted + "connectionTerminated"= 515 + } + + //Lowercase aliases + export {Connection as connection}; + export {Device as device}; + export {Errors as error}; + export {Feedback as feedback}; + export {Notification as notification}; +} From 9732f123672c2d2a6f6cda9a10c5e5c3c7c3dbab Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 17 Aug 2015 11:43:17 -0400 Subject: [PATCH 051/345] Fixing typo in ui-grid definition. "notifiyDataChange" should be "notifyDataChange" --- ui-grid/ui-grid.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ui-grid/ui-grid.d.ts b/ui-grid/ui-grid.d.ts index 981f363b2..9dbb6dac9 100644 --- a/ui-grid/ui-grid.d.ts +++ b/ui-grid/ui-grid.d.ts @@ -248,7 +248,7 @@ declare module uiGrid { clearRowInvisible(rowEntity: any): void; getVisibleRows(grid: IGridInstance): Array; handleWindowResize(): void; - notifiyDataChange(type: string): void; + notifyDataChange(type: string): void; refreshRows(): ng.IPromise; registerColumnsProcessor(processorFunction: IColumnProcessor, priority: number): void; registerRowsProcessor(rowProcessor: IRowProcessor, priority: number): void; From ad3abeb456a9b299278e91cedda4f4d5f8c4818a Mon Sep 17 00:00:00 2001 From: benishouga Date: Tue, 18 Aug 2015 01:09:15 +0900 Subject: [PATCH 052/345] Support the string for the second argument of Router.run. --- react-router/react-router-test.ts | 14 ++++++++++---- react-router/react-router.d.ts | 1 + 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/react-router/react-router-test.ts b/react-router/react-router-test.ts index 62180a258..115c8b77f 100644 --- a/react-router/react-router-test.ts +++ b/react-router/react-router-test.ts @@ -312,12 +312,18 @@ class RunTest { var v2: Router.Router = Router.run(React.createElement(Router.Route, null), Router.HistoryLocation, (Handler, state) => { React.render(React.createElement(Handler, null), document.body); }); - - // React.createFactory() version - var v3: Router.Router = Router.run(React.createFactory(Router.Route)(), (Handler) => { + var v3: Router.Router = Router.run(React.createElement(Router.Route, null), '/foo/bar', (Handler, state) => { React.render(React.createElement(Handler, null), document.body); }); - var v4: Router.Router = Router.run(React.createFactory(Router.Route)(), Router.HistoryLocation, (Handler, state) => { + + // React.createFactory() version + var v4: Router.Router = Router.run(React.createFactory(Router.Route)(), (Handler) => { + React.render(React.createElement(Handler, null), document.body); + }); + var v5: Router.Router = Router.run(React.createFactory(Router.Route)(), Router.HistoryLocation, (Handler, state) => { + React.render(React.createElement(Handler, null), document.body); + }); + var v6: Router.Router = Router.run(React.createFactory(Router.Route)(), '/foo/bar', (Handler, state) => { React.render(React.createElement(Handler, null), document.body); }); } diff --git a/react-router/react-router.d.ts b/react-router/react-router.d.ts index d8dd12c97..51664b03a 100644 --- a/react-router/react-router.d.ts +++ b/react-router/react-router.d.ts @@ -175,6 +175,7 @@ declare module ReactRouter { function create(options: RouterCreateOption): Router; function run(routes: Route, callback: RouterRunCallback): Router; function run(routes: Route, location: LocationBase, callback: RouterRunCallback): Router; + function run(routes: Route, location: string, callback: RouterRunCallback): Router; // From 232240bea530fe0ca1f427fab81d46d7b6f7eca9 Mon Sep 17 00:00:00 2001 From: Adam Babcock Date: Mon, 17 Aug 2015 11:25:39 -0500 Subject: [PATCH 053/345] Support for request-ip --- request-ip/request-ip-tests.ts | 10 ++++++++++ request-ip/request-ip.d.ts | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 request-ip/request-ip-tests.ts create mode 100644 request-ip/request-ip.d.ts diff --git a/request-ip/request-ip-tests.ts b/request-ip/request-ip-tests.ts new file mode 100644 index 000000000..8c5111e33 --- /dev/null +++ b/request-ip/request-ip-tests.ts @@ -0,0 +1,10 @@ +/// +/// + +import express = require('express'); +import requestIp = require('request-ip'); + +var ipMiddleware = function(req:express.Request, res:express.Response, next:Function) { + var clientIp = requestIp.getClientIp(req); + next(); +}; diff --git a/request-ip/request-ip.d.ts b/request-ip/request-ip.d.ts new file mode 100644 index 000000000..e71ed1a37 --- /dev/null +++ b/request-ip/request-ip.d.ts @@ -0,0 +1,32 @@ +// Type definitions for request-ip +// Project: https://github.com/pbojinov/request-ip +// Definitions by: Adam Babcock +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "request-ip" { + interface Request { + headers: { + 'x-client-ip'?: string; + 'x-forwarded-for'?: string; + 'x-real-ip'?: string; + 'x-cluster-client-ip'?: string; + 'x-forwarded'?: string; + 'forwarded-for'?: string; + 'forwarded'?: string; + }; + connection: { + remoteAddress?: string; + socket?: { + remoteAddress?: string + }; + }; + info?: { + remoteAddress?: string + }; + socket?: { + remoteAddress?: string + }; + } + + export function getClientIp(req:Request):string; +} From 14394df1810b7899ae4b7c843dfbd326e9230529 Mon Sep 17 00:00:00 2001 From: Felipe Barriga Richards Date: Mon, 17 Aug 2015 14:50:12 -0300 Subject: [PATCH 054/345] lodash: Fix _.has and _.result --- lodash/lodash-tests.ts | 6 ++++++ lodash/lodash.d.ts | 21 +++++++++++---------- 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 2cbec6853..4e741f5dc 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1571,6 +1571,10 @@ result = _(any).noop(true, 'a', 1); var object = { 'cheese': 'crumpets', + 'one': 1, + 'nested': { + 'two': 2 + }, 'stuff': function () { return 'nonsense'; } @@ -1578,6 +1582,8 @@ var object = { result = _.result(object, 'cheese'); result = _.result(object, 'stuff'); +result = _.result(object, 'one'); +result = _.result(object, ['nested', 'two'] ); var tempObject = {}; result = _.runInContext(tempObject); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index c088f5459..7fd62eb4b 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -6810,13 +6810,12 @@ declare module _ { //_.has interface LoDashStatic { /** - * Checks if the specified object property exists and is a direct property, instead of an - * inherited property. - * @param object The object to check. - * @param property The property to check for. - * @return True if key is a direct property, else false. + * Checks if path is a direct property. + * @param object The object to query. + * @param path The path to check. + * @return True if path is a direct property, else False. **/ - has(object: any, property: string): boolean; + has(object: any, path: string|string[]): boolean; } //_.invert @@ -7822,12 +7821,14 @@ declare module _ { /** * Resolves the value of property on object. If property is a function it will be invoked with * the this binding of object and its result returned, else the property value is returned. If - * object is falsey then undefined is returned. - * @param object The object to inspect. - * @param property The property to get the value of. + * object is false then undefined is returned. + * @param object The object to query. + * @param path The path of the property to resolve. + * @param defaultValue The value returned if the resolved value is undefined. * @return The resolved value. **/ - result(object: any, property: string): any; + + result(object: any, path: string|string[], defaultValue?: T): T; } //_.runInContext From 5fb2a9fe67a2b50f1c928e05351b02abcd54b098 Mon Sep 17 00:00:00 2001 From: Felipe Barriga Richards Date: Mon, 17 Aug 2015 15:21:37 -0300 Subject: [PATCH 055/345] lodash: fix pull, remove, fill, pluck --- lodash/lodash-tests.ts | 1 + lodash/lodash.d.ts | 62 +++++++++++++++++++++--------------------- 2 files changed, 32 insertions(+), 31 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 2cbec6853..34080d18d 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -639,6 +639,7 @@ result = _(stoogesAgesDict).sum('age'); result = _.pluck(stoogesAges, 'name'); result = _(stoogesAges).pluck('name').value(); +result = _.pluck(stoogesAges, ['name']); // _.partition result = _.partition('abcd', (n) => n < 'c'); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index c088f5459..97c02f4b4 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -1092,16 +1092,16 @@ declare module _ { * @param values The values to remove. * @return array. **/ - pull( - array: Array, - ...values: any[]): any[]; + pull( + array: Array, + ...values: T[]): T[]; /** * @see _.pull **/ - pull( - array: List, - ...values: any[]): any[]; + pull( + array: List, + ...values: T[]): T[]; } interface LoDashStatic { @@ -1141,50 +1141,50 @@ declare module _ { * @param thisArg The this binding of callback. * @return A new array of removed elements. **/ - remove( - array: Array, - callback?: ListIterator, - thisArg?: any): any[]; + remove( + array: Array, + callback?: ListIterator, + thisArg?: any): T[]; /** * @see _.remove **/ - remove( - array: List, - callback?: ListIterator, - thisArg?: any): any[]; + remove( + array: List, + callback?: ListIterator, + thisArg?: any): T[]; /** * @see _.remove * @param pluckValue _.pluck style callback **/ - remove( - array: Array, - pluckValue?: string): any[]; + remove( + array: Array, + pluckValue?: string): T[]; /** * @see _.remove * @param pluckValue _.pluck style callback **/ - remove( - array: List, - pluckValue?: string): any[]; + remove( + array: List, + pluckValue?: string): T[]; /** * @see _.remove * @param whereValue _.where style callback **/ - remove( - array: Array, - wherealue?: Dictionary): any[]; + remove( + array: Array, + wherealue?: Dictionary): T[]; /** * @see _.remove * @param whereValue _.where style callback **/ - remove( - array: List, - wherealue?: Dictionary): any[]; + remove( + array: List, + wherealue?: Dictionary): T[]; /** * @see _.remove @@ -2494,7 +2494,7 @@ declare module _ { * @see _.fill */ fill( - value: any, + value: TResult, start?: number, end?: number): LoDashArrayWrapper; } @@ -2504,7 +2504,7 @@ declare module _ { * @see _.fill */ fill( - value: any, + value: TResult, start?: number, end?: number): LoDashObjectWrapper>; } @@ -4069,21 +4069,21 @@ declare module _ { **/ pluck( collection: Array, - property: string): any[]; + property: string|string[]): any[]; /** * @see _.pluck **/ pluck( collection: List, - property: string): any[]; + property: string|string[]): any[]; /** * @see _.pluck **/ pluck( collection: Dictionary, - property: string): any[]; + property: string|string[]): any[]; } interface LoDashArrayWrapper { From 4d0f988e3c906e7a66bbd79dc11443c533038cb5 Mon Sep 17 00:00:00 2001 From: Joe Skeen Date: Mon, 17 Aug 2015 13:27:17 -0600 Subject: [PATCH 056/345] Definitions for gulp-sort --- gulp-sort/gulp-sort-tests.ts | 49 ++++++++++++++++++++++++++++++++++++ gulp-sort/gulp-sort.d.ts | 44 ++++++++++++++++++++++++++++++++ 2 files changed, 93 insertions(+) create mode 100644 gulp-sort/gulp-sort-tests.ts create mode 100644 gulp-sort/gulp-sort.d.ts diff --git a/gulp-sort/gulp-sort-tests.ts b/gulp-sort/gulp-sort-tests.ts new file mode 100644 index 000000000..0dd260f66 --- /dev/null +++ b/gulp-sort/gulp-sort-tests.ts @@ -0,0 +1,49 @@ +/** Tests taken from https://github.com/pgilad/gulp-sort#usage */ +/// +/// +/// + +import gulp = require('gulp'); +import sort = require('gulp-sort'); + +// default sort +gulp.src('./src/js/**/*.js') + .pipe(sort()) + .pipe(gulp.dest('./build/js')); + +// pass in a custom comparator function +gulp.src('./src/js/**/*.js') + .pipe(sort(customComparator)) + .pipe(gulp.dest('./build/js')); + +// sort descending +gulp.src('./src/js/**/*.js') + .pipe(sort({ + asc: false + })) + .pipe(gulp.dest('./build/js')); + +// sort with a custom comparator +gulp.src('./src/js/**/*.js') + .pipe(sort({ + comparator: function(file1, file2) { + if (file1.path.indexOf('build') > -1) { + return 1; + } + if (file2.path.indexOf('build') > -1) { + return -1; + } + return 0; + } + })) + .pipe(gulp.dest('./build/js')); + +function customComparator(file1, file2) { + if (file1.path.indexOf('build') > -1) { + return 1; + } + if (file2.path.indexOf('build') > -1) { + return -1; + } + return 0; +} \ No newline at end of file diff --git a/gulp-sort/gulp-sort.d.ts b/gulp-sort/gulp-sort.d.ts new file mode 100644 index 000000000..7289c1f51 --- /dev/null +++ b/gulp-sort/gulp-sort.d.ts @@ -0,0 +1,44 @@ +// Type definitions for gulp-sort +// Project: https://github.com/pgilad/gulp-sort +// Definitions by: Joe Skeen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +/** Sort files in stream by path or any custom sort comparator */ +declare module 'gulp-sort' { + + import gulpUtil = require('gulp-util'); + + interface IOptions { + /** + * A function to compare two files. + * Returns: + * -1 if file1 should be before file2, + * 0 if file1 is equivalent to file2, and + * 1 if file1 should be after file2 + */ + comparator?: IComparatorFunction; + /** Whether to sort in ascending order, default is true */ + asc?; + } + + interface IComparatorFunction { + /** + * A function to compare two files. + * Returns: + * -1 if file1 should be before file2, + * 0 if file1 is equivalent to file2, and + * 1 if file1 should be after file2 + */ + (file1: gulpUtil.File, file2: gulpUtil.File): number; + } + + /** Sort files in stream by path or any custom sort comparator */ + function gulpSort(): NodeJS.ReadWriteStream; + function gulpSort(comparator: IComparatorFunction): NodeJS.ReadWriteStream; + function gulpSort(options: IOptions): NodeJS.ReadWriteStream; + + export = gulpSort; +} From 64cfad5c09adff9a47d004d7b9c7aad23be86c83 Mon Sep 17 00:00:00 2001 From: Joe Skeen Date: Mon, 17 Aug 2015 13:31:19 -0600 Subject: [PATCH 057/345] Fix implicit any issues --- gulp-sort/gulp-sort-tests.ts | 3 ++- gulp-sort/gulp-sort.d.ts | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/gulp-sort/gulp-sort-tests.ts b/gulp-sort/gulp-sort-tests.ts index 0dd260f66..12685c085 100644 --- a/gulp-sort/gulp-sort-tests.ts +++ b/gulp-sort/gulp-sort-tests.ts @@ -5,6 +5,7 @@ import gulp = require('gulp'); import sort = require('gulp-sort'); +import gulpUtil = require('gulp-util'); // default sort gulp.src('./src/js/**/*.js') @@ -38,7 +39,7 @@ gulp.src('./src/js/**/*.js') })) .pipe(gulp.dest('./build/js')); -function customComparator(file1, file2) { +function customComparator(file1: gulpUtil.File, file2: gulpUtil.File) { if (file1.path.indexOf('build') > -1) { return 1; } diff --git a/gulp-sort/gulp-sort.d.ts b/gulp-sort/gulp-sort.d.ts index 7289c1f51..c06b9c3e0 100644 --- a/gulp-sort/gulp-sort.d.ts +++ b/gulp-sort/gulp-sort.d.ts @@ -21,7 +21,7 @@ declare module 'gulp-sort' { */ comparator?: IComparatorFunction; /** Whether to sort in ascending order, default is true */ - asc?; + asc?: boolean; } interface IComparatorFunction { From b8d40ffd99a3c4acc584c88ee51c3f5656d921ec Mon Sep 17 00:00:00 2001 From: psnider Date: Mon, 17 Aug 2015 20:27:44 +0000 Subject: [PATCH 058/345] add decls for mailparser --- mailparser/mailparser-tests.ts | 69 +++++++++++++++++++++++++++ mailparser/mailparser.d.ts | 86 ++++++++++++++++++++++++++++++++++ 2 files changed, 155 insertions(+) create mode 100644 mailparser/mailparser-tests.ts create mode 100644 mailparser/mailparser.d.ts diff --git a/mailparser/mailparser-tests.ts b/mailparser/mailparser-tests.ts new file mode 100644 index 000000000..51d562788 --- /dev/null +++ b/mailparser/mailparser-tests.ts @@ -0,0 +1,69 @@ +import mailparser_mod = require("mailparser"); +import MailParser = mailparser_mod.MailParser; +import ParsedMail = mailparser_mod.ParsedMail; + + + +var mailparser = new MailParser(); + + +mailparser.on("headers", function(headers){ + console.log(headers.received); +}); + +mailparser.on("end", function(mail){ + mail; // object structure for parsed e-mail +}); + + +// Decode a simple e-mail +// This example decodes an e-mail from a string + +var email = "From: 'Sender Name' \r\n"+ + "To: 'Receiver Name' \r\n"+ + "Subject: Hello world!\r\n"+ + "\r\n"+ + "How are you today?"; + // setup an event listener when the parsing finishes +mailparser.on("end", function(mail_object){ + console.log("From:", mail_object.from); //[{address:'sender@example.com',name:'Sender Name'}] + console.log("Subject:", mail_object.subject); // Hello world! + console.log("Text body:", mail_object.text); // How are you today? +}); + // send the email source to the parser +mailparser.write(email); +mailparser.end(); + + +// Pipe file to MailParser +// This example pipes a readableStream file to MailParser +mailparser = new MailParser(); +import fs = require("fs"); +mailparser.on("end", function(mail_object){ + console.log("Subject:", mail_object.subject); +}); + +fs.createReadStream("email.eml").pipe(mailparser); + + +// Attachments +mailparser.on("end", function(mail_object : ParsedMail){ + mail_object.attachments.forEach(function(attachment){ + console.log(attachment.fileName); + }); +}); + + +// Attachment streaming +var mp = new MailParser({ + streamAttachments: true +}) + +mp.on("attachment", function(attachment, mail){ + var output = fs.createWriteStream(attachment.generatedFileName); + attachment.stream.pipe(output); +}); + + + + diff --git a/mailparser/mailparser.d.ts b/mailparser/mailparser.d.ts new file mode 100644 index 000000000..9e67cc78a --- /dev/null +++ b/mailparser/mailparser.d.ts @@ -0,0 +1,86 @@ +// Type definitions for mailparser v0.5.2 +// Project: https://www.npmjs.com/package/mailparser +// Definitions by: Peter Snider +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +/// + + +declare module 'mailparser' { + import WritableStream = NodeJS.WritableStream; + import EventEmitter = NodeJS.EventEmitter; + + interface Options { + debug?: boolean; // if set to true print all incoming lines to console + streamAttachments?: boolean; // if set to true, stream attachments instead of including them + unescapeSMTP?: boolean; // if set to true replace double dots in the beginning of the file + defaultCharset?: string; // the default charset for text/plain and text/html content, if not set reverts to Latin-1 + showAttachmentLinks?: boolean; // if set to true, show inlined attachment links filename + } + + + interface EmailAddress { + address: string; + name: string; + } + + + interface Attachment { + contentType: string; + fileName: string; + contentDisposition: string; // e.g. 'attachment' + contentId: string; // e.g. '5.1321281380971@localhost' + transferEncoding: string; // e.g. 'base64' + length: number; // length of the attachment in bytes + generatedFileName: string; // e.g. 'image.png' + checksum: string; // the md5 hash of the file, e.g. 'e4cef4c6e26037bcf8166905207ea09b' + content: Buffer; // possibly a SlowBuffer + } + + // emitted with the 'end' event + interface ParsedMail { + headers: any; // unprocessed headers in the form of - {key: value} - if there were multiple fields with the same key then the value is an array + from: EmailAddress[]; // should be only one though) + to: EmailAddress[]; + cc?: EmailAddress[]; + bcc?: EmailAddress[]; + subject: string; // the subject line + references?: string[]; // an array of reference message id values (not set if no reference values present) + inReplyTo?: string[]; // an array of In-Reply-To message id values (not set if no in-reply-to values present) + priority?: string; // priority of the e-mail, always one of the following: normal (default), high, low + text: string; // text body + html: string; // html body + date?: Date; // If date could not be resolved or is not found this field is not set. Check the original date string from headers.date + attachments?: Attachment[]; + } + + + + class MailParser implements WritableStream { + constructor(options? : Options); + on(event : string, callback : (any : any) => void) : void; + + // from WritableStream + writable: boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: 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; + + // from EventEmitter + static listenerCount(emitter: EventEmitter, event: string): number; + addListener(event: string, listener: Function): EventEmitter; + on(event: string, listener: Function): EventEmitter; + once(event: string, listener: Function): EventEmitter; + removeListener(event: string, listener: Function): EventEmitter; + removeAllListeners(event?: string): EventEmitter; + setMaxListeners(n: number): void; + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + } +} + From 9f02d024a6938f9cacb17ced718d818775656645 Mon Sep 17 00:00:00 2001 From: Raphael ATALLAH Date: Mon, 17 Aug 2015 15:54:05 -0700 Subject: [PATCH 059/345] Updated typescript definitions for angular-odata-resources. Added support for $select --- .../angular-odata-resources-tests.ts | 9 +++++++++ .../angular-odata-resources.d.ts | 13 ++++++++----- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/angular-odata-resources/angular-odata-resources-tests.ts b/angular-odata-resources/angular-odata-resources-tests.ts index 5b8dbcc52..23286adc0 100644 --- a/angular-odata-resources/angular-odata-resources-tests.ts +++ b/angular-odata-resources/angular-odata-resources-tests.ts @@ -197,3 +197,12 @@ users = odataResourceClass.odata() var countResult = odataResourceClass.odata().count(); var total = countResult.result; + + + +var usersSelect1 = odataResourceClass.odata() + .select('name', 'user'); + + +var usersSelect2 = odataResourceClass.odata() + .select(['name', 'user']); \ No newline at end of file diff --git a/angular-odata-resources/angular-odata-resources.d.ts b/angular-odata-resources/angular-odata-resources.d.ts index 0a83df2c3..fb6fa5b81 100644 --- a/angular-odata-resources/angular-odata-resources.d.ts +++ b/angular-odata-resources/angular-odata-resources.d.ts @@ -278,14 +278,17 @@ declare module OData { private expandables; constructor(callback: ProviderCallback); filter(operand1: any, operand2?: any, operand3?: any): Provider; - orderBy(arg1: any, arg2?: any): Provider; + orderBy(arg1: string, arg2?: string): Provider; take(amount: number): Provider; skip(amount: number): Provider; private execute(); - query(success?: any, error?: any): T[]; - single(success?: any, error?: any): T; - get(data: any, success?: any, error?: any): T; - expand(params: any, otherParam1?: any, otherParam2?: any, otherParam3?: any, otherParam4?: any, otherParam5?: any, otherParam6?: any, otherParam7?: any): Provider; + query(success?: ((p:T)=>void), error?: (()=>void)): T[]; + single(success?: ((p:T)=>void), error?: (()=>void)): T; + get(key: any, success?: ((p:T)=>void), error?: (()=>void)): T; + expand(...params: string[]): Provider; + expand(params: string[]): Provider; + select(...params: string[]): Provider; + select(params: string[]): Provider; count(success?: (result: ICountResult) => any, error?: () => any):ICountResult; withInlineCount(): Provider; } From e99ef514ee0989bb5ce126e43dffd52b15df0be8 Mon Sep 17 00:00:00 2001 From: Raphael ATALLAH Date: Mon, 17 Aug 2015 16:06:16 -0700 Subject: [PATCH 060/345] Fixed return type for query method --- angular-odata-resources/angular-odata-resources.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/angular-odata-resources/angular-odata-resources.d.ts b/angular-odata-resources/angular-odata-resources.d.ts index fb6fa5b81..f0619deed 100644 --- a/angular-odata-resources/angular-odata-resources.d.ts +++ b/angular-odata-resources/angular-odata-resources.d.ts @@ -282,7 +282,7 @@ declare module OData { take(amount: number): Provider; skip(amount: number): Provider; private execute(); - query(success?: ((p:T)=>void), error?: (()=>void)): T[]; + query(success?: ((p:T[])=>void), error?: (()=>void)): T[]; single(success?: ((p:T)=>void), error?: (()=>void)): T; get(key: any, success?: ((p:T)=>void), error?: (()=>void)): T; expand(...params: string[]): Provider; From fdb0de3a61d9a15fe60c33af92dbcbb792d60b48 Mon Sep 17 00:00:00 2001 From: Raphael ATALLAH Date: Mon, 17 Aug 2015 16:09:18 -0700 Subject: [PATCH 061/345] angular-odata-resources: added $promise property on the return type of count --- angular-odata-resources/angular-odata-resources.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/angular-odata-resources/angular-odata-resources.d.ts b/angular-odata-resources/angular-odata-resources.d.ts index f0619deed..7c625d40c 100644 --- a/angular-odata-resources/angular-odata-resources.d.ts +++ b/angular-odata-resources/angular-odata-resources.d.ts @@ -267,6 +267,7 @@ declare module OData { interface ICountResult{ result: number; + $promise: angular.IPromise; } class Provider { From 12d453946f096a52f48327d7744f5404eaf94877 Mon Sep 17 00:00:00 2001 From: Michael Randolph Date: Mon, 17 Aug 2015 19:31:51 -0400 Subject: [PATCH 062/345] node-jsfl-runner typings --- node-jsfl-runner/node-jsfl-runner-tests.ts | 21 +++++++++++++ node-jsfl-runner/node-jsfl-runner.d.ts | 35 ++++++++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 node-jsfl-runner/node-jsfl-runner-tests.ts create mode 100644 node-jsfl-runner/node-jsfl-runner.d.ts diff --git a/node-jsfl-runner/node-jsfl-runner-tests.ts b/node-jsfl-runner/node-jsfl-runner-tests.ts new file mode 100644 index 000000000..f92f4bfde --- /dev/null +++ b/node-jsfl-runner/node-jsfl-runner-tests.ts @@ -0,0 +1,21 @@ +/// + +import * as jsfl from 'node-jsfl-runner'; + +let myJSFL: jsfl.JSFL = { + init: (param: string): void => { + + } +} + +jsfl.createJSFL(myJSFL, 'fileName.jsfl', ['Hello!'], (err: NodeJS.ErrnoException) => { + +}); + +jsfl.runJSFL('fileName.jsfl', (err: NodeJS.ErrnoException) => { + +}); + +jsfl.deleteJSFL('fileName.jsfl', (err: NodeJS.ErrnoException) => { + +}); \ No newline at end of file diff --git a/node-jsfl-runner/node-jsfl-runner.d.ts b/node-jsfl-runner/node-jsfl-runner.d.ts new file mode 100644 index 000000000..b3f0a8688 --- /dev/null +++ b/node-jsfl-runner/node-jsfl-runner.d.ts @@ -0,0 +1,35 @@ +// Type definitions for node-jsfl-runner +// Project: https://www.npmjs.com/package/node-jsfl-runner +// Definitions by: Michael Randolph +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +declare module "node-jsfl-runner" { + interface JSFL { + init: (...args: any[]) => void; + [index: string]: any; + } + + /** + * Creates a JSFL file from a JSFL object + * @param jsfl A valid JSFL object + * @param fileName Path to output JSFL file location + * @param initParams Parameters to pass to JSFL init function + * @param callback Callback + */ + function createJSFL(jsfl: JSFL, fileName: string, initParams: Array, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Deletes a JSFL file + * @param fileName Path to JSFL file to delete + * @param callback Callback + */ + function deleteJSFL(fileName: string, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Runs a JSFL file + * @param fileName Path to JSFL file to run + * @param callback Callback + */ + function runJSFL(fileName: string, callback: (err: NodeJS.ErrnoException) => void): void; +} \ No newline at end of file From 245a296826db9afbe62f7b65851124585df61b9f Mon Sep 17 00:00:00 2001 From: Tim Perry Date: Tue, 11 Aug 2015 16:40:38 +0100 Subject: [PATCH 063/345] Make concat types support its full auto-flattening API --- lodash/lodash-tests.ts | 1 + lodash/lodash.d.ts | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 2cbec6853..22ff04e8b 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -123,6 +123,7 @@ result = <_.LoDashObjectWrapper<_.Dictionary>>_(<{ [index: string]: stri //Wrapped array shortcut methods result = <_.LoDashArrayWrapper>_([1, 2, 3, 4]).concat(5, 6); +result = <_.LoDashArrayWrapper>_([1, 2, 3, 4]).concat([5, 6]); result = _([1, 2, 3, 4]).join(','); result = _([1, 2, 3, 4]).pop(); result = <_.LoDashArrayWrapper>_([1, 2, 3, 4]).push(5, 6, 7); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index c088f5459..932146a3b 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -252,7 +252,7 @@ declare module _ { interface LoDashObjectWrapper extends LoDashWrapperBase> { } interface LoDashArrayWrapper extends LoDashWrapperBase> { - concat(...items: T[]): LoDashArrayWrapper; + concat(...items: Array>): LoDashArrayWrapper; join(seperator?: string): string; pop(): T; push(...items: T[]): LoDashArrayWrapper; From 337f471b428d53f03f209edf6d7f2c90ccae815b Mon Sep 17 00:00:00 2001 From: Gabriel Monteagudo Date: Tue, 18 Aug 2015 02:00:33 -0300 Subject: [PATCH 064/345] Definitions for ydn-db --- ydn-db/ydn-db-tests.ts | 82 +++++++++++ ydn-db/ydn-db.d.ts | 306 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 388 insertions(+) create mode 100644 ydn-db/ydn-db-tests.ts create mode 100644 ydn-db/ydn-db.d.ts diff --git a/ydn-db/ydn-db-tests.ts b/ydn-db/ydn-db-tests.ts new file mode 100644 index 000000000..95279b831 --- /dev/null +++ b/ydn-db/ydn-db-tests.ts @@ -0,0 +1,82 @@ +/// + +var schema = { + stores: [{ + name: 'todo', + keyPath: "timeStamp" + }] +}; + + +/** + * Create and initialize the database. Depending on platform, this will + * create IndexedDB or WebSql or even localStorage storage mechanism. + * @type {ydn.db.Storage} + */ +var db = new ydn.db.Storage('todo_2', schema); + +var deleteTodo = function(id: any) { + db.remove('todo', id).fail(function(e) { + console.error(e); + }); + + getAllTodoItems(); +}; + +var getAllTodoItems = function() { + var todos = document.getElementById("todoItems"); + todos.innerHTML = ""; + + var df = db.values('todo'); + + df.done(function(items) { + var n = items.length; + for (var i = 0; i < n; i++) { + renderTodo(items[i]); + } + }); + + df.fail(function(e) { + console.error(e); + }) +}; + +var renderTodo = function(row: any) { + var todos = document.getElementById("todoItems"); + var li = document.createElement("li"); + var a = document.createElement("a"); + var t = document.createTextNode(row.text); + + a.addEventListener("click", function() { + deleteTodo(row.timeStamp); + }, false); + + a.textContent = " [Delete]"; + li.appendChild(t); + li.appendChild(a); + todos.appendChild(li) +}; + +var addTodo = function() { + var todo = document.getElementById("todo"); + + var data = { + "text": todo.value, + "timeStamp": new Date().getTime() + }; + db.put('todo', data).fail(function(e) { + console.error(e); + }); + + todo.value = ""; + + getAllTodoItems(); +}; + +function init() { + getAllTodoItems(); +} + +db.onReady(function() { + init(); +}); diff --git a/ydn-db/ydn-db.d.ts b/ydn-db/ydn-db.d.ts new file mode 100644 index 000000000..564c8ad4c --- /dev/null +++ b/ydn-db/ydn-db.d.ts @@ -0,0 +1,306 @@ +// Type definitions for YDN-DB version 1 +// Project: http://dev.yathit.com/ydn-db/index.html +// Definitions by: Kyaw Tun , Gabriel Monteagudo +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface FullTextSource { + storeName: string; + keyPath: string; + weight?: number; +} + +interface FullTextCatalog { + name: string; + lang: string; + sources: FullTextSource[]; +} + +interface IndexSchemaJson { + name?: string; + keyPath: string|string[]; + type?: string; + unique?: boolean; + multiEntry?: boolean; +} + +interface StoreSchemaJson { + autoIncrement?: boolean; + dispatchEvents?: boolean; + name?: string; + indexes?: IndexSchemaJson[]; + keyPath?: string; + type?: string; +} + +interface DatabaseSchemaJson { + version?: number; + stores: StoreSchemaJson[]; + fullTextCatalogs?: FullTextCatalog; +} + +interface StorageOptions { + mechanisms?: string[]; + size?: number; + autoSchema?: boolean; + isSerial?: boolean; + requestType?: string; +} + +declare module ydn.db { + export class Request { + abort(): any; + always(callback: (data: any) => void): any; + done(callback: (data: any) => void): any; + fail(callback: (data: any) => void): any; + then(success_callback: (data: any) => any, error_callback: (data: Error) => any): any; + canAbort(): boolean; + } + + export function cmp(first: any, second: any): number; + + export function deleteDatabase(db_name: string, type?: string): void; + + export class Key { + constructor(json: Object); + constructor(key_string: string); + constructor(store_name: string, id: any, parent_key?: Key); + } + + export class Iterator { + join(peer_store_name: string, peer_field_name?: string, value?: any): any; + getKey(): any; + getPrimaryKey(): any; + reset(): Iterator; + restrict(peer_field_name: string, value: any): any; + resume(key: any, index_key: any): Iterator; + reverse(key: any, index_key: any): Iterator; + } + + enum EventType { + created, + deleted, + error, + fail, + ready, + updated + } + + enum Policy { + all, + atomic, + multi, + repeat, + single + } + + enum TransactionMode { + readonly, + readwrite + } + + enum Op { + ">", "<", "=", ">=", "<=", "^" + } + + export class IndexKeyIterator extends Iterator { + constructor(store_name: string, index_name: string, key_range?: any, reverse?: boolean); + + static where(store_name: string, index_name: string, op: Op, value: any, op2: Op, value2: any): any; + + } + + export class KeyIterator extends Iterator { + constructor(store_name: string, key_range?: any, reverse?: boolean); + + static where(store_name: string, op: Op, value: any, op2: Op, value2: any): any; + + } + + export class ValueIterator extends Iterator { + constructor(store_name: string, key_range?: any, reverse?: boolean); + + static where(store_name: string, op: Op, value: any, op2: Op, value2: any): any; + + } + + export class IndexValueIterator extends Iterator { + constructor(store_name: string, index_name: string, key_range?: any, reverse?: boolean); + + static where(store_name: string, index_name: string, op: Op, value: any, op2: Op, value2: any): any; + + } + + export class Streamer { + constructor(storage: ydn.db.Storage, store_name: string, opt_field_name?: string); + + push(key: any, value?: any): any; + + collect(callback: (values: any[]) => void): any; + + setSink(callback: (key: any, value: any, toWait: () => boolean) => void): any; + } + + export class ICursor { + getKey(i?: number): any; + getPrimaryKey(i?: number): any; + getValue(i?: number): any; + clear(i?: number): Request; + update(value: Object, i?: number): Request; + } + + export class Query { + count(): Request; + open(callback: (ICursor: any) => void, Iterator: any, TransactionMode: any): Request; + patch(Object: any): Request; + patch(field_name: string, value: any): Request; + patch(field_names: string[], value: any[]): Request; + order(field_name: string): Query; + order(field_name: string, descending: boolean): Query; + order(field_names: string[]): Query; + order(field_names: string[], descending: boolean): Query; + reverse(): Query; + list(): Request; + list(limit: number): Request; + where(field_name: string, op: Op, value: any): any; + where(field_name: string, op: Op, value: any, op2: Op, value2: any): any; + } + + export class DbOperator { + + add(store_name: string, value: any, key: any): Request; + add(store_name: string, value: any): Request; + + clear(store_name: string, key_or_key_range: any): Request; + clear(store_name: string): Request; + clear(store_names: string[]): Request; + + count(store_name: string, key_range?: any): Request; + count(store_name: string, index_name: string, key_range: any): Request; + count(store_names: string[]): Request; + + executeSql(sql: string, params?: any[]): Request; + + from(store_name: string): Query; + from(store_name: string, op: Op, value: any): Query; + from(store_name: string, op: Op, value: any, op2: Op, value2: any): Query; + + get(store_name: string, key: any): Request; + + keys(iter: Iterator, limit?: number): Request; + keys(store_name: string, key_range?: Object, limit?: number, offset?: number, reverse?: boolean): Request; + keys(store_name: string, index_name: string, key_range?: Object, limit?: number, offset?: number, reverse?: boolean): Request; + keys(store_name: string, limit?: boolean, offset?: number): Request; + + open(next_callback: (cursor: ICursor) => any, iterator: Iterator, mode: TransactionMode): Request; + + put(store_name: string, value: any, key: any): Request; + put(store_name: string, value: any[], key: any[]): Request; + put(store_name: string, value: any): Request; + put(store_name: string, value: any[]): Request; + + remove(store_name: string, id_or_key_range: any): Request; + remove(store_name: string, index_name: string, id_or_key_range: any): Request; + clear(store_name: string, key_or_key_range: any): Request; + + scan(solver: (keys: any[], values: any[]) => any, iterators: Iterator[]): Request; + + values(iter: Iterator, limit?: number): Request; + values(store_name: string, key_range?: Object, limit?: number, offset?: number, reverse?: boolean): Request; + values(store_name: string, index_name: string, key_range?: Object, limit?: number, offset?: number, reverse?: boolean): Request; + values(store_name: string, ids?: Array): Request; + values(keys?: Array): Request; + } + + export class Storage extends DbOperator { + + constructor(db_name?: string, schema?: DatabaseSchemaJson, options?: StorageOptions); + + addEventListener(type: EventType, handler: (event: any) => void, capture?: boolean): any; + addEventListener(type: EventType[], handler: (event: any) => void, capture?: boolean): any; + + branch(thread: Policy, isSerial: boolean, scope: string[], mode: TransactionMode, maxRequest: number): DbOperator; + + close(): any; + + get(store_name: string, key: any): Request; + + getName(callback: any): string; + + getSchema(callback: any): DatabaseSchemaJson; + + getType(): string; + + onReady(Error?: any): any; + + removeEventListener(type: EventType, handler: (event: any) => void, capture?: boolean): any; + removeEventListener(type: EventType[], handler: (event: any) => void, capture?: boolean): any; + + run(callback: (iStorage: ydn.db.Storage) => void, store_names: string[], mode: TransactionMode): Request; + + search(catalog_name: string): Request; + + setName(name: string): any; + + transaction(callback: (tx: any) => void, store_names: string[], mode: TransactionMode, completed_handler: (type: string, e?: Error) => void): any; + + } +} + +declare module ydb.db.algo { + + export class Solver { + + } + + export class NestedLoop extends Solver { + constructor(out: { push: (value: any) => void }, limit?: number); + } + + export class SortedMerge extends Solver { + constructor(out: { push: (value: any) => void }, limit?: number); + } + + export class ZigzagMerge extends Solver { + constructor(out: { push: (value: any) => void }, limit?: number); + } + +} + +declare module ydn.db.events { + + export class Event { + + name: string; + + type: ydn.db.EventType; + } + + export class RecordEvent extends Event { + + getStoreName(): string; + + getKey(): any; + + getValue(): any; + } + + + export class StorageEvent extends Event { + + getError(): Error; + + getVersion(): number; + + getOldVersion(): number; + } + + + export class StoreEvent extends Event { + + getStoreName(): string; + + getKeys(): any[]; + + getValues(): any[]; + } +} From 92ce54989d828b19f0759dd581f10055975ba81f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20Corbi=C3=A8re?= Date: Tue, 18 Aug 2015 19:26:06 +0200 Subject: [PATCH 065/345] [gulp-less] Update the definition of IOptions Add "modifyVars" Make "paths" optional --- gulp-less/gulp-less-tests.ts | 16 ++++++++++++++++ gulp-less/gulp-less.d.ts | 3 ++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/gulp-less/gulp-less-tests.ts b/gulp-less/gulp-less-tests.ts index 76e0a697c..a0671e766 100644 --- a/gulp-less/gulp-less-tests.ts +++ b/gulp-less/gulp-less-tests.ts @@ -4,6 +4,22 @@ import gulp = require("gulp"); import less = require("gulp-less"); +// Without options +gulp.task("less", () => { + gulp.src("less/**/*.less") + .pipe(less()) + .pipe(gulp.dest("public/css")); +}); + +// With an empty option object +gulp.task("less", () => { + gulp.src("less/**/*.less") + .pipe(less({})) + .pipe(gulp.dest("public/css")); +}); + + +// With some options gulp.task("less", () => { gulp.src("less/**/*.less") .pipe(less({ diff --git a/gulp-less/gulp-less.d.ts b/gulp-less/gulp-less.d.ts index 9ca5e35b7..84adca370 100644 --- a/gulp-less/gulp-less.d.ts +++ b/gulp-less/gulp-less.d.ts @@ -8,7 +8,8 @@ declare module "gulp-less" { interface IOptions { - paths: string[]; + modifyVars?: {}; + paths?: string[]; plugins?: any[]; } From 3aba989e923199d9c4834b2c69eb698c9276b344 Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Tue, 18 Aug 2015 19:04:19 +0100 Subject: [PATCH 066/345] Type definitions and tests for upper-case --- upper-case/upper-case.d.ts | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 upper-case/upper-case.d.ts diff --git a/upper-case/upper-case.d.ts b/upper-case/upper-case.d.ts new file mode 100644 index 000000000..c59348776 --- /dev/null +++ b/upper-case/upper-case.d.ts @@ -0,0 +1,9 @@ +// Type definitions for upper-case +// Project: https://github.com/blakeembrey/upper-case +// Definitions by: Sam Saint-Pettersen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "upper-case" { + function upperCase(string: any, locale?: string): string; + export = upperCase; +} From 6e22f9146c5f0cb87a2fc582dfa2d0a3c025fb72 Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Tue, 18 Aug 2015 19:06:32 +0100 Subject: [PATCH 067/345] Type definitions and tests for upper-case --- upper-case/upper-case-tests.ts | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 upper-case/upper-case-tests.ts diff --git a/upper-case/upper-case-tests.ts b/upper-case/upper-case-tests.ts new file mode 100644 index 000000000..7e1a4a0b5 --- /dev/null +++ b/upper-case/upper-case-tests.ts @@ -0,0 +1,9 @@ +/// + +import upperCase = require('upper-case'); + +console.log(upperCase(null)); // => "" +console.log(upperCase('string')); // => "STRING" +console.log(upperCase('string', 'tr')); // => "STRİNG" + +console.log(upperCase({ toString: function() { return 'test' } })); // => "TEST" From 95c2990f0ac17d991f72bbc51fb3217ce354809c Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Tue, 18 Aug 2015 19:07:18 +0100 Subject: [PATCH 068/345] Update upper-case-tests.ts --- upper-case/upper-case-tests.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/upper-case/upper-case-tests.ts b/upper-case/upper-case-tests.ts index 7e1a4a0b5..a7128bdf6 100644 --- a/upper-case/upper-case-tests.ts +++ b/upper-case/upper-case-tests.ts @@ -4,6 +4,5 @@ import upperCase = require('upper-case'); console.log(upperCase(null)); // => "" console.log(upperCase('string')); // => "STRING" -console.log(upperCase('string', 'tr')); // => "STRİNG" console.log(upperCase({ toString: function() { return 'test' } })); // => "TEST" From 4af10f4fae29eabec77058fc16b88af282bbea70 Mon Sep 17 00:00:00 2001 From: Dan Lewi Harkestad Date: Tue, 18 Aug 2015 20:09:11 +0200 Subject: [PATCH 069/345] Added tests covering all modifications. --- angular-ui-router/angular-ui-router-tests.ts | 48 ++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/angular-ui-router/angular-ui-router-tests.ts b/angular-ui-router/angular-ui-router-tests.ts index a05f13dd8..dccd8f7b1 100644 --- a/angular-ui-router/angular-ui-router-tests.ts +++ b/angular-ui-router/angular-ui-router-tests.ts @@ -14,12 +14,28 @@ myApp.config(( var matcher: ng.ui.IUrlMatcher = $urlMatcherFactory.compile("/foo/:bar?param1"); + $urlMatcherFactory.caseInsensitive(false); + var isCaseInsensitive = $urlMatcherFactory.caseInsensitive(); + + $urlMatcherFactory.defaultSquashPolicy("nosquash"); + + $urlMatcherFactory.strictMode(true); + var isStrictMode = $urlMatcherFactory.strictMode(); + $urlMatcherFactory.type("myType2", { encode: function (item: any) { return item; }, decode: function (item: any) { return item; }, is: function (item: any) { return true; } }); + $urlMatcherFactory.type("fullType", { + decode: (val) => parseInt(val, 10), + encode: (val) => val && val.toString(), + equals: (a, b) => this.is(a) && a === b, + is: (val) => angular.isNumber(val) && isFinite(val) && val % 1 === 0, + pattern: /\d+/ + }); + var obj: Object = matcher.exec('/user/bob', { x:'1', q:'hello' }); var concat: ng.ui.IUrlMatcher = matcher.concat('/test'); var str: string = matcher.format({ id:'bob', q:'yes' }); @@ -177,3 +193,35 @@ module UiViewScrollProviderTests { $uiViewScrollProvider.useAnchorScroll(); }]); } + +interface ITestUserService { + isLoggedIn: () => boolean; + handleLogin: () => ng.IPromise<{}>; +} + +module UrlRouterProviderTests { + var app = angular.module("urlRouterProviderTests", ["ui.router"]); + + app.config(($urlRouterProvider: ng.ui.IUrlRouterProvider) => { + // Prevent $urlRouter from automatically intercepting URL changes; + // this allows you to configure custom behavior in between + // location changes and route synchronization: + $urlRouterProvider.deferIntercept(); + }).run(($rootScope: ng.IRootScopeService, $urlRouter: ng.ui.IUrlRouterService, UserService: ITestUserService) => { + $rootScope.$on('$locationChangeSuccess', e => { + // UserService is an example service for managing user state + if (UserService.isLoggedIn()) return; + + // Prevent $urlRouter's default handler from firing + e.preventDefault(); + + UserService.handleLogin().then(() => { + // Once the user has logged in, sync the current URL to the router: + $urlRouter.sync(); + }); + }); + + // Configures $urlRouter's listener *after* your custom listener + $urlRouter.listen(); + }); +} From 763868e7deed5a5087aa1e0e2455656109d9e628 Mon Sep 17 00:00:00 2001 From: MugeSo Date: Wed, 19 Aug 2015 11:32:47 +0900 Subject: [PATCH 070/345] rsmq-worker: export Client interface --- rsmq-worker/rsmq-worker-tests.ts | 4 +- rsmq-worker/rsmq-worker.d.ts | 71 ++++++++++++++++---------------- 2 files changed, 39 insertions(+), 36 deletions(-) diff --git a/rsmq-worker/rsmq-worker-tests.ts b/rsmq-worker/rsmq-worker-tests.ts index 4568302dd..fa635e415 100644 --- a/rsmq-worker/rsmq-worker-tests.ts +++ b/rsmq-worker/rsmq-worker-tests.ts @@ -1,7 +1,9 @@ import RSMQWorker = require('rsmq-worker'); -var worker = new RSMQWorker("my-queue"); +var worker: RSMQWorker.Client; + +worker = new RSMQWorker("my-queue"); worker.changeInterval(1); worker.changeInterval([0, 1, 5, 10]); diff --git a/rsmq-worker/rsmq-worker.d.ts b/rsmq-worker/rsmq-worker.d.ts index 8783d914f..9823daa87 100644 --- a/rsmq-worker/rsmq-worker.d.ts +++ b/rsmq-worker/rsmq-worker.d.ts @@ -9,44 +9,45 @@ declare module "rsmq-worker" { import redis = require('redis'); import events = require('events'); - interface CallbackT { - (e?:Error, res?:R): void; + module RSMQWorker { + export interface Client extends events.EventEmitter { + start(): Client; + stop(): Client; + send(message: string, delay?: number, cb?: CallbackT): Client; + send(message: string, cb: CallbackT): Client; + del(id: string, cb?: CallbackT): Client; + changeInterval(interval: number|number[]): Client; + } + + export interface Options { + interval?: number; + maxReceiveCount?: number; + invisibletime?: number; + defaultDelay?: number; + autostart?: boolean; + timeout: number; + customExceedCheck?: CustomExceedCheckCallback; + rsmq?: RedisSMQ.Client; + redis?: redis.RedisClient; + redisPrefix?: string; + host?: string; + port?: number; + options?: redis.ClientOpts; + } + + export interface CustomExceedCheckCallback { + (message: RedisSMQ.Message): boolean; + } + + export interface CallbackT { + (e?:Error, res?:R): void; + } } interface RSMQWorkerStatic { - new(queuename: string, options?: WorkerOptions): RSMQWorker; + new(queuename: string, options?: RSMQWorker.Options): RSMQWorker.Client; } - interface WorkerOptions { - interval?: number; - maxReceiveCount?: number; - invisibletime?: number; - defaultDelay?: number; - autostart?: boolean; - timeout: number; - customExceedCheck?: CustomExceedCheckCallback; - rsmq?: RedisSMQ.Client; - redis?: redis.RedisClient; - redisPrefix?: string; - host?: string; - port?: number; - options?: redis.ClientOpts; - } - - interface CustomExceedCheckCallback { - (message: RedisSMQ.Message): boolean; - } - - - interface RSMQWorker extends events.EventEmitter { - start(): RSMQWorker; - stop(): RSMQWorker; - send(message: string, delay?: number, cb?: CallbackT): RSMQWorker; - send(message: string, cb: CallbackT): RSMQWorker; - del(id: string, cb?: CallbackT): RSMQWorker; - changeInterval(interval: number|number[]): RSMQWorker; - } - - var worker: RSMQWorkerStatic; - export = worker; + var RSMQWorker: RSMQWorkerStatic; + export = RSMQWorker; } From a0f49f14ee51736e8dbd625942214674c9fe9a1f Mon Sep 17 00:00:00 2001 From: MugeSo Date: Wed, 19 Aug 2015 11:37:34 +0900 Subject: [PATCH 071/345] rsmq-worker: change Options.timeout optional --- rsmq-worker/rsmq-worker.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rsmq-worker/rsmq-worker.d.ts b/rsmq-worker/rsmq-worker.d.ts index 9823daa87..6af1564e1 100644 --- a/rsmq-worker/rsmq-worker.d.ts +++ b/rsmq-worker/rsmq-worker.d.ts @@ -25,7 +25,7 @@ declare module "rsmq-worker" { invisibletime?: number; defaultDelay?: number; autostart?: boolean; - timeout: number; + timeout?: number; customExceedCheck?: CustomExceedCheckCallback; rsmq?: RedisSMQ.Client; redis?: redis.RedisClient; From 6ddf6c5edea0f2385c5c4af837fefddb29ac8cfe Mon Sep 17 00:00:00 2001 From: zenorbi Date: Wed, 19 Aug 2015 09:48:06 +0200 Subject: [PATCH 072/345] Fixed feedbackData.device being a Device instead of a Buffer --- apn/apn-test.ts | 4 ++-- apn/apn.d.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/apn/apn-test.ts b/apn/apn-test.ts index a9e2c21a7..b47259d76 100644 --- a/apn/apn-test.ts +++ b/apn/apn-test.ts @@ -50,7 +50,7 @@ var feedbackService = new apn.Feedback({ feedbackService.on("error", (error:Error) => { console.log("push feedback error", error.name, error.message); }); -function processFeedbackData(device:Buffer, time:number) { +function processFeedbackData(device:apn.Device, time:number) { } feedbackService.on("feedback", (feedbackData) => { feedbackData.forEach((data) => { @@ -135,7 +135,7 @@ pushSomeNotifications(); function handleFeedback(feedbackData:apn.FeedbackData[]) { feedbackData.forEach(function(feedbackItem) { - console.log("Device: " + feedbackItem.device.toString("hex") + " has been unreachable, since: " + feedbackItem.time); + console.log("Device: " + feedbackItem.device.toString() + " has been unreachable, since: " + feedbackItem.time); }); } diff --git a/apn/apn.d.ts b/apn/apn.d.ts index ed38086ef..cd67743da 100644 --- a/apn/apn.d.ts +++ b/apn/apn.d.ts @@ -307,7 +307,7 @@ declare module "apn" { } export interface FeedbackData { time:number; - device:Buffer; + device:Device; } /** * Connection to the Apple Push Notification Feedback Service and if `interval` isn't disabled automatically begins polling the service. Many of the options are the same as `apn.Connection()` From 2daf450b8f86f09f6b0de1b5f86fce3cf185c687 Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 19 Aug 2015 14:21:19 +0200 Subject: [PATCH 073/345] updated enabled as per angular changes (after 1.3.14 > 1.4.0) --- angularjs/angular-animate.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/angularjs/angular-animate.d.ts b/angularjs/angular-animate.d.ts index 1ecc3d0d7..35fe10ca9 100644 --- a/angularjs/angular-animate.d.ts +++ b/angularjs/angular-animate.d.ts @@ -30,11 +30,11 @@ declare module angular.animate { /** * Globally enables / disables animations. * - * @param value If provided then set the animation on or off. * @param element If provided then the element will be used to represent the enable/disable operation. + * @param value If provided then set the animation on or off. * @returns current animation state */ - enabled(value?: boolean, element?: JQuery): boolean; + enabled(element?: JQuery, value?: boolean): boolean; /** * Performs an inline animation on the element. From 3ef00546da8850c9c962bffb87d65cd43a9b262b Mon Sep 17 00:00:00 2001 From: Marcin Porebski Date: Wed, 19 Aug 2015 15:09:10 +0200 Subject: [PATCH 074/345] url-template definitions --- url-template/url-template-tests.ts | 13 +++++++++++++ url-template/url-template.d.ts | 24 ++++++++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 url-template/url-template-tests.ts create mode 100644 url-template/url-template.d.ts diff --git a/url-template/url-template-tests.ts b/url-template/url-template-tests.ts new file mode 100644 index 000000000..f477a160a --- /dev/null +++ b/url-template/url-template-tests.ts @@ -0,0 +1,13 @@ +/// + + +import urlTemplate = require('url-template'); + +var emailUrl = urlTemplate.parse('/{email}/{folder}/{id}'); + +// Returns '/user@domain/test/42' +emailUrl.expand({ + email: 'user@domain', + folder: 'test', + id: 42 +}); diff --git a/url-template/url-template.d.ts b/url-template/url-template.d.ts new file mode 100644 index 000000000..6ed7f5e86 --- /dev/null +++ b/url-template/url-template.d.ts @@ -0,0 +1,24 @@ +// Type definitions for url-template 2.0.6 +// Project: https://github.com/bramstein/url-template +// Definitions by: Marcin Porębski +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module UrlTemplate +{ + interface TemplateParser { + parse(template: string): Template; + } + + interface Template { + expand(parameters: any): string; + } +} + +declare module "url-template" +{ + var urlTemplate: UrlTemplate.TemplateParser; + + export = urlTemplate; +} + + From 44e32d3b32c98cb1aa16ec5ea8e5b48b29e58b55 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Karl=20D=C3=BC=C3=BCna?= Date: Wed, 19 Aug 2015 17:13:35 +0300 Subject: [PATCH 075/345] easy-xapi-utils --- easy-xapi-utils/easy-xapi-utils-tests.ts | 43 ++++++++++++++++++++++++ easy-xapi-utils/easy-xapi-utils.d.ts | 16 +++++++++ 2 files changed, 59 insertions(+) create mode 100644 easy-xapi-utils/easy-xapi-utils-tests.ts create mode 100644 easy-xapi-utils/easy-xapi-utils.d.ts diff --git a/easy-xapi-utils/easy-xapi-utils-tests.ts b/easy-xapi-utils/easy-xapi-utils-tests.ts new file mode 100644 index 000000000..d80a7976c --- /dev/null +++ b/easy-xapi-utils/easy-xapi-utils-tests.ts @@ -0,0 +1,43 @@ +/** + * Created by karl on 14/07/15. + */ + +/// +/// +/// + +import express = require('express'); +import eXapi = require('easy-xapi'); +import eUtils = require('easy-xapi-utils'); + +eXapi.init({ + jSend: { + partial: true + } +}); + +var xApi = eXapi.create({ + root: __dirname, + log: { + name: 'Log', + level: 'info' + }, + port: 3000, + name: 'test', + mount: function (app) { + app.get('/', eUtils.isLoggedIn(), function (req, res) { + res.send('ok'); + }); + app.get('/role', eUtils.isLoggedIn('admin'), function (req, res) { + res.send('ok'); + }); + app.get('/', eUtils.isLoggedOut(), function (req, res) { + res.send('ok'); + }); + app.get('/role', eUtils.hasRole('guest'), function (req, res) { + res.send('ok'); + }); + } +}); + +xApi.listen(); diff --git a/easy-xapi-utils/easy-xapi-utils.d.ts b/easy-xapi-utils/easy-xapi-utils.d.ts new file mode 100644 index 000000000..637829098 --- /dev/null +++ b/easy-xapi-utils/easy-xapi-utils.d.ts @@ -0,0 +1,16 @@ +// Type definitions for easy-xapi-utils +// Project: https://github.com/DeadAlready/easy-xapi-utils +// Definitions by: Karl Düüna +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// +/// + +declare module "easy-xapi-utils" { + import express = require('express'); + + export function isLoggedIn(role?: string): express.RequestHandler; + export function isLoggedOut(): express.RequestHandler; + export function hasRole(role: string): express.RequestHandler; +} From 329f39b8da64bea4f7a7e5fa530220a8439e9853 Mon Sep 17 00:00:00 2001 From: Matt Gibbs Date: Wed, 19 Aug 2015 10:46:48 -0400 Subject: [PATCH 076/345] Correcting typings on Tour Buttons --- tether-shepherd/tether-shepherd.d.ts | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/tether-shepherd/tether-shepherd.d.ts b/tether-shepherd/tether-shepherd.d.ts index b632fb771..eeee87104 100644 --- a/tether-shepherd/tether-shepherd.d.ts +++ b/tether-shepherd/tether-shepherd.d.ts @@ -143,7 +143,7 @@ declare module TetherShepherd { title?: string; attachTo?: any; beforeShowPromise?: any; - classes?: any; + classes?: string; buttons?: IShepherdTourButton[]; advanceOn?: any; showCancelLink?: boolean; @@ -156,9 +156,13 @@ declare module TetherShepherd { interface IShepherdTourButton { text: string; - classes: string[]; - action?: any; - events?: any; + classes?: string; + action?: Function; + events?: IShepherdTourButtonEventHash; + } + + interface IShepherdTourButtonEventHash { + [Key: string]: Function; } interface IShepherdTourAttachProperties { From 0ac23ee1fb12c3c3d849deb8f1cd50353a5e9839 Mon Sep 17 00:00:00 2001 From: Matt Gibbs Date: Wed, 19 Aug 2015 11:22:40 -0400 Subject: [PATCH 077/345] Creating more robust test case. --- tether-shepherd/tether-shepherd-tests.ts | 46 ++++++++++++++++++++++-- 1 file changed, 44 insertions(+), 2 deletions(-) diff --git a/tether-shepherd/tether-shepherd-tests.ts b/tether-shepherd/tether-shepherd-tests.ts index 48bef675b..7325a8464 100644 --- a/tether-shepherd/tether-shepherd-tests.ts +++ b/tether-shepherd/tether-shepherd-tests.ts @@ -6,11 +6,53 @@ var tour = new Shepherd.Tour({ } }); -tour.addStep('test-step', { +var step1Options: TetherShepherd.IShepherdTourStepOptions = { text: 'This is a test step being added to the test tour', title: 'Test Step Title', attachTo: { element: '#button', on: 'right' + }, + buttons: [ + { + text: 'Continue', + action: tour.next + }, + { + text: 'Cancel', + action: tour.cancel + } + ] +}; + +tour.addStep('test-step', step1Options); + +var step2Options: TetherShepherd.IShepherdTourStepOptions = { + text: 'This is the next step being added to the test tour', + title: 'Test Step Title 2 - Electric Boogaloo', + attachTo: '#anotherButton right', + buttons: [ + { + text: 'Done', + action: tour.next, + events: { + 'mouseover': () => { + console.log('I did not feel like making a function body that pretended to do something else'); + } + } + } + ], + when: { + destroy: () => { + console.log('Destroyed the Step 2'); + } } -}); +}; + +tour.addStep('test-step-2', step2Options); + +var queriedStep = tour.getById('test-step-2'); + +queriedStep.destroy(); + +tour.start(); \ No newline at end of file From 132ed07af75076dfbc7643533e043d9a7eda652f Mon Sep 17 00:00:00 2001 From: Demian Gemperli Date: Wed, 19 Aug 2015 18:16:23 +0200 Subject: [PATCH 078/345] Fix cordova file transfer download --- cordova/cordova-tests.ts | 8 ++++++-- cordova/plugins/FileTransfer.d.ts | 8 ++++---- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/cordova/cordova-tests.ts b/cordova/cordova-tests.ts index d162b1ab6..491b49773 100644 --- a/cordova/cordova-tests.ts +++ b/cordova/cordova-tests.ts @@ -176,8 +176,12 @@ file.download('http://some.server.com/download.php', console.error('Failed with exception ' + err.exception); } }, - { headers: null }, - true); + true, + { + headers: { + "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA==" + } + }); file.upload('cdvfile://localhost/persistent/path/to/downloads/', 'http://some.server.com/download.php', diff --git a/cordova/plugins/FileTransfer.d.ts b/cordova/plugins/FileTransfer.d.ts index d0c023ae8..7cbde5322 100644 --- a/cordova/plugins/FileTransfer.d.ts +++ b/cordova/plugins/FileTransfer.d.ts @@ -53,8 +53,8 @@ interface FileTransfer { target: string, successCallback: (fileEntry: FileEntry) => void, errorCallback: (error: FileTransferError) => void, - options?: FileDownloadOptions, - trustAllHosts?: boolean): void; + trustAllHosts?: boolean, + options?: FileDownloadOptions): void; /** * Aborts an in-progress transfer. The onerror callback is passed a FileTransferError object * which has an error code of FileTransferError.ABORT_ERR. @@ -98,8 +98,8 @@ interface FileUploadOptions { /** Optional parameters for download method. */ interface FileDownloadOptions { - /** A map of header name/header values. Use an array to specify more than one value. */ - headers?: Object[]; + /** A map of header name/header values. */ + headers?: {}; } /** A FileTransferError object is passed to an error callback when an error occurs. */ From cb2b22f81a17658943fbcb06f15c0bde4e60e79c Mon Sep 17 00:00:00 2001 From: Marcin Porebski Date: Wed, 19 Aug 2015 18:48:48 +0200 Subject: [PATCH 079/345] string score definitions --- string_score/string_score-tests.ts | 8 ++++++++ string_score/string_score.d.ts | 8 ++++++++ 2 files changed, 16 insertions(+) create mode 100644 string_score/string_score-tests.ts create mode 100644 string_score/string_score.d.ts diff --git a/string_score/string_score-tests.ts b/string_score/string_score-tests.ts new file mode 100644 index 000000000..8a7399603 --- /dev/null +++ b/string_score/string_score-tests.ts @@ -0,0 +1,8 @@ +/// + +import string_score = require('string_score'); + +var a = 'abc'; +var b = 'xyz'; + +console.log(a.score(b).toString()); diff --git a/string_score/string_score.d.ts b/string_score/string_score.d.ts new file mode 100644 index 000000000..2d901ba39 --- /dev/null +++ b/string_score/string_score.d.ts @@ -0,0 +1,8 @@ +// Type definitions for url-template 0.1.22 +// Project: https://github.com/joshaven/string_score +// Definitions by: Marcin Porębski +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface String { + score: (word: string, fuzzy?: number) => number; +} From 0659ddca429da57326e2856c92bf51dfbad29dc2 Mon Sep 17 00:00:00 2001 From: Ray Solomon Date: Wed, 19 Aug 2015 10:10:20 -0700 Subject: [PATCH 080/345] bunyan: fix ts1202 errors when targeting es6 Before this change: ``` [ray@localhost DefinitelyTyped]$ tsc --noImplicitAny bunyan/bunyan-test.ts --module commonjs --target es6 bunyan/bunyan-test.ts(3,1): error TS1202: Import assignment cannot be used when targeting ECMAScript 6 or higher. Consider using 'import * as ns from "mod"', 'import {a} from "mod"' or 'import d from "mod"' instead. bunyan/bunyan.d.ts(9,5): error TS1202: Import assignment cannot be used when targeting ECMAScript 6 or higher. Consider using 'import * as ns from "mod"', 'import {a} from "mod"' or 'import d from "mod"' instead. [ray@localhost DefinitelyTyped]$ ``` After this change: ``` [ray@localhost DefinitelyTyped]$ tsc --noImplicitAny bunyan/bunyan-test.ts --module commonjs --target es6 [ray@localhost DefinitelyTyped]$ ``` --- bunyan/bunyan-test.ts | 2 +- bunyan/bunyan.d.ts | 8 +++----- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/bunyan/bunyan-test.ts b/bunyan/bunyan-test.ts index b8e51d145..c10c6c6e0 100644 --- a/bunyan/bunyan-test.ts +++ b/bunyan/bunyan-test.ts @@ -1,6 +1,6 @@ /// -import bunyan = require('bunyan'); +import * as bunyan from 'bunyan'; var ringBufferOptions:bunyan.RingBufferOptions = { limit: 100 diff --git a/bunyan/bunyan.d.ts b/bunyan/bunyan.d.ts index 1f73705c3..e491b8cd3 100644 --- a/bunyan/bunyan.d.ts +++ b/bunyan/bunyan.d.ts @@ -6,9 +6,7 @@ /// declare module "bunyan" { - import events = require('events'); - import EventEmitter = events.EventEmitter; - import WritableStream = NodeJS.WritableStream; + import { EventEmitter } from 'events'; class Logger extends EventEmitter { constructor(options:LoggerOptions); @@ -52,7 +50,7 @@ declare module "bunyan" { name: string; streams?: Stream[]; level?: string | number; - stream?: WritableStream; + stream?: NodeJS.WritableStream; serializers?: Serializers; src?: boolean; } @@ -65,7 +63,7 @@ declare module "bunyan" { type?: string; level?: number | string; path?: string; - stream?: WritableStream | Stream; + stream?: NodeJS.WritableStream | Stream; closeOnExit?: boolean; } From 8409007d3e20b8d462d945b5c3c9d86d2e6bbf06 Mon Sep 17 00:00:00 2001 From: Andrew F Date: Wed, 19 Aug 2015 11:35:40 -0700 Subject: [PATCH 081/345] Add interface typing --- segment-analytics/segment-analytics.d.ts | 98 ++++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100755 segment-analytics/segment-analytics.d.ts diff --git a/segment-analytics/segment-analytics.d.ts b/segment-analytics/segment-analytics.d.ts new file mode 100755 index 000000000..6d5f4465f --- /dev/null +++ b/segment-analytics/segment-analytics.d.ts @@ -0,0 +1,98 @@ +// Type definitions for Segment's analytics.js +// Project: https://segment.com/docs/libraries/analytics.js/ +// Definitions by: Andrew Fong +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module SegmentAnalytics { + + // Generic options object with integrations + interface ISegmentOpts { + integrations: Integrations; + }; + + // The actual analytics.js object + interface AnalyticsJS { + + /* Configure Segment with write key */ + load(writeKey: string); + + /* The identify method is how you tie one of your users and their actions + to a recognizable userId and traits. */ + identify(userId: string, traits?: Object, + options?: ISegmentOpts, + callback?: () => void): void; + identify(userId: string, traits: Object, callback?: () => void): void; + identify(userId: string, callback?: () => void): void; + identify(traits?: Object, + options?: ISegmentOpts, + callback?: () => void): void; + identify(traits?: Object, + callback?: () => void): void; + identify(callback: () => void): void; + + /* The track method lets you record any actions your users perform. */ + track(event: string, properties?: Object, + options?: ISegmentOpts, + callback?: () => void): void; + track(event: string, properties?: Object, + callback?: () => void): void; + track(event: string, callback?: () => void): void; + + /* The page method lets you record page views on your website, along with + optional extra information about the page being viewed. */ + page(category: string, name: string, properties?: Object, + options?: ISegmentOpts, + callback?: () => void): void; + page(name?: string, properties?: Object, + options?: ISegmentOpts, + callback?: () => void): void; + page(name?: string, properties?: Object, callback?: () => void): void; + page(name?: string, callback?: () => void): void; + page(properties?: Object, + options?: ISegmentOpts, + callback?: () => void): void; + page(callback?: () => void): void; + + /* The alias method combines two previously unassociated user identities. + This comes in handy if the same user visits from two different devices + and you want to combine their history. + + Some providers also don’t alias automatically for you when an anonymous + user signs up (like Mixpanel), so you need to call alias manually right + after sign up with their brand new userId. */ + alias(userId: string, previousId?: string, + options?: ISegmentOpts, + callback?: () => void): void; + alias(userId: string, previousId?: string, callback?: () => void): void; + alias(userId: string, callback?: () => void): void; + alias(userId: string, options?: ISegmentOpts, + callback?: () => void): void; + + /* trackLink is a helper that binds a track call to whenever a link is + clicked. Usually the page would change before you could call track, but + with trackLink a small timeout is inserted to give the track call enough + time to fire. */ + trackLink(elements: Element|Element[], event: string, properties?: Object); + + /* trackForm is a helper that binds a track call to a form submission. + Usually the page would change before you could call track, but with + trackForm a small timeout is inserted to give the track call enough + time to fire. */ + trackForm(elements: Element|Element[], event: string, properties?: Object); + + /* The ready method allows you to pass in a callback that will be called as + soon as all of your enabled integrations have loaded. It’s like jQuery’s + ready method, except for integrations. */ + ready(callback: () => void); + + // Cookie-based user object + user(): { + id(): string; + logout(): void; + reset(): void; + }; + } +} + + +// declare var analytics: ISegment; \ No newline at end of file From 42edb17991ae0d38eb41325637e81d6e728c2da8 Mon Sep 17 00:00:00 2001 From: Andrew F Date: Wed, 19 Aug 2015 12:03:08 -0700 Subject: [PATCH 082/345] Group method --- segment-analytics/segment-analytics.d.ts | 34 +++++++++++++++--------- 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/segment-analytics/segment-analytics.d.ts b/segment-analytics/segment-analytics.d.ts index 6d5f4465f..1b8cc8bf5 100755 --- a/segment-analytics/segment-analytics.d.ts +++ b/segment-analytics/segment-analytics.d.ts @@ -6,8 +6,9 @@ declare module SegmentAnalytics { // Generic options object with integrations - interface ISegmentOpts { - integrations: Integrations; + interface SegmentOpts { + integrations?: Integrations; + anonymousId?: string; }; // The actual analytics.js object @@ -19,12 +20,12 @@ declare module SegmentAnalytics { /* The identify method is how you tie one of your users and their actions to a recognizable userId and traits. */ identify(userId: string, traits?: Object, - options?: ISegmentOpts, + options?: SegmentOpts, callback?: () => void): void; identify(userId: string, traits: Object, callback?: () => void): void; identify(userId: string, callback?: () => void): void; identify(traits?: Object, - options?: ISegmentOpts, + options?: SegmentOpts, callback?: () => void): void; identify(traits?: Object, callback?: () => void): void; @@ -32,7 +33,7 @@ declare module SegmentAnalytics { /* The track method lets you record any actions your users perform. */ track(event: string, properties?: Object, - options?: ISegmentOpts, + options?: SegmentOpts, callback?: () => void): void; track(event: string, properties?: Object, callback?: () => void): void; @@ -41,18 +42,27 @@ declare module SegmentAnalytics { /* The page method lets you record page views on your website, along with optional extra information about the page being viewed. */ page(category: string, name: string, properties?: Object, - options?: ISegmentOpts, + options?: SegmentOpts, callback?: () => void): void; page(name?: string, properties?: Object, - options?: ISegmentOpts, + options?: SegmentOpts, callback?: () => void): void; page(name?: string, properties?: Object, callback?: () => void): void; page(name?: string, callback?: () => void): void; page(properties?: Object, - options?: ISegmentOpts, + options?: SegmentOpts, callback?: () => void): void; page(callback?: () => void): void; + /* The group method associates an individual user with a group. The group + can a company, organization, account, project, team or any other name + you came up with for the same concept. */ + group(groupId: string, traits?: Object, + options?: SegemntOpts, + callback?: () => void): void; + group(groupId: string, traits?: Object, callback?: () => void): void; + group(groupId: string, callback?: () => void): void; + /* The alias method combines two previously unassociated user identities. This comes in handy if the same user visits from two different devices and you want to combine their history. @@ -61,11 +71,11 @@ declare module SegmentAnalytics { user signs up (like Mixpanel), so you need to call alias manually right after sign up with their brand new userId. */ alias(userId: string, previousId?: string, - options?: ISegmentOpts, + options?: SegmentOpts, callback?: () => void): void; alias(userId: string, previousId?: string, callback?: () => void): void; alias(userId: string, callback?: () => void): void; - alias(userId: string, options?: ISegmentOpts, + alias(userId: string, options?: SegmentOpts, callback?: () => void): void; /* trackLink is a helper that binds a track call to whenever a link is @@ -90,9 +100,9 @@ declare module SegmentAnalytics { id(): string; logout(): void; reset(): void; + anonymousId(newId?: string): string; }; } } - -// declare var analytics: ISegment; \ No newline at end of file +declare var analytics: SegmentAnalytics.AnalyticsJS; From 47b934362ae9891e5a2d4ae819a5381d7f7e0d60 Mon Sep 17 00:00:00 2001 From: Giovanni Bassi Date: Wed, 19 Aug 2015 16:24:39 -0300 Subject: [PATCH 083/345] Remove global `module` definition from angular-mocks Because it conficts with commonjs. See http://wiki.commonjs.org/wiki/Modules/1.1: > In a module, there must be a free variable "module", that is an Object. Also see the existing `module` declaration on: https://github.com/borisyankov/DefinitelyTyped/blob/27e02d6674ffe8186a567515b4c157bcf945911e/node/node.d.ts#L61 Workaround is to use `angular.mock.module` instead of `module`. Closes #2072 --- angularjs/angular-mocks.d.ts | 3 ++- bardjs/bardjs-tests.ts | 14 +++++++------- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/angularjs/angular-mocks.d.ts b/angularjs/angular-mocks.d.ts index e6b668a7b..09e4ac61f 100644 --- a/angularjs/angular-mocks.d.ts +++ b/angularjs/angular-mocks.d.ts @@ -237,5 +237,6 @@ declare module angular { /////////////////////////////////////////////////////////////////////////////// // functions attached to global object (window) /////////////////////////////////////////////////////////////////////////////// -declare var module: (...modules: any[]) => any; +//Use `angular.mock.module` instead of `module`, as `module` conflicts with commonjs. +//declare var module: (...modules: any[]) => any; declare var inject: angular.IInjectStatic; diff --git a/bardjs/bardjs-tests.ts b/bardjs/bardjs-tests.ts index b033ffe3c..71671b23e 100644 --- a/bardjs/bardjs-tests.ts +++ b/bardjs/bardjs-tests.ts @@ -39,7 +39,7 @@ module bardTests { var myService: MyService; var $rootScope: angular.IRootScopeService; - beforeEach(module(bard.$httpBackend, 'myModule')); + beforeEach(angular.mock.module(bard.$httpBackend, 'myModule')); beforeEach(inject(function(_myService_: MyService, _$rootScope_: angular.IRootScopeService) { myService = _myService_; @@ -63,7 +63,7 @@ module bardTests { function test_$q() { var myService: MyService; - beforeEach(module(bard.$q, bard.$httpBackend, 'myModule')); + beforeEach(angular.mock.module(bard.$q, bard.$httpBackend, 'myModule')); beforeEach(inject(function(_myService_: MyService) { myService = _myService_; @@ -139,7 +139,7 @@ module bardTests { * bard.fakeLogger */ function test_fakeLogger() { - beforeEach(module('myModule', bard.fakeLogger)); + beforeEach(angular.mock.module('myModule', bard.fakeLogger)); //// beforeEach(bard.appModule('myModule', bard.fakeLogger)); //// @@ -150,7 +150,7 @@ module bardTests { * bard.fakeRouteHelperProvider */ function test_fakeRouteHelperProvider() { - beforeEach(module('myModule', bard.fakeRouteHelperProvider)); + beforeEach(angular.mock.module('myModule', bard.fakeRouteHelperProvider)); //// beforeEach(bard.appModule('myModule', bard.fakeRouteHelperProvider)); //// @@ -161,7 +161,7 @@ module bardTests { * bard.fakeRouteProvider */ function test_fakeRouteProvider() { - beforeEach(module('myModule', bard.fakeRouteProvider)); + beforeEach(angular.mock.module('myModule', bard.fakeRouteProvider)); //// beforeEach(bard.appModule('myModule', bard.fakeRouteProvider)); //// @@ -172,7 +172,7 @@ module bardTests { * bard.fakeStateProvider */ function test_fakeStateProvider() { - beforeEach(module('myModule', bard.fakeStateProvider)); + beforeEach(angular.mock.module('myModule', bard.fakeStateProvider)); //// beforeEach(bard.appModule('myModule', bard.fakeStateProvider)); //// @@ -183,7 +183,7 @@ module bardTests { * bard.fakeToastr */ function test_fakeToastr() { - beforeEach(module('myModule', bard.fakeToastr)); + beforeEach(angular.mock.module('myModule', bard.fakeToastr)); //// beforeEach(bard.appModule('myModule', bard.fakeToastr)); //// From d4a0660d7174dfa67ff1c983fd0d4001220e96c3 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Thu, 20 Aug 2015 01:04:01 +0500 Subject: [PATCH 084/345] lodash: changed _.isRegExp() method --- lodash/lodash-tests.ts | 8 ++++++-- lodash/lodash.d.ts | 27 +++++++++++++++++---------- 2 files changed, 23 insertions(+), 12 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 2cbec6853..62d17bbe0 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1168,6 +1168,12 @@ result = _(undefined).isNaN(); result = _.isNative(Array.prototype.push); result = _(Array.prototype.push).isNative(); +// _.isRegExp +result = _.isRegExp(any); +result = _(1).isRegExp(); +result = _([]).isRegExp(); +result = _({}).isRegExp(); + // _.isTypedArray result = _.isTypedArray([]); result = _([]).isTypedArray(); @@ -1427,8 +1433,6 @@ result = _.isPlainObject(new Stooge('moe', 40)); result = _.isPlainObject([1, 2, 3]); result = _.isPlainObject({ 'name': 'moe', 'age': 40 }); -result = _.isRegExp(/moe/); - result = _.isString('moe'); result = _.isUndefined(void 0); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index c088f5459..71c4a2ef0 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -6160,6 +6160,23 @@ declare module _ { isNative(): boolean; } + //_.isRegExp + interface LoDashStatic { + /** + * Checks if value is classified as a RegExp object. + * @param value The value to check. + * @return Returns true if value is correctly classified, else false. + */ + isRegExp(value?: any): boolean; + } + + interface LoDashWrapperBase { + /** + * see _.isRegExp + */ + isRegExp(): boolean; + } + //_.isTypedArray interface LoDashStatic { /** @@ -7036,16 +7053,6 @@ declare module _ { isPlainObject(value?: any): boolean; } - //_.isRegExp - interface LoDashStatic { - /** - * Checks if value is a regular expression. - * @param value The value to check. - * @return True if the value is a regular expression, else false. - **/ - isRegExp(value?: any): boolean; - } - //_.isString interface LoDashStatic { /** From 4d2ad3d1b3a5b8890d68ab370ad78dbaf723d914 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Wed, 19 Aug 2015 05:40:51 +0500 Subject: [PATCH 085/345] lodash: changed _.isArray() method --- lodash/lodash-tests.ts | 9 ++++++--- lodash/lodash.d.ts | 27 +++++++++++++++++---------- 2 files changed, 23 insertions(+), 13 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 2cbec6853..a3728d7f2 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1139,6 +1139,12 @@ result = _(1).gte(2); result = _([]).gte(2); result = _({}).gte(2); +// _.isArray +result = _.isArray(any); +result = _(1).isArray(); +result = _([]).isArray(); +result = _({}).isArray(); + // _.isEmpty result = _.isEmpty([1, 2, 3]); result = _.isEmpty({}); @@ -1365,9 +1371,6 @@ result = _.invert({ 'first': 'moe', 'second': 'larry' }); (function (...args: any[]) { return _.isArguments(arguments); })(1, 2, 3); -(function () { return _.isArray(arguments); })(); -result = _.isArray([1, 2, 3]); - result = _.isBoolean(null); result = _.isDate(new Date()); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index c088f5459..61c99b913 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -6080,6 +6080,23 @@ declare module _ { gte(other: any): boolean; } + //_.isArray + interface LoDashStatic { + /** + * Checks if value is classified as an Array object. + * @param value The value to check. + * @return Returns true if value is correctly classified, else false. + **/ + isArray(value?: any): boolean; + } + + interface LoDashWrapperBase { + /** + * @see _.isArray + */ + isArray(): boolean; + } + //_.isEmpty interface LoDashStatic { /** @@ -6839,16 +6856,6 @@ declare module _ { isArguments(value?: any): boolean; } - //_.isArray - interface LoDashStatic { - /** - * Checks if value is an array. - * @param value The value to check. - * @return True if the value is an array, else false. - **/ - isArray(value?: any): boolean; - } - //_.isBoolean interface LoDashStatic { /** From 8f3167dc9f512956db10a3ba4524978f64d1aeac Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Thu, 20 Aug 2015 01:20:35 +0500 Subject: [PATCH 086/345] lodash: changed _.deburr() method --- lodash/lodash-tests.ts | 4 ++++ lodash/lodash.d.ts | 22 +++++++++++++++++++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 2cbec6853..c3e378c11 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1652,7 +1652,11 @@ result = _.uniqueId(); result = _.camelCase('Foo Bar'); result = _.capitalize('fred'); + +// _.deburr result = _.deburr('déjà vu'); +result = _('déjà vu').deburr(); + result = _.endsWith('abc', 'c'); // _.escape diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index c088f5459..506c3c47b 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -7441,7 +7441,27 @@ declare module _ { interface LoDashStatic { camelCase(str?: string): string; capitalize(str?: string): string; - deburr(str?: string): string; + } + + //_.deburr + interface LoDashStatic { + /** + * Deburrs string by converting latin-1 supplementary letters to basic latin letters and removing combining + * diacritical marks. + * @param string The string to deburr. + * @return Returns the deburred string. + */ + deburr(string?: string): string; + } + + interface LoDashWrapper { + /** + * @see _.deburr + */ + deburr(): string; + } + + interface LoDashStatic { endsWith(str?: string, target?: string, position?: number): boolean; } From d34f2fd473602067925a4304e350e2378767e2d7 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Thu, 20 Aug 2015 01:33:02 +0500 Subject: [PATCH 087/345] lodash: changed _.isUndefined() method --- lodash/lodash-tests.ts | 8 ++++++-- lodash/lodash.d.ts | 27 +++++++++++++++++---------- 2 files changed, 23 insertions(+), 12 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 2cbec6853..e37c827ed 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1172,6 +1172,12 @@ result = _(Array.prototype.push).isNative(); result = _.isTypedArray([]); result = _([]).isTypedArray(); +// _.isUndefined +result = _.isUndefined(any); +result = _(1).isUndefined(); +result = _([]).isUndefined(); +result = _({}).isUndefined(); + // _.lt result = _.lt(1, 2); result = _(1).lt(2); @@ -1431,8 +1437,6 @@ result = _.isRegExp(/moe/); result = _.isString('moe'); -result = _.isUndefined(void 0); - result = _.keys({ 'one': 1, 'two': 2, 'three': 3 }); result = _({ 'one': 1, 'two': 2, 'three': 3 }).keys().value(); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index c088f5459..2c2220238 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -6177,6 +6177,23 @@ declare module _ { isTypedArray(): boolean; } + //_.isUndefined + interface LoDashStatic { + /** + * Checks if value is undefined. + * @param value The value to check. + * @return Returns true if value is undefined, else false. + **/ + isUndefined(value: any): boolean; + } + + interface LoDashWrapperBase { + /** + * see _.isUndefined + */ + isUndefined(): boolean; + } + //_.lt interface LoDashStatic { /** @@ -7056,16 +7073,6 @@ declare module _ { isString(value?: any): boolean; } - //_.isUndefined - interface LoDashStatic { - /** - * Checks if value is undefined. - * @param value The value to check. - * @return True if the value is undefined, else false. - **/ - isUndefined(value?: any): boolean; - } - //_.keys interface LoDashStatic { /** From 46dc2e2b3d4cd73e7d80235608da3b69bee5e449 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Wed, 19 Aug 2015 05:54:51 +0500 Subject: [PATCH 088/345] lodash: changed _.startsWith() method --- lodash/lodash-tests.ts | 5 +++++ lodash/lodash.d.ts | 20 +++++++++++++++++++- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 2cbec6853..c8b386a7e 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1683,7 +1683,12 @@ result = _.snakeCase('Foo Bar'); result = _('Foo Bar').snakeCase(); result = _.startCase('--foo-bar'); + +// _.startsWith result = _.startsWith('abc', 'a'); +result = _.startsWith('abc', 'a', 1); +result = _('abc').startsWith('a'); +result = _('abc').startsWith('a', 1); // _.trim result = _.trim(); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index c088f5459..ecbcc05f2 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -7530,7 +7530,25 @@ declare module _ { interface LoDashStatic { startCase(str?: string): string; - startsWith(str?: string, target?: string, position?: number): boolean; + } + + //_.startsWith + interface LoDashStatic { + /** + * Checks if string starts with the given target string. + * @param string The string to search. + * @param target The string to search for. + * @param position The position to search from. + * @return Returns true if string starts with target, else false. + */ + startsWith(string?: string, target?: string, position?: number): boolean; + } + + interface LoDashWrapper { + /** + * @see _.startsWith + */ + startsWith(target?: string, position?: number): boolean; } //_.trim From 763b5865d4d69da428f3ad65258d7b31be1e7058 Mon Sep 17 00:00:00 2001 From: Andrew F Date: Wed, 19 Aug 2015 13:35:56 -0700 Subject: [PATCH 089/345] Add tests and additional definitions --- segment-analytics/segment-analytics-tests.ts | 211 +++++++++++++++++++ segment-analytics/segment-analytics.d.ts | 84 +++++--- 2 files changed, 265 insertions(+), 30 deletions(-) create mode 100755 segment-analytics/segment-analytics-tests.ts diff --git a/segment-analytics/segment-analytics-tests.ts b/segment-analytics/segment-analytics-tests.ts new file mode 100755 index 000000000..56df14e28 --- /dev/null +++ b/segment-analytics/segment-analytics-tests.ts @@ -0,0 +1,211 @@ +/// +/// + +// Some random vals to use + +// Use for page props or user traits +var testProps = { + favoriteCheese: "brie", + favoritePie: "apple" +}; + +// Segment options +var testOpts = { + integrations: { + Mixpanel: true + } +}; + +var testCb = function() {}; + + +///////////// + +function test_identify() { + // userId and traits + analytics.identify('1e810c197e', { + name: 'Bill Lumbergh', + email: 'bill@initech.com' + }); + + // No traits + analytics.identify('1e810c197e'); + + // No userId + analytics.identify({ + email: 'bill@initech.com', + newsletter: true, + industry: 'Technology' + }); + + // Callback + analytics.identify('1e810c197e', function(){ + // Do something after the identify request has been sent, like + // submit a form or redirect to a new page. + }); + + // With options + analytics.identify('1e810c197e', testProps, testOpts); + + // All args + analytics.identify('1e810c197e', testProps, testOpts, testCb); +} + +function testTrack() { + analytics.track('Signed Up'); + + analytics.track('Signed Up', { + plan: 'Startup', + source: 'Analytics Academy' + }); + + analytics.track('Signed Up', testProps, testOpts, testCb); +} + +function testPage() { + analytics.page('Signup'); + + analytics.page('Pricing', { + title: 'Segment Pricing', + url: 'https://segment.com/pricing', + path: '/pricing', + referrer: 'https://segment.com' + }); + + analytics.page('Category', 'Signup'); + + analytics.page('Signup', testProps, testOpts, testCb); +} + +function testAlias() { + analytics.alias('019mr8mf4r'); + analytics.alias('newId', 'oldId'); + analytics.alias('019mr8mf4r', testOpts, testCb); +} + +function testGroup() { + analytics.group('test_group'); + analytics.group('test_group', { + name: "Initech", + industry: "Technology", + employees: 329 + }); + analytics.group('test_group', testProps, testOpts, testCb); +} + +function testTrackLink() { + var link1 = document.getElementById('free-trial-link'); + var link2 = document.getElementById('free-trial-link-2'); + var links = $('.free-trial-links'); + + analytics.trackLink(link1, 'Clicked Free-Trial Link'); + analytics.trackLink(link1, 'Clicked Free-Trial Link', { + plan: 'Enterprise' + }); + + analytics.trackLink([link1, link2], 'Clicked Free-Trial Link', testProps); + analytics.trackLink(links, 'Clicked Free-Trial Link', testProps); + + // With function name and properties + analytics.trackLink(links, + function(elm) { + return String(elm); + }, + function(elm) { + return { + x: 123, + y: 456 + }; + }); +} + +function testTrackForm() { + var form1 = document.getElementById('signup-form'); + var form2 = document.getElementById('signin-form'); + var forms = $('.forms'); + + analytics.trackForm(form1, 'Signed up'); + analytics.trackForm(form1, 'Signed Up', { + plan: 'Premium', + revenue: 99.00 + }); + + analytics.trackForm([form1, form2], 'Clicked Free-Trial Link', testProps); + analytics.trackForm(forms, 'Clicked Free-Trial Link', testProps); + + // With function name and properties + analytics.trackForm(forms, + function(elm) { + return String(elm); + }, + function(elm) { + return { + x: 123, + y: 456 + }; + }); +} + +function testReady() { + analytics.ready(function(){ + ( window).mixpanel.set_config({ verbose: true }); + }); +} + +function testUserGroup() { + analytics.ready(function(){ + var user = analytics.user(); + var id = user.id(); + var traits = user.traits(); + }); + + analytics.ready(function(){ + var group = analytics.group(); + var id = group.id(); + var traits = group.traits(); + }); +} + +function testClearTraits() { + analytics.user().traits({}); + analytics.group().traits({}); +} + +function testResetLogout() { + analytics.reset(); +} + +function testAnonId() { + analytics.user().anonymousId(); + analytics.user().anonymousId('ABC-123-XYZ'); + + analytics.identify('123', { + gender: 'Male', + }, { + anonymousId: 'ABC-123-XYZ' + }); + + analytics.page({}, { anonymousId: 'ABC-123-XYZ' }); + + analytics.track('Clicked CTA', { + callToAction: 'Signup' + }, { + anonymousId: 'ABC-123-XYZ' + }); +} + +function testDebug() { + analytics.debug(); + analytics.debug(false); +} + +declare var bigdata: any; +function testEmitter() { + analytics.on('track', function(event, properties, options){ + bigdata.push(['recordEvent', event]); + }); +} + +function testTimeout() { + analytics.timeout(500); +} \ No newline at end of file diff --git a/segment-analytics/segment-analytics.d.ts b/segment-analytics/segment-analytics.d.ts index 1b8cc8bf5..f2de55846 100755 --- a/segment-analytics/segment-analytics.d.ts +++ b/segment-analytics/segment-analytics.d.ts @@ -3,37 +3,35 @@ // Definitions by: Andrew Fong // Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + declare module SegmentAnalytics { // Generic options object with integrations - interface SegmentOpts { - integrations?: Integrations; + interface SegmentOpts { + integrations?: any; anonymousId?: string; - }; + } // The actual analytics.js object - interface AnalyticsJS { + interface AnalyticsJS { /* Configure Segment with write key */ load(writeKey: string); /* The identify method is how you tie one of your users and their actions to a recognizable userId and traits. */ - identify(userId: string, traits?: Object, - options?: SegmentOpts, + identify(userId: string, traits?: Object, options?: SegmentOpts, callback?: () => void): void; identify(userId: string, traits: Object, callback?: () => void): void; identify(userId: string, callback?: () => void): void; - identify(traits?: Object, - options?: SegmentOpts, - callback?: () => void): void; - identify(traits?: Object, + identify(traits?: Object, options?: SegmentOpts, callback?: () => void): void; + identify(traits?: Object, callback?: () => void): void; identify(callback: () => void): void; /* The track method lets you record any actions your users perform. */ - track(event: string, properties?: Object, - options?: SegmentOpts, + track(event: string, properties?: Object, options?: SegmentOpts, callback?: () => void): void; track(event: string, properties?: Object, callback?: () => void): void; @@ -42,23 +40,19 @@ declare module SegmentAnalytics { /* The page method lets you record page views on your website, along with optional extra information about the page being viewed. */ page(category: string, name: string, properties?: Object, - options?: SegmentOpts, - callback?: () => void): void; + options?: SegmentOpts, callback?: () => void): void; page(name?: string, properties?: Object, - options?: SegmentOpts, - callback?: () => void): void; + options?: SegmentOpts, callback?: () => void): void; page(name?: string, properties?: Object, callback?: () => void): void; page(name?: string, callback?: () => void): void; - page(properties?: Object, - options?: SegmentOpts, + page(properties?: Object, options?: SegmentOpts, callback?: () => void): void; page(callback?: () => void): void; /* The group method associates an individual user with a group. The group - can a company, organization, account, project, team or any other name + can a company, organization, account, project, team or any other name you came up with for the same concept. */ - group(groupId: string, traits?: Object, - options?: SegemntOpts, + group(groupId: string, traits?: Object, options?: SegmentOpts, callback?: () => void): void; group(groupId: string, traits?: Object, callback?: () => void): void; group(groupId: string, callback?: () => void): void; @@ -70,39 +64,69 @@ declare module SegmentAnalytics { Some providers also don’t alias automatically for you when an anonymous user signs up (like Mixpanel), so you need to call alias manually right after sign up with their brand new userId. */ - alias(userId: string, previousId?: string, - options?: SegmentOpts, + alias(userId: string, previousId?: string, options?: SegmentOpts, callback?: () => void): void; alias(userId: string, previousId?: string, callback?: () => void): void; alias(userId: string, callback?: () => void): void; - alias(userId: string, options?: SegmentOpts, - callback?: () => void): void; + alias(userId: string, options?: SegmentOpts, callback?: () => void): void; /* trackLink is a helper that binds a track call to whenever a link is clicked. Usually the page would change before you could call track, but with trackLink a small timeout is inserted to give the track call enough time to fire. */ - trackLink(elements: Element|Element[], event: string, properties?: Object); + trackLink(elements: JQuery|Element[]|Element, + event: string|{ (elm: Element): string }, + properties?: Object|{ (elm: Element): Object }); /* trackForm is a helper that binds a track call to a form submission. Usually the page would change before you could call track, but with trackForm a small timeout is inserted to give the track call enough time to fire. */ - trackForm(elements: Element|Element[], event: string, properties?: Object); + trackForm(elements: JQuery|Element[]|Element, + event: string|{ (Element): string }, + properties?: Object|{ (elm: Element): Object }); /* The ready method allows you to pass in a callback that will be called as soon as all of your enabled integrations have loaded. It’s like jQuery’s ready method, except for integrations. */ ready(callback: () => void); - // Cookie-based user object + /* If you need to clear the user and group id and traits we’ve added a + reset function that is most commonly used when your identified users + logout of your application. */ + reset(); + + /* Once Analytics.js loaded, you can retrieve information about the + currently identified user or group like their id and traits. */ user(): { id(): string; logout(): void; reset(): void; anonymousId(newId?: string): string; - }; + traits(newTraits?: Object): void; + } + + group(): { + id(): string; + traits(newTraits?: Object): void; + } + + /* Analytics.js has a debug mode that logs helpful messages to the + console. */ + debug(state?: boolean): void; + + /* The global analytics object emits events whenever you call alias, group, + identify, track or page. That way you can listen to those events and run + your own custom code. */ + on(event: string, + callback: { + (event: string, properties: Object, options: SegmentOpts): void + }); + + /* You can extend the length (in milliseconds) of the method callbacks and + helpers */ + timeout(milliseconds: number); } } -declare var analytics: SegmentAnalytics.AnalyticsJS; +declare var analytics: SegmentAnalytics.AnalyticsJS; From fdb85c2f307fb20458b640de55bb3a9b594a3fbc Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Mon, 17 Aug 2015 20:09:46 +0500 Subject: [PATCH 090/345] lodash: added _.attempt() method --- lodash/lodash-tests.ts | 16 +++++++++++++++- lodash/lodash.d.ts | 24 +++++++++++++++++++++--- 2 files changed, 36 insertions(+), 4 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 2cbec6853..8922569da 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -91,6 +91,12 @@ var result: any; var any: any; +interface TResult { + a: number; + b: string; + c: boolean; +} + // _.MapCache var testMapCache: _.MapCache; result = <(key: string) => boolean>testMapCache.delete; @@ -1539,9 +1545,17 @@ result = _(new TestValueIn()).valuesIn().value(); // → [1, 2, 3] /********** -* Utilities * +* Utility * ***********/ +// _.attempt +interface TestAttemptFn { + (): TResult; +} +var testAttempFn: TestAttemptFn; +result = _.attempt(testAttempFn); +result = _(testAttempFn).attempt(); + result = <{ name: string }>_.identity({ 'name': 'moe' }); _.mixin({ diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index c088f5459..6146bc97d 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -7614,9 +7614,27 @@ declare module _ { words(str?: string, pattern?: string|RegExp): string[]; } - /************* - * Utilities * - *************/ + /*********** + * Utility * + ***********/ + + //_.attempt + interface LoDashStatic { + /** + * Attempts to invoke func, returning either the result or the caught error object. Any additional arguments + * are provided to func when it’s invoked. + * @param func The function to attempt. + * @return Returns the func result or error object. + */ + attempt(func: (...args: any[]) => TResult): TResult|Error; + } + + interface LoDashObjectWrapper { + /** + * @see _.attempt + */ + attempt(): TResult|Error; + } //_.identity interface LoDashStatic { From 496f751d45a1f63f3dc36171427cb658ea1d666f Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Tue, 18 Aug 2015 21:16:18 +0500 Subject: [PATCH 091/345] lodash: changed _.isFinite() method --- lodash/lodash-tests.ts | 12 ++++++------ lodash/lodash.d.ts | 31 ++++++++++++++++++------------- 2 files changed, 24 insertions(+), 19 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 2cbec6853..c2f0b3f2d 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1147,6 +1147,12 @@ result = _([1, 2, 3]).isEmpty(); result = _({}).isEmpty(); result = _('').isEmpty(); +// _.isFinite +result = _.isFinite(any); +result = _(1).isFinite(); +result = _([]).isFinite(); +result = _({}).isFinite(); + // _.isMatch var testIsMatchCustiomizerFn: (value: any, other: any, indexOrKey: number|string) => boolean; result = _.isMatch({}, {}); @@ -1399,12 +1405,6 @@ result = _(testEqArray).isEqual(testEqOtherArray, testEqCustomizerFn); result = _.eq(testEqArray, testEqOtherArray, testEqCustomizerFn); result = _(testEqArray).eq(testEqOtherArray, testEqCustomizerFn); -result = _.isFinite(-101); -result = _.isFinite('10'); -result = _.isFinite(true); -result = _.isFinite(''); -result = _.isFinite(Infinity); - result = _.isFunction(_); result = _.isNull(null); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index c088f5459..9e4834df8 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -6098,6 +6098,24 @@ declare module _ { isEmpty(): boolean; } + //_.isFinite + interface LoDashStatic { + /** + * Checks if value is a finite primitive number. + * Note: This method is based on Number.isFinite. + * @param value The value to check. + * @return Returns true if value is a finite number, else false. + **/ + isFinite(value?: any): boolean; + } + + interface LoDashWrapperBase { + /** + * @see _.isFinite + */ + isFinite(): boolean; + } + //_.isMatch interface isMatchCustomizer { (value: any, other: any, indexOrKey?: number|string): boolean; @@ -6970,19 +6988,6 @@ declare module _ { thisArg?: any): boolean; } - //_.isFinite - interface LoDashStatic { - /** - * Checks if value is, or can be coerced to, a finite number. - * - * Note: This is not the same as native isFinite which will return true for booleans and empty - * strings. See http://es5.github.io/#x15.1.2.5. - * @param value The value to check. - * @return True if the value is finite, else false. - **/ - isFinite(value?: any): boolean; - } - //_.isFunction interface LoDashStatic { /** From 01730f3e2796bae492464e00c9591ef8c10f0aca Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Tue, 18 Aug 2015 20:47:46 +0500 Subject: [PATCH 092/345] lodash: changed _.pad(), _.padLeft() and _.padRight() methods --- lodash/lodash-tests.ts | 19 +++++++++++++ lodash/lodash.d.ts | 64 ++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 80 insertions(+), 3 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 2cbec6853..4008f23f7 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1664,12 +1664,31 @@ result = _.escapeRegExp('[lodash](https://lodash.com/)'); result = _('[lodash](https://lodash.com/)').escapeRegExp(); result = _.kebabCase('Foo Bar'); + +// _.pad +result = _.pad('abd'); result = _.pad('abc', 8); result = _.pad('abc', 8, '_-'); +result = _('abc').pad(); +result = _('abc').pad(8); +result = _('abc').pad(8, '_-'); + +// _.padLeft +result = _.padLeft('abc'); result = _.padLeft('abc', 6); result = _.padLeft('abc', 6, '_-'); +result = _('abc').padLeft(); +result = _('abc').padLeft(6); +result = _('abc').padLeft(6, '_-'); + +// _.padRight +result = _.padRight('abc'); result = _.padRight('abc', 6); result = _.padRight('abc', 6, '_-'); +result = _('abc').padRight(); +result = _('abc').padRight(6); +result = _('abc').padRight(6, '_-'); + result = _.repeat('*', 3); // _.parseInt diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index c088f5459..6eb4a69c6 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -7482,9 +7482,67 @@ declare module _ { interface LoDashStatic { kebabCase(str?: string): string; - pad(str?: string, length?: number, chars?: string): string; - padLeft(str?: string, length?: number, chars?: string): string; - padRight(str?: string, length?: number, chars?: string): string; + } + + interface LoDashStatic { + /** + * + * @param string The string to pad. + * @param length The padding length. + * @param chars The string used as padding. + * @return Returns the padded string. + */ + pad(string?: string, length?: number, chars?: string): string; + } + + //_.pad + interface LoDashWrapper { + /** + * @see _.pad + */ + pad(length?: number, chars?: string): string; + } + + //_.padLeft + interface LoDashStatic { + /** + * Pads string on the left side if it’s shorter than length. Padding characters are truncated if they exceed + * length. + * @param string The string to pad. + * @param length The padding length. + * @param chars The string used as padding. + * @return Returns the padded string. + */ + padLeft(string?: string, length?: number, chars?: string): string; + } + + //_.padLeft + interface LoDashWrapper { + /** + * @see _.padLeft + */ + padLeft(length?: number, chars?: string): string; + } + + //_.padRight + interface LoDashStatic { + /** + * Pads string on the right side if it’s shorter than length. Padding characters are truncated if they exceed + * length. + * @param string The string to pad. + * @param length The padding length. + * @param chars The string used as padding. + * @return Returns the padded string. + */ + padRight(string?: string, length?: number, chars?: string): string; + } + + //_.padRight + interface LoDashWrapper { + /** + * @see _.padRight + */ + padRight(length?: number, chars?: string): string; } //_.parseInt From 68b97ecc7d1d15f64673aa2ab092ebb283d613fc Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Tue, 11 Aug 2015 22:13:13 +0500 Subject: [PATCH 093/345] angularjs: added Deferred tests --- angularjs/angular-tests.ts | 42 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index 10d806217..01b8eff26 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -325,6 +325,48 @@ httpFoo.success((data, status, headers, config) => { }); +// Deferred signature tests +module TestDeferred { + var any: any; + + interface TResult { + a: number; + b: string; + c: boolean; + } + var tResult: TResult; + + var deferred: angular.IDeferred; + + // deferred.resolve + { + let result: void; + result = deferred.resolve(); + result = deferred.resolve(tResult); + } + + // deferred.reject + { + let result: void; + result = deferred.reject(); + result = deferred.reject(any); + } + + // deferred.notify + { + let result: void; + result = deferred.notify(); + result = deferred.notify(any); + } + + // deferred.promise + { + let result: angular.IPromise; + result = deferred.promise; + } +} + + // Promise signature tests module TestPromise { var result: any; From 7652914a5b38b44434f1f4173f377a05cb8f2cfd Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Tue, 11 Aug 2015 21:51:19 +0500 Subject: [PATCH 094/345] angularjs: changed $timeout signature, added tests --- angularjs/angular-tests.ts | 39 ++++++++++++++++++++++++++++++++++++++ angularjs/angular.d.ts | 5 +++-- 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index 10d806217..a9f77b97e 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -381,6 +381,45 @@ var scope: ng.IScope = element.scope(); var isolateScope: ng.IScope = element.isolateScope(); +// $timeout signature tests +module TestTimeout { + interface TResult { + a: number; + b: string; + c: boolean; + } + var fnTResult: (...args: any[]) => TResult; + var promiseAny: angular.IPromise; + var $timeout: angular.ITimeoutService; + + // $timeout + { + let result: angular.IPromise; + result = $timeout(); + } + { + let result: angular.IPromise; + result = $timeout(1); + result = $timeout(1, true); + } + { + let result: angular.IPromise; + result = $timeout(fnTResult); + result = $timeout(fnTResult, 1); + result = $timeout(fnTResult, 1, true); + result = $timeout(fnTResult, 1, true, 1); + result = $timeout(fnTResult, 1, true, 1, ''); + result = $timeout(fnTResult, 1, true, 1, '', true); + } + + // $timeout.cancel + { + let result: boolean; + result = $timeout.cancel(); + result = $timeout.cancel(promiseAny); + } +} + function test_IAttributes(attributes: ng.IAttributes){ return attributes; diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 17c0c9384..0dc9ca2ca 100644 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -725,8 +725,9 @@ declare module angular { // see http://docs.angularjs.org/api/ng.$timeout /////////////////////////////////////////////////////////////////////////// interface ITimeoutService { - (func: (...args: any[]) => T, delay?: number, invokeApply?: boolean): IPromise; - cancel(promise: IPromise): boolean; + (delay?: number, invokeApply?: boolean): IPromise; + (fn: (...args: any[]) => T, delay?: number, invokeApply?: boolean, ...args: any[]): IPromise; + cancel(promise?: IPromise): boolean; } /////////////////////////////////////////////////////////////////////////// From 68374669bf0ef6eb20d5aff2ea4d96dca83e4621 Mon Sep 17 00:00:00 2001 From: Andrew F Date: Wed, 19 Aug 2015 13:42:59 -0700 Subject: [PATCH 095/345] load test; fix implicit any errors --- segment-analytics/segment-analytics-tests.ts | 5 +++++ segment-analytics/segment-analytics.d.ts | 16 ++++++++-------- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/segment-analytics/segment-analytics-tests.ts b/segment-analytics/segment-analytics-tests.ts index 56df14e28..b876ea1be 100755 --- a/segment-analytics/segment-analytics-tests.ts +++ b/segment-analytics/segment-analytics-tests.ts @@ -21,6 +21,10 @@ var testCb = function() {}; ///////////// +function test_load() { + analytics.load("YOUR_WRITE_KEY"); +} + function test_identify() { // userId and traits analytics.identify('1e810c197e', { @@ -63,6 +67,7 @@ function testTrack() { } function testPage() { + analytics.page(); analytics.page('Signup'); analytics.page('Pricing', { diff --git a/segment-analytics/segment-analytics.d.ts b/segment-analytics/segment-analytics.d.ts index f2de55846..3cdfbbc56 100755 --- a/segment-analytics/segment-analytics.d.ts +++ b/segment-analytics/segment-analytics.d.ts @@ -17,7 +17,7 @@ declare module SegmentAnalytics { interface AnalyticsJS { /* Configure Segment with write key */ - load(writeKey: string); + load(writeKey: string): void; /* The identify method is how you tie one of your users and their actions to a recognizable userId and traits. */ @@ -76,25 +76,25 @@ declare module SegmentAnalytics { time to fire. */ trackLink(elements: JQuery|Element[]|Element, event: string|{ (elm: Element): string }, - properties?: Object|{ (elm: Element): Object }); + properties?: Object|{ (elm: Element): Object }): void; /* trackForm is a helper that binds a track call to a form submission. Usually the page would change before you could call track, but with trackForm a small timeout is inserted to give the track call enough time to fire. */ trackForm(elements: JQuery|Element[]|Element, - event: string|{ (Element): string }, - properties?: Object|{ (elm: Element): Object }); + event: string|{ (elm: Element): string }, + properties?: Object|{ (elm: Element): Object }): void; /* The ready method allows you to pass in a callback that will be called as soon as all of your enabled integrations have loaded. It’s like jQuery’s ready method, except for integrations. */ - ready(callback: () => void); + ready(callback: () => void): void; /* If you need to clear the user and group id and traits we’ve added a reset function that is most commonly used when your identified users logout of your application. */ - reset(); + reset(): void; /* Once Analytics.js loaded, you can retrieve information about the currently identified user or group like their id and traits. */ @@ -121,11 +121,11 @@ declare module SegmentAnalytics { on(event: string, callback: { (event: string, properties: Object, options: SegmentOpts): void - }); + }): void; /* You can extend the length (in milliseconds) of the method callbacks and helpers */ - timeout(milliseconds: number); + timeout(milliseconds: number): void; } } From 7ed20bd0cf6438bc4590a765c69073212a7c5de9 Mon Sep 17 00:00:00 2001 From: MugeSo Date: Thu, 20 Aug 2015 12:13:36 +0900 Subject: [PATCH 096/345] rsmq-worker: fix contributor name --- rsmq-worker/rsmq-worker.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rsmq-worker/rsmq-worker.d.ts b/rsmq-worker/rsmq-worker.d.ts index 6af1564e1..5d4f9079a 100644 --- a/rsmq-worker/rsmq-worker.d.ts +++ b/rsmq-worker/rsmq-worker.d.ts @@ -1,6 +1,6 @@ // Type definitions for rsmq-worker 0.3.5 // Project: http://smrchy.github.io/rsmq/rsmq-worker/ -// Definitions by: Qubo +// Definitions by: TANAKA Koichi // Definitions: https://github.com/borisyankov/DefinitelyTyped /// From aa7e750ff747a0685378a7db12fede44a07877ef Mon Sep 17 00:00:00 2001 From: TimChen44 Date: Thu, 20 Aug 2015 16:22:03 +0800 Subject: [PATCH 097/345] Update ionic.d.ts Fix IonicActionSheetOptions bugs --- ionic/ionic.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ionic/ionic.d.ts b/ionic/ionic.d.ts index eba0ef6d4..b1b215217 100644 --- a/ionic/ionic.d.ts +++ b/ionic/ionic.d.ts @@ -16,7 +16,7 @@ declare module ionic { cancelText?: string; destructiveText?: string; cancel?: ()=>any; - buttonClicked?: ()=>any; + buttonClicked?: (index: any)=>any; destructiveButtonClicked?: ()=>any; cancelOnStateChange?: boolean; cssClass?: string; From e92bf375381c8e3b8717a2b714f303840856021c Mon Sep 17 00:00:00 2001 From: Rogier Schouten Date: Thu, 20 Aug 2015 10:56:30 +0200 Subject: [PATCH 098/345] Update Sinon typings for Sinon 1.16.0 Add setSystemTime() method --- sinon/sinon-tests.ts | 6 ++++++ sinon/sinon.d.ts | 17 +++++++++++++++-- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/sinon/sinon-tests.ts b/sinon/sinon-tests.ts index ca916788d..3e6f72086 100644 --- a/sinon/sinon-tests.ts +++ b/sinon/sinon-tests.ts @@ -109,3 +109,9 @@ testSix(); testSeven(); testEight(); testNine(); + +var clock: Sinon.SinonFakeTimers = sinon.useFakeTimers(); +clock.setSystemTime(1000); +clock.setSystemTime(new Date()); + + diff --git a/sinon/sinon.d.ts b/sinon/sinon.d.ts index 6440dda90..cdb316976 100644 --- a/sinon/sinon.d.ts +++ b/sinon/sinon.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Sinon 1.8.1 +// Type definitions for Sinon 1.16.0 // Project: http://sinonjs.org/ // Definitions by: William Sears // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -181,7 +181,20 @@ declare module Sinon { Date(year: number, month: number, day: number, hour: number, minute: number, second: number): Date; Date(year: number, month: number, day: number, hour: number, minute: number, second: number, ms: number): Date; restore(): void; - } + + /** + * Simulate the user changing the system clock while your program is running. It changes the 'now' timestamp + * without affecting timers, intervals or immediates. + * @param now The new 'now' in unix milliseconds + */ + setSystemTime(now: number): void; + /** + * Simulate the user changing the system clock while your program is running. It changes the 'now' timestamp + * without affecting timers, intervals or immediates. + * @param now The new 'now' as a JavaScript Date + */ + setSystemTime(date: Date): void; + } interface SinonFakeTimersStatic { (): SinonFakeTimers; From 8a49a6fc1427593898005eda6072da06333fccf1 Mon Sep 17 00:00:00 2001 From: Paul Jolly Date: Thu, 20 Aug 2015 10:17:13 +0100 Subject: [PATCH 099/345] Add type parameters to channel definitions --- postal/postal.d.ts | 62 +++++++++++++++++++++++----------------------- 1 file changed, 31 insertions(+), 31 deletions(-) diff --git a/postal/postal.d.ts b/postal/postal.d.ts index e1bad48cc..a23e14d87 100644 --- a/postal/postal.d.ts +++ b/postal/postal.d.ts @@ -15,36 +15,36 @@ interface IResolver { purge(options?: {topic?: string, binding?: string, compact?: boolean}): void; } -interface ICallback { - (data: any, envelope: IEnvelope): void +interface ICallback { + (data: T, envelope: IEnvelope): void } -interface ISubscriptionDefinition { +interface ISubscriptionDefinition { channel: string; topic: string; - callback: ICallback; + callback: ICallback; // after and before lack documentation - constraint(predicateFn: (data: any, envelope: IEnvelope) => boolean): ISubscriptionDefinition; - constraints(predicateFns: ((data: any, envelope: IEnvelope) => boolean)[]): ISubscriptionDefinition; - context(theContext: any): ISubscriptionDefinition; - debounce(interval: number): ISubscriptionDefinition; - defer(): ISubscriptionDefinition; - delay(waitTime: number): ISubscriptionDefinition; - disposeAfter(maxCalls: number): ISubscriptionDefinition; - distinct(): ISubscriptionDefinition; - distinctUntilChanged(): ISubscriptionDefinition; - logError(): ISubscriptionDefinition; - once(): ISubscriptionDefinition; - throttle(interval: number): ISubscriptionDefinition; - subscribe(callback: ICallback): ISubscriptionDefinition; + constraint(predicateFn: (data: T, envelope: IEnvelope) => boolean): ISubscriptionDefinition; + constraints(predicateFns: ((data: T, envelope: IEnvelope) => boolean)[]): ISubscriptionDefinition; + context(theContext: any): ISubscriptionDefinition; + debounce(interval: number): ISubscriptionDefinition; + defer(): ISubscriptionDefinition; + delay(waitTime: number): ISubscriptionDefinition; + disposeAfter(maxCalls: number): ISubscriptionDefinition; + distinct(): ISubscriptionDefinition; + distinctUntilChanged(): ISubscriptionDefinition; + logError(): ISubscriptionDefinition; + once(): ISubscriptionDefinition; + throttle(interval: number): ISubscriptionDefinition; + subscribe(callback: ICallback): ISubscriptionDefinition; unsubscribe(): void; } -interface IEnvelope { +interface IEnvelope { topic: string; - data?: any; + data?: T; /*Uses DEFAULT_CHANNEL if no channel is provided*/ channel?: string; @@ -53,10 +53,10 @@ interface IEnvelope { } -interface IChannelDefinition { - subscribe(topic: string, callback: ICallback): ISubscriptionDefinition; +interface IChannelDefinition { + subscribe(topic: string, callback: ICallback): ISubscriptionDefinition; - publish(topic: string, data?: any): void; + publish(topic: string, data?: T): void; channel: string; } @@ -73,24 +73,24 @@ interface IDestinationArg { interface IPostal { subscriptions: {}; - wiretaps: ICallback[]; + wiretaps: ICallback[]; - addWireTap(callback: ICallback): () => void; + addWireTap(callback: ICallback): () => void; - channel(name?: string): IChannelDefinition; + channel(name?: string): IChannelDefinition; - getSubscribersFor(): ISubscriptionDefinition[]; - getSubscribersFor(options: {channel?: string, topic?: string, context?: any}): ISubscriptionDefinition[]; - getSubscribersFor(predicateFn: (sub: ISubscriptionDefinition) => boolean): ISubscriptionDefinition[]; + getSubscribersFor(): ISubscriptionDefinition[]; + getSubscribersFor(options: {channel?: string, topic?: string, context?: any}): ISubscriptionDefinition[]; + getSubscribersFor(predicateFn: (sub: ISubscriptionDefinition) => boolean): ISubscriptionDefinition[]; linkChannels(source: ISourceArg | ISourceArg[], destination: IDestinationArg | IDestinationArg[]): void; - publish(envelope: IEnvelope): void; + publish(envelope: IEnvelope): void; reset(): void; - subscribe(options: {channel?: string, topic: string, callback: ICallback}): ISubscriptionDefinition; - unsubscribe(sub: ISubscriptionDefinition): void; + subscribe(options: {channel?: string, topic: string, callback: ICallback}): ISubscriptionDefinition; + unsubscribe(sub: ISubscriptionDefinition): void; unsubscribeFor(): void; unsubscribeFor(options: {channel?: string, topic?: string, context?: any}): void; From 964d8d647001b5277f5a0309fdade125e224f829 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20Corbi=C3=A8re?= Date: Thu, 20 Aug 2015 11:40:54 +0200 Subject: [PATCH 100/345] [gulp-changed] Add type definitions --- gulp-changed/gulp-changed-tests.ts | 19 ++++++++++ gulp-changed/gulp-changed.d.ts | 60 ++++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+) create mode 100644 gulp-changed/gulp-changed-tests.ts create mode 100644 gulp-changed/gulp-changed.d.ts diff --git a/gulp-changed/gulp-changed-tests.ts b/gulp-changed/gulp-changed-tests.ts new file mode 100644 index 000000000..ae6104eed --- /dev/null +++ b/gulp-changed/gulp-changed-tests.ts @@ -0,0 +1,19 @@ +/// +/// +/// + +import * as gulp from "gulp"; +import changed = require("gulp-changed"); +import minifyHtml = require("gulp-minify-html"); + +// Without options +gulp.src("*.html") + .pipe(changed("build")) + .pipe(minifyHtml()) + .pipe(gulp.dest("build")); + +// Without some options +gulp.src("*.html") + .pipe(changed("build", { hasChanged: changed.compareSha1Digest })) + .pipe(minifyHtml()) + .pipe(gulp.dest("build")); diff --git a/gulp-changed/gulp-changed.d.ts b/gulp-changed/gulp-changed.d.ts new file mode 100644 index 000000000..f2a3e0d64 --- /dev/null +++ b/gulp-changed/gulp-changed.d.ts @@ -0,0 +1,60 @@ +// Type definitions for gulp-changed +// Project: https://github.com/sindresorhus/gulp-changed +// Definitions by: Thomas Corbière +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare module "gulp-changed" +{ + import { Transform } from "stream"; + import File = require("vinyl"); + + interface IComparator + { + /** + * @param stream Should be used to queue sourceFile if it passes some comparison + * @param callback Should be called when done + * @param sourceFile File to operate on + * @param destPath Destination for sourceFile as an absolute path + */ + (stream: Transform, callback: Function, sourceFile: File, destPath: string): void; + } + + interface IDestination + { + (file: string|Buffer): string; + } + + interface IOptions + { + /** + * The working directory the folder is relative to. + * @default process.cwd() + */ + cwd?: string; + + /** + * Extension of the destination files. + */ + extension?: string; + + /** + * Function that determines whether the source file is different from the destination file. + * @default changed.compareLastModifiedTime + */ + hasChanged?: IComparator; + } + + interface IGulpChanged + { + (destination: string|IDestination, options?: IOptions): NodeJS.ReadWriteStream; + + compareLastModifiedTime: IComparator; + compareSha1Digest: IComparator; + } + + const changed: IGulpChanged; + export = changed; +} From a0357a3bb1934ef912b73d2042c7cd9abc5b30ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20Corbi=C3=A8re?= Date: Thu, 20 Aug 2015 12:28:13 +0200 Subject: [PATCH 101/345] [gulp-newer] Add type definitions --- gulp-newer/gulp-newer-tests.ts | 17 +++++++++++++ gulp-newer/gulp-newer.d.ts | 46 ++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 gulp-newer/gulp-newer-tests.ts create mode 100644 gulp-newer/gulp-newer.d.ts diff --git a/gulp-newer/gulp-newer-tests.ts b/gulp-newer/gulp-newer-tests.ts new file mode 100644 index 000000000..43f0c55cc --- /dev/null +++ b/gulp-newer/gulp-newer-tests.ts @@ -0,0 +1,17 @@ +/// +/// +/// + +import * as gulp from "gulp"; +import newer = require("gulp-newer"); +import minifyHtml = require("gulp-minify-html"); + +gulp.src("*.html") + .pipe(newer("build")) + .pipe(minifyHtml()) + .pipe(gulp.dest("build")); + +gulp.src("*.html") + .pipe(newer({ dest: "build" })) + .pipe(minifyHtml()) + .pipe(gulp.dest("build")); diff --git a/gulp-newer/gulp-newer.d.ts b/gulp-newer/gulp-newer.d.ts new file mode 100644 index 000000000..ca4fdc9a1 --- /dev/null +++ b/gulp-newer/gulp-newer.d.ts @@ -0,0 +1,46 @@ +// Type definitions for gulp-newer +// Project: https://github.com/tschaub/gulp-newer +// Definitions by: Thomas Corbière +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "gulp-newer" +{ + interface IOptions + { + /** + * Path to destination directory or file. + */ + dest: string; + + /** + * Source files will be matched to destination files with the provided extension. + */ + ext?: string; + + /** + * Map relative source paths to relative destination paths. + */ + map?: (relativePath: string) => string; + } + + interface IGulpNewer + { + /** + * Create a transform stream that passes through files whose modification time + * is more recent than the corresponding destination file's modification time. + * @param dest Path to destination directory or file. + */ + (dest: string): NodeJS.ReadWriteStream; + + /** + * Create a transform stream that passes through files whose modification time + * is more recent than the corresponding destination file's modification time. + */ + (options: IOptions): NodeJS.ReadWriteStream; + } + + const newer: IGulpNewer; + export = newer; +} From 829c564bf1e86a14d35ebaebe78384c281e632d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20Corbi=C3=A8re?= Date: Thu, 20 Aug 2015 12:37:27 +0200 Subject: [PATCH 102/345] [gulp-changed] Fix typo --- gulp-changed/gulp-changed-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gulp-changed/gulp-changed-tests.ts b/gulp-changed/gulp-changed-tests.ts index ae6104eed..dae92e0fd 100644 --- a/gulp-changed/gulp-changed-tests.ts +++ b/gulp-changed/gulp-changed-tests.ts @@ -12,7 +12,7 @@ gulp.src("*.html") .pipe(minifyHtml()) .pipe(gulp.dest("build")); -// Without some options +// With some options gulp.src("*.html") .pipe(changed("build", { hasChanged: changed.compareSha1Digest })) .pipe(minifyHtml()) From 5b010131f16dc0ae1b6ec6cc3cb36a95419ca0db Mon Sep 17 00:00:00 2001 From: Marcin Porebski Date: Thu, 20 Aug 2015 14:17:47 +0200 Subject: [PATCH 103/345] typo fix --- string_score/string_score.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/string_score/string_score.d.ts b/string_score/string_score.d.ts index 2d901ba39..5e3ee05d5 100644 --- a/string_score/string_score.d.ts +++ b/string_score/string_score.d.ts @@ -1,4 +1,4 @@ -// Type definitions for url-template 0.1.22 +// Type definitions for string_score 0.1.22 // Project: https://github.com/joshaven/string_score // Definitions by: Marcin Porębski // Definitions: https://github.com/borisyankov/DefinitelyTyped From 8a1f9f526d462bb6bbbb2603e3bcf1c4e4c818cc Mon Sep 17 00:00:00 2001 From: jbghoul Date: Thu, 20 Aug 2015 15:58:08 +0200 Subject: [PATCH 104/345] HighchartsDateTimeFormats: add missing millisecond --- highcharts/highcharts.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/highcharts/highcharts.d.ts b/highcharts/highcharts.d.ts index ee3a2ce4c..483e37fca 100644 --- a/highcharts/highcharts.d.ts +++ b/highcharts/highcharts.d.ts @@ -13,6 +13,7 @@ interface HighchartsPosition { } interface HighchartsDateTimeFormats { + millisecond?: string; // '%H:%M:%S.%L' second?: string; // '%H:%M:%S' minute?: string; // '%H:%M' hour?: string; // '%H:%M' From f62efc0d21f9029e84bf1cd9c07ec9c17a3c5690 Mon Sep 17 00:00:00 2001 From: Joe Skeen Date: Thu, 20 Aug 2015 08:21:50 -0600 Subject: [PATCH 105/345] Added overloads to gul-if and added documentation --- gulp-if/gulp-if-tests.ts | 24 ++++++++++++---- gulp-if/gulp-if.d.ts | 62 ++++++++++++++++++++++++++++++++++++---- 2 files changed, 74 insertions(+), 12 deletions(-) diff --git a/gulp-if/gulp-if-tests.ts b/gulp-if/gulp-if-tests.ts index e1ba54c91..6edb3bc13 100644 --- a/gulp-if/gulp-if-tests.ts +++ b/gulp-if/gulp-if-tests.ts @@ -1,10 +1,22 @@ /// /// -import gulp = require("gulp"); -import _if = require("gulp-if"); +import gulp = require('gulp'); +import _if = require('gulp-if'); -gulp.src("test.css") - .pipe(_if(true, gulp.src("test.css"))); +gulp.src('test.css') + .pipe(_if(true, gulp.src('test.css'))); -gulp.src("test.css") - .pipe(_if(false, gulp.src("test.css"), gulp.src("test.css"))); \ No newline at end of file +gulp.src('test.css') + .pipe(_if(false, gulp.src('test.css'), gulp.src('test.css'))); + +gulp.src('test.css') + .pipe(_if({isDirectory: true}, gulp.src('test.css'))); + +gulp.src('test.css') + .pipe(_if({isFile: true}, gulp.src('test.css'))); + +gulp.src('test.css') + .pipe(_if(file => true, gulp.src('test.css'))); + +gulp.src('test.css') + .pipe(_if(/.*?\.css/, gulp.src('test.css'))); \ No newline at end of file diff --git a/gulp-if/gulp-if.d.ts b/gulp-if/gulp-if.d.ts index 474682b9d..9eab80f8b 100644 --- a/gulp-if/gulp-if.d.ts +++ b/gulp-if/gulp-if.d.ts @@ -1,14 +1,64 @@ // Type definitions for gulp-if // Project: https://github.com/robrich/gulp-if -// Definitions by: Asana +// Definitions by: Asana , Joe Skeen // Definitions: https://github.com/borisyankov/DefinitelyTyped /// +/// -declare module "gulp-if" { - function gulpIf( - condition: boolean, - stream: NodeJS.ReadWriteStream, - elseStream?: NodeJS.ReadWriteStream): NodeJS.ReadWriteStream; +declare module 'gulp-if' { + import fs = require('fs'); + import vinyl = require('vinyl'); + + interface GulpIf { + /** + * gulp-if will pipe data to stream whenever condition is truthy. + * If condition is falsey and elseStream is passed, data will pipe to elseStream + * After data is piped to stream or elseStream or neither, data is piped down-stream. + * + * @param condition whether input should be piped to stream + * @param stream the stream to pipe to if condition is true + * @param elseStream (optional) the stream to pipe to if condition is false + */ + (condition: boolean, stream: NodeJS.ReadWriteStream, elseStream?: NodeJS.ReadWriteStream): NodeJS.ReadWriteStream; + /** + * gulp-if will pipe data to stream whenever condition is truthy. + * If condition is falsey and elseStream is passed, data will pipe to elseStream + * After data is piped to stream or elseStream or neither, data is piped down-stream. + * + * @param condition a Node Stat filter condition to be executed on the vinyl file's Stats object + * @param stream the stream to pipe to if condition is true + * @param elseStream (optional) the stream to pipe to if condition is false + */ + (condition: StatFilterCondition, stream: NodeJS.ReadWriteStream, elseStream?: NodeJS.ReadWriteStream): NodeJS.ReadWriteStream; + /** + * gulp-if will pipe data to stream whenever condition is truthy. + * If condition is falsey and elseStream is passed, data will pipe to elseStream + * After data is piped to stream or elseStream or neither, data is piped down-stream. + * + * @param condition a function taking a vinyl file and returning a boolean + * @param stream the stream to pipe to if condition is true + * @param elseStream (optional) the stream to pipe to if condition is false + */ + (condition: (fs: vinyl) => boolean, stream: NodeJS.ReadWriteStream, elseStream?: NodeJS.ReadWriteStream): NodeJS.ReadWriteStream; + /** + * gulp-if will pipe data to stream whenever condition is truthy. + * If condition is falsey and elseStream is passed, data will pipe to elseStream + * After data is piped to stream or elseStream or neither, data is piped down-stream. + * + * @param condition a RegularExpression that works on the file.path + * @param stream the stream to pipe to if condition is true + * @param elseStream (optional) the stream to pipe to if condition is false + */ + (condition: RegExp, stream: NodeJS.ReadWriteStream, elseStream?: NodeJS.ReadWriteStream): NodeJS.ReadWriteStream; + } + + interface StatFilterCondition { + isDirectory?: boolean; + isFile?: boolean; + } + + var gulpIf: GulpIf; + export = gulpIf; } \ No newline at end of file From 673be8a16912c0f95dd998e1ffcadb17cd7d5328 Mon Sep 17 00:00:00 2001 From: Aya Morisawa Date: Thu, 20 Aug 2015 23:52:15 +0900 Subject: [PATCH 106/345] Fix return value of transform in request-promise.d.ts The return value of `transform` function is not necessarily `number`. --- request-promise/request-promise.d.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/request-promise/request-promise.d.ts b/request-promise/request-promise.d.ts index 9cee53eee..246f1e5d9 100644 --- a/request-promise/request-promise.d.ts +++ b/request-promise/request-promise.d.ts @@ -3,6 +3,8 @@ // Definitions by: Christopher Glantschnig // Definitions: https://github.com/borisyankov/DefinitelyTyped +// Change [0]: 2015/08/20 - Aya Morisawa + /// /// /// @@ -22,7 +24,7 @@ declare module 'request-promise' { module RequestPromiseAPI { export interface Options extends request.Options { simple?: boolean; - transform?: (body: any, response: http.IncomingMessage) => number; + transform?: (body: any, response: http.IncomingMessage) => any; resolveWithFullResponse?: boolean; } } From b49efc4030dd0eed7929c738f316d3a541c185ef Mon Sep 17 00:00:00 2001 From: rhysd Date: Fri, 21 Aug 2015 00:55:57 +0900 Subject: [PATCH 107/345] Added definitions for auto-launch package Project page is here. https://github.com/Teamwork/node-auto-launch > Launch node-webkit apps at login (mac & windows) --- auto-launch/auto-launch-tests.ts | 17 +++++++++++++ auto-launch/auto-launch.d.ts | 41 ++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 auto-launch/auto-launch-tests.ts create mode 100644 auto-launch/auto-launch.d.ts diff --git a/auto-launch/auto-launch-tests.ts b/auto-launch/auto-launch-tests.ts new file mode 100644 index 000000000..735985624 --- /dev/null +++ b/auto-launch/auto-launch-tests.ts @@ -0,0 +1,17 @@ +/// + +import AutoLaunch = require('auto-launch'); + +var a1 = new AutoLaunch({ + name: 'Foo', +}); + +var a2 = new AutoLaunch({ + name: 'Foo', + path: '/Applications/Foo.app', + isHidden: true, +}); + +a1.enable(); +a2.disable(); +var enabled: boolean = a1.isEnabled(); diff --git a/auto-launch/auto-launch.d.ts b/auto-launch/auto-launch.d.ts new file mode 100644 index 000000000..c208d10fd --- /dev/null +++ b/auto-launch/auto-launch.d.ts @@ -0,0 +1,41 @@ +// Type definitions for auto-launch 0.1.18 +// Project: https://github.com/Teamwork/node-auto-launch +// Definitions by: rhysd +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface AutoLaunchOption { + /** + * Application name. + */ + name: string; + /** + * Hidden on launch or not. Default is false. + */ + isHidden?: boolean; + /** + * Path to application directory. + * Default is process.execPath. + */ + path?: string; +} + +declare class AutoLaunch { + constructor(opts: AutoLaunchOption); + /** + * Enables to launch at start up + */ + enable(callback?: (err: Error) => void): void; + /** + * Disables to launch at start up + */ + disable(callback?: (err: Error) => void): void; + /** + * Returns if auto start up is enabled + */ + isEnabled(callback?: (err: Error) => void): boolean; +} + +declare module "auto-launch" { + var al: typeof AutoLaunch; + export = al; +} From e7b8c8bc7f784811a2d7dd57339686f60db82796 Mon Sep 17 00:00:00 2001 From: mfrantz Date: Thu, 6 Aug 2015 13:06:30 -0700 Subject: [PATCH 108/345] semaphore v1.0.3 --- semaphore/semaphore-tests.ts | 14 ++++++++++++++ semaphore/semaphore.d.ts | 26 ++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 semaphore/semaphore-tests.ts create mode 100644 semaphore/semaphore.d.ts diff --git a/semaphore/semaphore-tests.ts b/semaphore/semaphore-tests.ts new file mode 100644 index 000000000..d6df36030 --- /dev/null +++ b/semaphore/semaphore-tests.ts @@ -0,0 +1,14 @@ +/// + +import semaphore = require('semaphore'); + +var sem: semaphore.Semaphore = semaphore(10); + +function task() { + console.log('My task'); + sem.leave(); +} + +sem.take(task); +sem.take(2, task); +sem.leave(2); diff --git a/semaphore/semaphore.d.ts b/semaphore/semaphore.d.ts new file mode 100644 index 000000000..0a2855b82 --- /dev/null +++ b/semaphore/semaphore.d.ts @@ -0,0 +1,26 @@ +// Type definitions for semaphore v1.0.3 +// Project: https://github.com/abrkn/semaphore.js +// Definitions by: Matt Frantz +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module 'semaphore' { + + function semaphore(capacity?: number): semaphore.Semaphore; + + module semaphore { + + interface Task { + (): void; + } + + interface Semaphore { + capacity: number; + + take(task: Task): void; + take(n: number, task: Task): void; + + leave(n?: number): void; + } + } + export = semaphore; +} From c7a19cd5342b9cd64108f4ea5e8f709601d0feae Mon Sep 17 00:00:00 2001 From: Mark Nadig Date: Thu, 20 Aug 2015 12:41:58 -0600 Subject: [PATCH 109/345] angular-ui-scroll typings and tests --- angular-ui-scroll/angular-ui-scroll-tests.ts | 93 ++++++++++++++++++++ angular-ui-scroll/angular-ui-scroll.d.ts | 85 ++++++++++++++++++ 2 files changed, 178 insertions(+) create mode 100644 angular-ui-scroll/angular-ui-scroll-tests.ts create mode 100644 angular-ui-scroll/angular-ui-scroll.d.ts diff --git a/angular-ui-scroll/angular-ui-scroll-tests.ts b/angular-ui-scroll/angular-ui-scroll-tests.ts new file mode 100644 index 000000000..1a85dd6b5 --- /dev/null +++ b/angular-ui-scroll/angular-ui-scroll-tests.ts @@ -0,0 +1,93 @@ +/// +var myApp = angular.module('application', ['ui.scroll', 'ui.scroll.jqlite']); + +module application { + interface IItem { + id: number; + content: string; + } + + class DatasourceTest implements ng.ui.IScrollDatasource { + get(index: number, count: number, success: (results: IItem[]) => void): void { + var ret = new Array(); + for (var i=0; i < count; i++) { + ret.push({id: i, content: 'item ' + i.toString()}); + } + success(ret); + } + } + + function factory(): any { + return DatasourceTest; + } + + myApp.factory('DatasourceTest', factory); + + // demo/examples/adapter + myApp.controller('mainController', ['$scope', 'DatasourceTest', function($scope: ng.IScope, datasource: DatasourceTest) { + var firstListAdapter: ng.ui.IScrollAdapter, secondListAdapter: ng.ui.IScrollAdapter; + $scope['datasource'] = datasource; + + $scope['updateList1'] = (): void => { + firstListAdapter.applyUpdates( (item: IItem, scope: ng.IRepeatScope) => { + return item.content += ' *'; + }) + }; + + $scope['removeFromList1'] = (): void => { + firstListAdapter.applyUpdates( (item: IItem, scope: ng.IRepeatScope) => { + if (scope.$index % 2 === 0) { + return [] + } + }) + }; + + var idList1: number = 1000; + $scope['addToList1'] = (): void => { + firstListAdapter.applyUpdates((item: IItem, scope: ng.IRepeatScope) => { + var newItem: IItem; + newItem = void 0; + if (scope.$index === 2) { + newItem = { + id: idList1, + content: 'a new one #' + idList1 + }; + idList1++; + return [item, newItem]; + } + }); + }; + + $scope['updateList2'] = (): void => { + secondListAdapter.applyUpdates((item: IItem, scope: ng.IRepeatScope) => { + return item.content += ' *'; + }); + }; + + $scope['removeFromList2'] = (): void => { + secondListAdapter.applyUpdates((item: IItem, scope: ng.IRepeatScope) => { + if (scope.$index % 2 !== 0) { + return []; + } + }); + }; + + var idList2: number = 2000; + $scope['addToList2'] = (): void => { + secondListAdapter.applyUpdates((item: IItem, scope: ng.IRepeatScope) => { + var newItem: IItem; + newItem = void 0; + if (scope.$index === 4) { + newItem = { + id: idList2, + content: 'a new one #' + idList1 + }; + idList2++; + return [item, newItem]; + } + }); + }; + + }]); +} + diff --git a/angular-ui-scroll/angular-ui-scroll.d.ts b/angular-ui-scroll/angular-ui-scroll.d.ts new file mode 100644 index 000000000..08ed233c0 --- /dev/null +++ b/angular-ui-scroll/angular-ui-scroll.d.ts @@ -0,0 +1,85 @@ +// Type definitions for Angular JS 1.3.1+ (ui.scroll module) +// Project: https://github.com/angular-ui/ui-scroll +// Definitions by: Mark Nadig +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module angular.ui { + interface IScrollDatasource { + /** + * The datasource object implements methods and properties to be used by the directive to access the data + * + * @param index indicates the first data row requested + * + * @param count indicates number of data rows requested + * + * @param success function to call when the data are retrieved. The implementation of the service has to call + * this function when the data are retrieved and pass it an array of the items retrieved. If no items are + * retrieved, an empty array has to be passed. + * + * Important: Make sure to respect the index and count parameters of the request. The array passed to the + * success method should have exactly count elements unless it hit eof/bof + */ + get(index: number, count: number, success: (results: Array) => any): void; + } + + interface IScrollAdapter { + /** + * a boolean value indicating whether there are any pending load requests. + */ + isLoading: boolean; + /** + * a reference to the item currently in the topmost visible position. + */ + topVisible: any; + /** + * a reference to the DOM element currently in the topmost visible position. + */ + topVisibleElement: ng.IAugmentedJQueryStatic; + /** + * a reference to the scope created for the item currently in the topmost visible position. + */ + topVisibleScope: ng.IRepeatScope; + /** + * calling this method reinitializes and reloads the scroller content. + */ + reload(): void; + /** + * Replaces the item in the buffer at the given index with the new items. + * + * @param index provides position of the item to be affected in the dataset (not in the buffer). If the item with + * the given index currently is not in the buffer no updates will be applied. $index property of the item $scope + * can be used to access the index value for a given item + * + * @param newItems is an array of items to replace the affected item. If the array is empty ([]) the item will + * be deleted, otherwise the items in the array replace the item. If the newItem array contains the old item, + * the old item stays in place. + */ + applyUpdates(index: number, newItems: any[]): void; + /** + * Replaces the item in the buffer at the given index with the new items. + * + * @param updater is a function to be applied to every item currently in the buffer. The function will receive + * 3 parameters: item, scope, and element. Here item is the item to be affected, scope is the item $scope, and + * element is the html element for the item. The return value of the function should be an array of items. + * Similarly to the newItem parameter (see above), if the array is empty([]), the item is deleted, otherwise + * the item is replaced by the items in the array. If the return value is not an array, the item remains + * unaffected, unless some updates were made to the item in the updater function. This can be thought of as + * in place update. + */ + applyUpdates(updater: (item: any, scope: ng.IRepeatScope) => any): void; + /** + * Adds new items after the last item in the buffer + * + * @param newItems provides an array of items to be appended. + */ + append(newItems: any[]): void; + /** + * Adds new items before the first item in the buffer + * + * @param newItems provides an array of items to be prepended. + */ + prepend(newItems: any[]): void; + } +} From 5aca285de7bf04b073a96b6003c3009442cbbb18 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 20 Aug 2015 12:25:28 -0700 Subject: [PATCH 110/345] The difference is Nil in 'tcomb'. --- tcomb/tcomb.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tcomb/tcomb.d.ts b/tcomb/tcomb.d.ts index c189a6a0f..923bd2fa8 100644 --- a/tcomb/tcomb.d.ts +++ b/tcomb/tcomb.d.ts @@ -16,7 +16,7 @@ declare module TComb { assert: (condition: boolean, message?: string, ...values: any[]) => void; fail: (message?: string) => void; Any: Any_Static; - Nil: Str_Static; + Nil: Nil_Static; Str: Str_Static; Num: Num_Static; Bool: Bool_Static; From bfeb69f3e359a3b7453583954d20a540b7bd6e9e Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 20 Aug 2015 12:37:47 -0700 Subject: [PATCH 111/345] Fixed indentation in 'tcomb'. --- tcomb/tcomb.d.ts | 175 ++++++++++++++++++++++++----------------------- 1 file changed, 88 insertions(+), 87 deletions(-) diff --git a/tcomb/tcomb.d.ts b/tcomb/tcomb.d.ts index 923bd2fa8..c4676adfd 100644 --- a/tcomb/tcomb.d.ts +++ b/tcomb/tcomb.d.ts @@ -24,8 +24,9 @@ declare module TComb { Obj: Obj_Static; Func: Func_Static; - func: { (domain: TCombBase[], codomain: TCombBase, name?: string) : Func_Static; - (domain: TCombBase, codomain: TCombBase, name?: string) : Func_Static; + func: { + (domain: TCombBase[], codomain: TCombBase, name?: string): Func_Static; + (domain: TCombBase, codomain: TCombBase, name?: string) : Func_Static; } Err: Err_Static; Re: Re_Static; @@ -61,13 +62,13 @@ declare module TComb { export interface TCombBase { meta: { - /** - * The type kind, equal to "irreducible" for irreducible types. - */ + /** + * The type kind, equal to "irreducible" for irreducible types. + */ kind: string; - /** - * The type name. - */ + /** + * The type name. + */ name: string; }; displayName: string; @@ -107,17 +108,17 @@ declare module TComb { new (value: string): Str_Instance; (value: string): Str_Instance; meta: { - /** - * The type kind, equal to "irreducible" for irreducible types. - */ + /** + * The type kind, equal to "irreducible" for irreducible types. + */ kind: string; - /** - * The type name. - */ + /** + * The type name. + */ name: string; - /** - * The type predicate. - */ + /** + * The type predicate. + */ is: TypePredicate; }; } @@ -210,15 +211,15 @@ declare module TComb { - /** - * @param name - The type name. - * @param is - A predicate. - */ + /** + * @param name - The type name. + * @param is - A predicate. + */ - /** - * @param props - A hash whose keys are the field names and the values are the fields types. - * @param name - Useful for debugging purposes. - */ + /** + * @param props - A hash whose keys are the field names and the values are the fields types. + * @param name - Useful for debugging purposes. + */ export interface Struct_Static extends TCombBase { @@ -229,52 +230,52 @@ declare module TComb { name: string; props: any[]; }; - /** - * @param mixins - Contains the new props. - * @param name - Useful for debugging purposes. - */ + /** + * @param mixins - Contains the new props. + * @param name - Useful for debugging purposes. + */ extend(mixins: Object, name?: string): Struct_Static; - /** - * @param mixins - Contains the new props. - * @param name - Useful for debugging purposes. - */ + /** + * @param mixins - Contains the new props. + * @param name - Useful for debugging purposes. + */ extend(mixins: Struct_Static, name?: string): Struct_Static; - /** - * @param mixins - Contains the new props. - * @param name - Useful for debugging purposes. - */ + /** + * @param mixins - Contains the new props. + * @param name - Useful for debugging purposes. + */ extend(mixins: Object[], name?: string): Struct_Static; - /** - * @param mixins - Contains the new props. - * @param name - Useful for debugging purposes. - */ + /** + * @param mixins - Contains the new props. + * @param name - Useful for debugging purposes. + */ extend(mixins: Struct_Static[], name?: string): Struct_Static; } interface Struct_Instance { } - /** - * @param map - A hash whose keys are the enums (values are free). - * @param name - Useful for debugging purposes. - */ + /** + * @param map - A hash whose keys are the enums (values are free). + * @param name - Useful for debugging purposes. + */ export module enums { - /** - * @param keys - Array of enums. - * @param name - Useful for debugging purposes. - */ + /** + * @param keys - Array of enums. + * @param name - Useful for debugging purposes. + */ export function of(keys: string[], name?: string): TCombBase; - /** - * @param keys - String of enums separated by spaces. - * @param name - Useful for debugging purposes. - */ + /** + * @param keys - String of enums separated by spaces. + * @param name - Useful for debugging purposes. + */ export function of(keys: string, name?: string): TCombBase; } - /** - * @param name - Useful for debugging purposes. - */ + /** + * @param name - Useful for debugging purposes. + */ export interface Union_Static extends TCombBase { new (value: any, mutable?: boolean): Union_Instance; @@ -291,10 +292,10 @@ declare module TComb { } - /** - * @param type - The wrapped type. - * @param name - Useful for debugging purposes. - */ + /** + * @param type - The wrapped type. + * @param name - Useful for debugging purposes. + */ @@ -312,9 +313,9 @@ declare module TComb { } - /** - * @param name - Useful for debugging purposes. - */ + /** + * @param name - Useful for debugging purposes. + */ interface Tuple_Static extends TCombBase { new (value: any, mutable?: boolean): Tuple_Instance; @@ -329,11 +330,11 @@ declare module TComb { interface Tuple_Instance { } - /** - * Combines old types into a new one. - * @param type - A type already defined. - * @param name - Useful for debugging purposes. - */ + /** + * Combines old types into a new one. + * @param type - A type already defined. + * @param name - Useful for debugging purposes. + */ export interface Subtype_Static extends TCombBase { @@ -350,10 +351,10 @@ declare module TComb { interface Subtype_Instance { } - /** - * @param type - The type of list items. - * @param name - Useful for debugging purposes. - */ + /** + * @param type - The type of list items. + * @param name - Useful for debugging purposes. + */ export function list(type: TCombBase, name?: string): List_Static; interface List_Static extends TCombBase { @@ -369,11 +370,11 @@ declare module TComb { interface List_Instance { } - /** - * @param domain - The type of keys. - * @param codomain - The type of values. - * @param name - Useful for debugging purposes. - */ + /** + * @param domain - The type of keys. + * @param codomain - The type of values. + * @param name - Useful for debugging purposes. + */ interface Dict_Static extends TCombBase { @@ -390,16 +391,16 @@ declare module TComb { interface Dict_Instance { } - /** - * @param type - The type of the function's argument. - * @param codomain - The type of the function's return value. - * @param name - Useful for debugging purposes. - */ - /** - * @param type - The list of types of the function's arguments. - * @param codomain - The type of the function's return value. - * @param name - Useful for debugging purposes. - */ + /** + * @param type - The type of the function's argument. + * @param codomain - The type of the function's return value. + * @param name - Useful for debugging purposes. + */ + /** + * @param type - The list of types of the function's arguments. + * @param codomain - The type of the function's return value. + * @param name - Useful for debugging purposes. + */ interface Func_Static extends TCombBase { new (value: any, mutable?: boolean): Func_Instance; From 69a917929357233930258ebd45c1529ff06fa268 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 20 Aug 2015 12:38:05 -0700 Subject: [PATCH 112/345] Added 'any' cast in 'tcomb'. --- tcomb/tcomb-tests.ts | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/tcomb/tcomb-tests.ts b/tcomb/tcomb-tests.ts index 3a27ffc7f..aafd5e55b 100644 --- a/tcomb/tcomb-tests.ts +++ b/tcomb/tcomb-tests.ts @@ -577,17 +577,16 @@ describe('irreducible types constructors', function () { {T: Dat, x: new Date()} ].forEach(function (o) { - var T = o.T; - var x = o.x; + var { T, x } = o; it('should accept only valid values', function () { - eq(T(x), x); + eq((T)(x), x); }); it('should throw if used with new', function () { throwsWithMessage(function () { /* jshint ignore:start */ - var x = new (T) (); + var x = new (T) (); /* jshint ignore:end */ }, 'Operator `new` is forbidden for type `' + getTypeName(T) + '`'); }); From e48415a72df4eec7a26062065a394f97218c77d9 Mon Sep 17 00:00:00 2001 From: John Palgut Date: Thu, 20 Aug 2015 15:23:11 -0500 Subject: [PATCH 113/345] Add a type definition for HTTPOptions The method [Parse.Cloud.httpRequest](https://parse.com/docs/js/api/symbols/Parse.Cloud.html#.httpRequest) takes a [HTTPOptions](https://parse.com/docs/js/api/symbols/Parse.Cloud.HTTPOptions.html) options object and not a ParseDefaultOptions object. I've included an initial interface definition for HTTPOptions and updated the httpRequest method definition to match --- parse/parse.d.ts | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/parse/parse.d.ts b/parse/parse.d.ts index cb4fa8b2b..9322188af 100644 --- a/parse/parse.d.ts +++ b/parse/parse.d.ts @@ -23,6 +23,17 @@ declare module Parse { useMasterKey?: boolean; } + interface HTTPOptions { + url: string; + body?: any; + error?: Function; + followRedirects?: boolean; + headers?: any; + method?: string; + params?: any; + success?: Function; + } + interface CollectionOptions { model?: Object; query?: Query; @@ -796,7 +807,7 @@ declare module Parse { function beforeDelete(arg1: any, func?: (request: BeforeDeleteRequest, response: BeforeDeleteResponse) => void): void; function beforeSave(arg1: any, func?: (request: BeforeSaveRequest, response: BeforeSaveResponse) => void): void; function define(name: string, func?: (request: FunctionRequest, response: FunctionResponse) => void): void; - function httpRequest(options: ParseDefaultOptions): Promise; + function httpRequest(options: HTTPOptions): Promise; function job(name: string, func?: (request: JobRequest, status: JobStatus) => void): HttpResponse; function run(name: string, data?: any, options?: ParseDefaultOptions): Promise; function useMasterKey(): void; From fd06a4cbb56754a33dabf3906ee6dd0bff98f402 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 20 Aug 2015 13:52:02 -0700 Subject: [PATCH 114/345] Fix spelling mistakes gere and tgere in 'royalslider'. --- royalslider/royalslider-tests.ts | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/royalslider/royalslider-tests.ts b/royalslider/royalslider-tests.ts index 6cafcb6d6..4246ec90b 100644 --- a/royalslider/royalslider-tests.ts +++ b/royalslider/royalslider-tests.ts @@ -10,10 +10,10 @@ $(".royalSlider").royalSlider({ jQuery(document).ready(function () { $(".royalSlider").royalSlider({ - // general options go gere + // general options go here autoScaleSlider: true, thumbs: { - // thumbnails options go gere + // thumbnails options go here spacing: 10, arrowsAutoHide: true } @@ -22,10 +22,10 @@ jQuery(document).ready(function () { jQuery(document).ready(function () { $(".royalSlider").royalSlider({ - // general options go gere + // general options go here autoScaleSlider: true, fullscreen: { - // fullscreen options go gere + // fullscreen options go here enabled: true, nativeFS: true } @@ -34,10 +34,10 @@ jQuery(document).ready(function () { jQuery(document).ready(function () { $(".royalSlider").royalSlider({ - // general options go gere + // general options go here autoScaleSlider: true, deeplinking: { - // deep linking options go gere + // deep linking options go here enabled: true, prefix: 'slider-' } @@ -47,10 +47,10 @@ jQuery(document).ready(function () { jQuery(document).ready(function () { $(".royalSlider").royalSlider({ - // general options go gere + // general options go here autoScaleSlider: true, autoplay: { - // autoplay options go gere + // autoplay options go here enabled: true, pauseOnHover: true } @@ -59,10 +59,10 @@ jQuery(document).ready(function () { jQuery(document).ready(function () { $(".royalSlider").royalSlider({ - // general options go gere + // general options go here autoScaleSlider: true, video: { - // video options go gere + // video options go here autoHideBlocks: true, autoHideArrows: false } @@ -71,10 +71,10 @@ jQuery(document).ready(function () { jQuery(document).ready(function () { $(".royalSlider").royalSlider({ - // general options go gere + // general options go here autoScaleSlider: true, block: { - // animated blocks options go gere + // animated blocks options go here fadeEffect: false, moveEffect: 'left' } @@ -83,7 +83,7 @@ jQuery(document).ready(function () { jQuery(document).ready(function () { $(".royalSlider").royalSlider({ - // general options go gere + // general options go here keyboardNavEnabled: true, visibleNearby: { enabled: true, @@ -174,7 +174,7 @@ slider.ev.on('rsBeforeAnimStart', function (event) { slider.ev.on('rsBeforeMove', function (event: JQueryEventObject, type?: string, userAction?: boolean) { // before any transition start (including after drag release) // "type" - can be "next", "prev", or ID of slide to move - // userAction (Boolean) - defines if action is triggered by user (e.g. will be false if movement is triggered by autoPlay) + // userAction (Boolean) - defines if action is trighered by user (e.g. will be false if movement is trighered by autoPlay) }); slider.ev.on('rsBeforeSizeSet', function (event) { // before size of slider is changed From c8157285b7a1f4da8ecdedd7d36bae1c9108d3fe Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 20 Aug 2015 13:57:52 -0700 Subject: [PATCH 115/345] Added string overload for 'data' to return appropriate type in 'royalslider'. --- royalslider/royalslider-tests.ts | 2 +- royalslider/royalslider.d.ts | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/royalslider/royalslider-tests.ts b/royalslider/royalslider-tests.ts index 4246ec90b..88e44a6fb 100644 --- a/royalslider/royalslider-tests.ts +++ b/royalslider/royalslider-tests.ts @@ -100,7 +100,7 @@ jQuery(document).ready(function () { // Another example: $(".royalSlider").royalSlider('goTo', 3); // But it's recommended to get instance once if you have many calls: -var slider: RoyalSlider.RoyalSlider = $(".royalSlider").royalSlider().data('royalSlider'); +var slider = $(".royalSlider").royalSlider().data('royalSlider'); slider.goTo(3); // go to slide with id slider.next(); // next slide diff --git a/royalslider/royalslider.d.ts b/royalslider/royalslider.d.ts index 5dd7c2771..3f06b41b5 100644 --- a/royalslider/royalslider.d.ts +++ b/royalslider/royalslider.d.ts @@ -493,4 +493,6 @@ interface JQuery { * @param options The options */ royalSlider(options?: RoyalSlider.RoyalSliderOptions): JQuery; + + data(key: "royalSlider"): RoyalSlider.RoyalSlider; } \ No newline at end of file From d2f69d40abc7fc3bdc383eb8abf68cc9809b8080 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 20 Aug 2015 14:24:27 -0700 Subject: [PATCH 116/345] Add index signature to 'ComponentSpec' in 'react'. --- react/react-global.d.ts | 2 ++ react/react-tests.ts | 10 +++++----- react/react.d.ts | 2 ++ 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/react/react-global.d.ts b/react/react-global.d.ts index f8b376355..58ff14f39 100644 --- a/react/react-global.d.ts +++ b/react/react-global.d.ts @@ -215,6 +215,8 @@ declare module React { interface ComponentSpec extends Mixin { render(): ReactElement; + + [propertyName: string]: any; } // diff --git a/react/react-tests.ts b/react/react-tests.ts index a4d2c4f7a..fbd1cb516 100644 --- a/react/react-tests.ts +++ b/react/react-tests.ts @@ -41,24 +41,24 @@ var container: Element; var ClassicComponent: React.ClassicComponentClass = React.createClass({ - getDefaultProps: () => { + getDefaultProps() { return { hello: undefined, world: "peace", foo: undefined, - bar: undefined + bar: undefined, }; }, - getInitialState: () => { + getInitialState() { return { inputValue: this.context.someValue, seconds: this.props.foo }; }, - reset: () => { + reset() { this.replaceState(this.getInitialState()); }, - render: () => { + render() { return React.DOM.div(null, React.DOM.input({ ref: input => this._input = input, diff --git a/react/react.d.ts b/react/react.d.ts index 218c6c94a..671b23784 100644 --- a/react/react.d.ts +++ b/react/react.d.ts @@ -215,6 +215,8 @@ declare module __React { interface ComponentSpec extends Mixin { render(): ReactElement; + + [propertyName: string]: any; } // From fb0b124b2aa7e3d301114832426dc61849cd585b Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 20 Aug 2015 14:36:58 -0700 Subject: [PATCH 117/345] Added indexer to CSS properties in 'react'. --- react/react-global.d.ts | 4 ++++ react/react.d.ts | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/react/react-global.d.ts b/react/react-global.d.ts index 58ff14f39..83c2d54a4 100644 --- a/react/react-global.d.ts +++ b/react/react-global.d.ts @@ -396,10 +396,14 @@ declare module React { zIndex?: number; zoom?: number; + fontSize?: number | string; + // SVG-related properties fillOpacity?: number; strokeOpacity?: number; strokeWidth?: number; + + [propertyName: string]: string | number | boolean; } interface HTMLAttributes extends DOMAttributes { diff --git a/react/react.d.ts b/react/react.d.ts index 671b23784..f6dd25511 100644 --- a/react/react.d.ts +++ b/react/react.d.ts @@ -396,10 +396,14 @@ declare module __React { zIndex?: number; zoom?: number; + fontSize?: number | string; + // SVG-related properties fillOpacity?: number; strokeOpacity?: number; strokeWidth?: number; + + [propertyName: string]: string | number | boolean; } interface HTMLAttributes extends DOMAttributes { From cd5653f5a430db1875b33e7e0824c175e5a439aa Mon Sep 17 00:00:00 2001 From: Jordan Potter Date: Thu, 20 Aug 2015 16:29:39 -0700 Subject: [PATCH 118/345] Correct history.js return type annotations --- history/history.d.ts | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/history/history.d.ts b/history/history.d.ts index 07a31d011..f6a6bf407 100644 --- a/history/history.d.ts +++ b/history/history.d.ts @@ -5,23 +5,23 @@ interface HistoryAdapter { - bind(element: any, event: string, callback: () => void); - trigger(element: any, event: string); - onDomLoad(callback: () => void); + bind(element: any, event: string, callback: () => void): void; + trigger(element: any, event: string): void; + onDomLoad(callback: () => void): void; } -// Since History is defined in lib.d.ts as well +// Since History is defined in lib.d.ts as well // the name for our interfaces was chosen to be Historyjs // However at runtime you would need to do -// https://github.com/borisyankov/DefinitelyTyped/issues/277 +// https://github.com/borisyankov/DefinitelyTyped/issues/277 // var Historyjs: Historyjs = History; interface Historyjs { enabled: boolean; - pushState(data: any, title: string, url: string); - replaceState(data: any, title: string, url: string); + pushState(data: any, title: string, url: string): void; + replaceState(data: any, title: string, url: string): void; getState(): HistoryState; getStateByIndex(index: number): HistoryState; getCurrentIndex(): number; @@ -58,4 +58,4 @@ interface HistoryOptions { delayInit?: number; -} \ No newline at end of file +} From d333e3deb09c5aea1063c45d80ccaeba48bcb93b Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 20 Aug 2015 16:52:54 -0700 Subject: [PATCH 119/345] Add type annotation to avoid complaining about missing index signature in 'react'. --- react/react-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/react/react-tests.ts b/react/react-tests.ts index fbd1cb516..6540cc9f3 100644 --- a/react/react-tests.ts +++ b/react/react-tests.ts @@ -204,7 +204,7 @@ myComponent.reset(); // -------------------------------------------------------------------------- var children: any[] = ["Hello world", [null], React.DOM.span(null)]; -var divStyle = { // CSSProperties +var divStyle: React.CSSProperties = { // CSSProperties flex: "1 1 main-size", backgroundImage: "url('hello.png')" }; From 40ff00391a4b9f3c64a24e5071dfd96182ccceee Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 20 Aug 2015 16:47:19 -0700 Subject: [PATCH 120/345] Added 'events_listener', created subscription types, 'module' to 'namespace', etc. in 'sipml'. See https://groups.google.com/d/msg/doubango/AmmTDLGdon4/z6vZbMGyDAAJ for details. --- sipml/sipml.d.ts | 114 ++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 103 insertions(+), 11 deletions(-) diff --git a/sipml/sipml.d.ts b/sipml/sipml.d.ts index 84a694454..4d45fa6f4 100644 --- a/sipml/sipml.d.ts +++ b/sipml/sipml.d.ts @@ -3,7 +3,7 @@ // Definitions by: A. Groenenboom // Definitions: https://github.com/borisyankov/DefinitelyTyped -declare module SIPml { +declare namespace SIPml { class Event { public description: string; public type: string; @@ -14,12 +14,12 @@ declare module SIPml { public getSipResponseCode(): number; } - class EventTarget { - public addEventListener(type: any, listener: Function): void; - public removeEventListener(type: any): void; + class EventTarget { + public addEventListener(type: EventSubscriptionType, listener: (e: EventType) => void): void; + public removeEventListener(type: EventSubscriptionType): void; } - class Session extends EventTarget { + class Session extends EventTarget { public accept(configuration?: Session.Configuration): number; public getId(): number; public getRemoteFriendlyName(): string; @@ -28,10 +28,36 @@ declare module SIPml { public setConfiguration(configuration?: Session.Configuration): void; } - export module Session { + export namespace Session { + /** + * Should be + * + * "*" | + * "connecting" | + * "connected" | + * "terminating" | + * "terminated" | + * "i_ao_request" | + * "media_added" | + * "media_removed" | + * "i_request" | + * "o_request" | + * "cancelled_request" | + * "sent_request" | + * "transport_error" | + * "global_error" | + * "message_error" | + * "webrtc_error" | + */ + type EventSubscriptionType = string; + interface Configuration { audio_remote?: HTMLElement; bandwidth?: Object; + events_listener?: { + events: EventSubscriptionType | EventSubscriptionType[]; + listener: (e: Session.Event) => void + }; expires?: number; from?: string; sip_caps?: Object[]; @@ -41,7 +67,7 @@ declare module SIPml { video_size?: Object; } - class Call extends Session { + class Call extends Session implements EventTarget { public acceptTransfer(configuration?: Session.Configuration): number; public call(to: string, configuration?: Session.Configuration): number; public dtmf(): number; @@ -52,6 +78,42 @@ declare module SIPml { public resume(): number; public transfer(): number; } + + namespace Call { + /** + * Should be + * + * Session.EventSubscriptionType | + * "m_early_media" | + * "m_local_hold_ok" | + * "m_local_hold_nok" | + * "m_local_resume_ok" | + * "m_local_resume_nok" | + * "m_remote_hold" | + * "m_remote_resume" | + * "m_stream_video_local_added" | + * "m_stream_video_local_removed" | + * "m_stream_video_remote_added" | + * "m_stream_video_remote_removed" | + * "m_stream_audio_local_added" | + * "m_stream_audio_local_removed" | + * "m_stream_audio_remote_added" | + * "m_stream_audio_remote_removed" | + * "i_ect_new_call" | + * "o_ect_trying" | + * "o_ect_accepted" | + * "o_ect_completed" | + * "i_ect_completed" | + * "o_ect_failed" | + * "i_ect_failed" | + * "o_ect_notify" | + * "i_ect_notify" | + * "i_ect_requested " | + * "m_bfcp_info" | + * "i_info" | + */ + type EventSubscriptionType = Session.EventSubscriptionType; + } class Event extends SIPml.Event { public session: Session; @@ -74,13 +136,22 @@ declare module SIPml { public unregister(configuration?: Session.Configuration): void; } - class Subscribe extends Session { + class Subscribe extends Session implements EventTarget { public subscribe(to: string, configuration?: Session.Configuration): number; public unsubscribe(configuration?: Session.Configuration): number; } + + namespace Subscribe { + /** + * Should be + * + * Session.EventSubscriptionType | "i_notify" + */ + type EventSubscriptionType = Session.EventSubscriptionType; + } } - class Stack extends EventTarget { + class Stack extends EventTarget { public constructor(configuration?: Stack.Configuration); public setConfiguration(configuration: Stack.Configuration): number; public newSession(type: string, configuration?: Session.Configuration): any; @@ -88,7 +159,25 @@ declare module SIPml { public stop(timeout?: number): number; } - export module Stack { + export namespace Stack { + /** + * Should be + * + * "*" | + * "starting" | + * "started" | + * "stopping" | + * "stopped" | + * "failed_to_start" | + * "failed_to_stop" | + * "i_new_call" | + * "i_new_message" | + * "m_permission_requested" | + * "m_permission_accepted" | + * "m_permission_refused"; + */ + type EventSubscriptionType = string; + interface Configuration { bandwidth?: Object; display_name?: string; @@ -96,7 +185,10 @@ declare module SIPml { enable_early_ims?: boolean; enable_media_stream_cache?: boolean; enable_rtcweb_breaker?: boolean; - events_listener?: Object; + events_listener?: { + events: EventSubscriptionType | EventSubscriptionType[]; + listener: (e: Stack.Event) => void + }; ice_servers?: Object[]; impi?: string; impu?: string; From f4999e92bfe03f2edc2335b7d38bc664e2dc0916 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 20 Aug 2015 16:52:08 -0700 Subject: [PATCH 121/345] Replaced a few 'Object' types in 'sipml'. --- sipml/sipml.d.ts | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/sipml/sipml.d.ts b/sipml/sipml.d.ts index 4d45fa6f4..d033565e7 100644 --- a/sipml/sipml.d.ts +++ b/sipml/sipml.d.ts @@ -53,7 +53,7 @@ declare namespace SIPml { interface Configuration { audio_remote?: HTMLElement; - bandwidth?: Object; + bandwidth?: { audio: number; video: number; }; events_listener?: { events: EventSubscriptionType | EventSubscriptionType[]; listener: (e: Session.Event) => void @@ -64,7 +64,12 @@ declare namespace SIPml { sip_headers?: Object[]; video_local?: HTMLElement; video_remote?: HTMLElement; - video_size?: Object; + video_size?: { + minWidth?: number; + maxWidth?: number; + minHeight?: number; + maxHeight?: number; + }; } class Call extends Session implements EventTarget { @@ -179,7 +184,7 @@ declare namespace SIPml { type EventSubscriptionType = string; interface Configuration { - bandwidth?: Object; + bandwidth?: { audio: number; video: number; }; display_name?: string; enable_click2call?: boolean; enable_early_ims?: boolean; @@ -196,7 +201,12 @@ declare namespace SIPml { password?: string; realm?: string; sip_headers?: Object[]; - video_size?: Object; + video_size?: { + minWidth?: number; + maxWidth?: number; + minHeight?: number; + maxHeight?: number; + }; websocket_proxy_url?: string; } From 25db4a0cdfaad1adb29659e44b3cc6a45edd165e Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 20 Aug 2015 16:56:11 -0700 Subject: [PATCH 122/345] Normalize line endings in 'sipml'. --- sipml/sipml.d.ts | 396 +++++++++++++++++++++++------------------------ 1 file changed, 198 insertions(+), 198 deletions(-) diff --git a/sipml/sipml.d.ts b/sipml/sipml.d.ts index d033565e7..b6c77d898 100644 --- a/sipml/sipml.d.ts +++ b/sipml/sipml.d.ts @@ -1,37 +1,37 @@ -// Type definitions for SIPml5 -// Project: http://sipml5.org/ -// Definitions by: A. Groenenboom -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -declare namespace SIPml { - class Event { - public description: string; - public type: string; - - public getContent(): Object; - public getContentString(): string; - public getContentType(): Object; - public getSipResponseCode(): number; - } - - class EventTarget { - public addEventListener(type: EventSubscriptionType, listener: (e: EventType) => void): void; - public removeEventListener(type: EventSubscriptionType): void; - } - - class Session extends EventTarget { - public accept(configuration?: Session.Configuration): number; - public getId(): number; - public getRemoteFriendlyName(): string; - public getRemoteUri(): string; - public reject(configuration?: Session.Configuration): number; - public setConfiguration(configuration?: Session.Configuration): void; - } - - export namespace Session { - /** - * Should be - * +// Type definitions for SIPml5 +// Project: http://sipml5.org/ +// Definitions by: A. Groenenboom +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare namespace SIPml { + class Event { + public description: string; + public type: string; + + public getContent(): Object; + public getContentString(): string; + public getContentType(): Object; + public getSipResponseCode(): number; + } + + class EventTarget { + public addEventListener(type: EventSubscriptionType, listener: (e: EventType) => void): void; + public removeEventListener(type: EventSubscriptionType): void; + } + + class Session extends EventTarget { + public accept(configuration?: Session.Configuration): number; + public getId(): number; + public getRemoteFriendlyName(): string; + public getRemoteUri(): string; + public reject(configuration?: Session.Configuration): number; + public setConfiguration(configuration?: Session.Configuration): void; + } + + export namespace Session { + /** + * Should be + * * "*" | * "connecting" | * "connected" | @@ -47,48 +47,48 @@ declare namespace SIPml { * "transport_error" | * "global_error" | * "message_error" | - * "webrtc_error" | - */ - type EventSubscriptionType = string; - - interface Configuration { - audio_remote?: HTMLElement; - bandwidth?: { audio: number; video: number; }; - events_listener?: { - events: EventSubscriptionType | EventSubscriptionType[]; - listener: (e: Session.Event) => void - }; - expires?: number; - from?: string; - sip_caps?: Object[]; - sip_headers?: Object[]; - video_local?: HTMLElement; - video_remote?: HTMLElement; - video_size?: { - minWidth?: number; - maxWidth?: number; - minHeight?: number; - maxHeight?: number; - }; - } - - class Call extends Session implements EventTarget { - public acceptTransfer(configuration?: Session.Configuration): number; - public call(to: string, configuration?: Session.Configuration): number; - public dtmf(): number; - public hangup(configuration?: Session.Configuration): number; - public hold(configuration?: Session.Configuration): number; - public info(): number; - public rejectTransfer(): number; - public resume(): number; - public transfer(): number; - } - - namespace Call { - /** - * Should be - * - * Session.EventSubscriptionType | + * "webrtc_error" | + */ + type EventSubscriptionType = string; + + interface Configuration { + audio_remote?: HTMLElement; + bandwidth?: { audio: number; video: number; }; + events_listener?: { + events: EventSubscriptionType | EventSubscriptionType[]; + listener: (e: Session.Event) => void + }; + expires?: number; + from?: string; + sip_caps?: Object[]; + sip_headers?: Object[]; + video_local?: HTMLElement; + video_remote?: HTMLElement; + video_size?: { + minWidth?: number; + maxWidth?: number; + minHeight?: number; + maxHeight?: number; + }; + } + + class Call extends Session implements EventTarget { + public acceptTransfer(configuration?: Session.Configuration): number; + public call(to: string, configuration?: Session.Configuration): number; + public dtmf(): number; + public hangup(configuration?: Session.Configuration): number; + public hold(configuration?: Session.Configuration): number; + public info(): number; + public rejectTransfer(): number; + public resume(): number; + public transfer(): number; + } + + namespace Call { + /** + * Should be + * + * Session.EventSubscriptionType | * "m_early_media" | * "m_local_hold_ok" | * "m_local_hold_nok" | @@ -115,57 +115,57 @@ declare namespace SIPml { * "i_ect_notify" | * "i_ect_requested " | * "m_bfcp_info" | - * "i_info" | - */ - type EventSubscriptionType = Session.EventSubscriptionType; - } - - class Event extends SIPml.Event { - public session: Session; - - public getTransferDestinationFriendlyName(): string; - } - - class Message extends Session { - public send(to: string, content?: any, contentType?: string, configuration?: Session.Configuration): number; - } - - class Publish extends Session { - public publish(content?: any, contentType?: string, configuration?: Session.Configuration): number; - - public unpublish(configuration?: Session.Configuration): void; - } - - class Registration extends Session { - public register(configuration?: Session.Configuration): void; - public unregister(configuration?: Session.Configuration): void; - } - - class Subscribe extends Session implements EventTarget { - public subscribe(to: string, configuration?: Session.Configuration): number; - public unsubscribe(configuration?: Session.Configuration): number; - } - - namespace Subscribe { - /** - * Should be - * - * Session.EventSubscriptionType | "i_notify" - */ - type EventSubscriptionType = Session.EventSubscriptionType; - } - } - - class Stack extends EventTarget { - public constructor(configuration?: Stack.Configuration); - public setConfiguration(configuration: Stack.Configuration): number; - public newSession(type: string, configuration?: Session.Configuration): any; - public start(): number; - public stop(timeout?: number): number; - } - - export namespace Stack { - /** + * "i_info" | + */ + type EventSubscriptionType = Session.EventSubscriptionType; + } + + class Event extends SIPml.Event { + public session: Session; + + public getTransferDestinationFriendlyName(): string; + } + + class Message extends Session { + public send(to: string, content?: any, contentType?: string, configuration?: Session.Configuration): number; + } + + class Publish extends Session { + public publish(content?: any, contentType?: string, configuration?: Session.Configuration): number; + + public unpublish(configuration?: Session.Configuration): void; + } + + class Registration extends Session { + public register(configuration?: Session.Configuration): void; + public unregister(configuration?: Session.Configuration): void; + } + + class Subscribe extends Session implements EventTarget { + public subscribe(to: string, configuration?: Session.Configuration): number; + public unsubscribe(configuration?: Session.Configuration): number; + } + + namespace Subscribe { + /** + * Should be + * + * Session.EventSubscriptionType | "i_notify" + */ + type EventSubscriptionType = Session.EventSubscriptionType; + } + } + + class Stack extends EventTarget { + public constructor(configuration?: Stack.Configuration); + public setConfiguration(configuration: Stack.Configuration): number; + public newSession(type: string, configuration?: Session.Configuration): any; + public start(): number; + public stop(timeout?: number): number; + } + + export namespace Stack { + /** * Should be * * "*" | @@ -179,74 +179,74 @@ declare namespace SIPml { * "i_new_message" | * "m_permission_requested" | * "m_permission_accepted" | - * "m_permission_refused"; - */ - type EventSubscriptionType = string; - - interface Configuration { - bandwidth?: { audio: number; video: number; }; - display_name?: string; - enable_click2call?: boolean; - enable_early_ims?: boolean; - enable_media_stream_cache?: boolean; - enable_rtcweb_breaker?: boolean; - events_listener?: { - events: EventSubscriptionType | EventSubscriptionType[]; - listener: (e: Stack.Event) => void - }; - ice_servers?: Object[]; - impi?: string; - impu?: string; - outbound_proxy_url?: string; - password?: string; - realm?: string; - sip_headers?: Object[]; - video_size?: { - minWidth?: number; - maxWidth?: number; - minHeight?: number; - maxHeight?: number; - }; - websocket_proxy_url?: string; - } - - class Event extends SIPml.Event { - public description: string; - public newSession: Session; - public type: string; - } - } - - function getNavigatorFriendlyName(): string; - - function getNavigatorVersion(): string; - - function getSystemFriendlyName(): string; - - function getWebRtc4AllVersion(): string; - - function haveMediaStream(): boolean; - - function init(readyCallback?: (e:any) => any, errorCallback?: (e:any) => any): boolean; - - function isInitialized(): boolean; - - function isNavigatorOutdated(): boolean; - - function isReady(): boolean; - - function isScreenShareSupported(): boolean; - - function isWebRtcPluginOutdated(): boolean; - - function isWebRtc4AllSupported(): boolean; - - function isWebRtcSupported(): boolean; - - function isWebSocketSupported(): boolean; - - function setDebugLevel(level: string): void; - - function setWebRtcType(type: string): boolean; -} - + * "m_permission_refused"; + */ + type EventSubscriptionType = string; + + interface Configuration { + bandwidth?: { audio: number; video: number; }; + display_name?: string; + enable_click2call?: boolean; + enable_early_ims?: boolean; + enable_media_stream_cache?: boolean; + enable_rtcweb_breaker?: boolean; + events_listener?: { + events: EventSubscriptionType | EventSubscriptionType[]; + listener: (e: Stack.Event) => void + }; + ice_servers?: Object[]; + impi?: string; + impu?: string; + outbound_proxy_url?: string; + password?: string; + realm?: string; + sip_headers?: Object[]; + video_size?: { + minWidth?: number; + maxWidth?: number; + minHeight?: number; + maxHeight?: number; + }; + websocket_proxy_url?: string; + } + + class Event extends SIPml.Event { + public description: string; + public newSession: Session; + public type: string; + } + } + + function getNavigatorFriendlyName(): string; + + function getNavigatorVersion(): string; + + function getSystemFriendlyName(): string; + + function getWebRtc4AllVersion(): string; + + function haveMediaStream(): boolean; + + function init(readyCallback?: (e:any) => any, errorCallback?: (e:any) => any): boolean; + + function isInitialized(): boolean; + + function isNavigatorOutdated(): boolean; + + function isReady(): boolean; + + function isScreenShareSupported(): boolean; + + function isWebRtcPluginOutdated(): boolean; + + function isWebRtc4AllSupported(): boolean; + + function isWebRtcSupported(): boolean; + + function isWebSocketSupported(): boolean; + + function setDebugLevel(level: string): void; + + function setWebRtcType(type: string): boolean; +} + From 2df5e8ac4f73f8d685aeaf1f334360cdcaf91abb Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 20 Aug 2015 17:03:58 -0700 Subject: [PATCH 123/345] Fixed tests/typings for 'photoswipe'. --- photoswipe/photoswipe-tests.ts | 2 -- photoswipe/photoswipe.d.ts | 10 ++++++++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/photoswipe/photoswipe-tests.ts b/photoswipe/photoswipe-tests.ts index 79125bd05..ca136f3a2 100644 --- a/photoswipe/photoswipe-tests.ts +++ b/photoswipe/photoswipe-tests.ts @@ -6,13 +6,11 @@ function test_defaultUI() { src: "path/to/image.jpg", w: 100, h: 200, - specialProperty: true }, { src: "path/to/image2.jpg", w: 1000, h: 2000, - specialProperty: false } ]; diff --git a/photoswipe/photoswipe.d.ts b/photoswipe/photoswipe.d.ts index b09fe75dd..4916c2123 100644 --- a/photoswipe/photoswipe.d.ts +++ b/photoswipe/photoswipe.d.ts @@ -268,6 +268,16 @@ declare module PhotoSwipe { */ mainClass?: string; + /** + * Undocumented. + */ + mainScrollEndFriction?: number; + + /** + * Undocumented. + */ + panEndFriction?: number; + /** * Function that should return total number of items in gallery. Don't put very complex code here, function is executed very often. * From a0143072d67e316c8d2f1ceac4ab246e156d7c92 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Fri, 21 Aug 2015 06:07:26 +0500 Subject: [PATCH 124/345] lodash: changed _.trunc() method --- lodash/lodash-tests.ts | 6 ++++++ lodash/lodash.d.ts | 27 +++++++++++++++++++++++++-- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 2cbec6853..a63e308ac 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1706,11 +1706,17 @@ result = _.trimRight('-_-abc-_-', '_-'); result = _('-_-abc-_-').trimRight(); result = _('-_-abc-_-').trimRight('_-'); +// _.trunc result = _.trunc('hi-diddly-ho there, neighborino'); result = _.trunc('hi-diddly-ho there, neighborino', 24); result = _.trunc('hi-diddly-ho there, neighborino', { 'length': 24, 'separator': ' ' }); result = _.trunc('hi-diddly-ho there, neighborino', { 'length': 24, 'separator': /,? +/ }); result = _.trunc('hi-diddly-ho there, neighborino', { 'omission': ' […]' }); +result = _('hi-diddly-ho there, neighborino').trunc(); +result = _('hi-diddly-ho there, neighborino').trunc(24); +result = _('hi-diddly-ho there, neighborino').trunc({ 'length': 24, 'separator': ' ' }); +result = _('hi-diddly-ho there, neighborino').trunc({ 'length': 24, 'separator': /,? +/ }); +result = _('hi-diddly-ho there, neighborino').trunc({ 'omission': ' […]' }); // _.unescape result = _.unescape('fred, barney, & pebbles'); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index c088f5459..e9248577a 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -7587,9 +7587,32 @@ declare module _ { trimRight(chars?: string): string; } + //_.trunc + interface TruncOptions { + /** The maximum string length. */ + length?: number; + /** The string to indicate text is omitted. */ + omission?: string; + /** The separator pattern to truncate to. */ + separator?: string|RegExp; + } + interface LoDashStatic { - trunc(str?: string, len?: number): string; - trunc(str?: string, options?: { length?: number; omission?: string; separator?: string|RegExp }): string; + /** + * Truncates string if it’s longer than the given maximum string length. The last characters of the truncated + * string are replaced with the omission string which defaults to "…". + * @param string The string to truncate. + * @param options The options object or maximum string length. + * @return Returns the truncated string. + */ + trunc(string?: string, options?: TruncOptions|number): string; + } + + interface LoDashWrapper { + /** + * @see _.trunc + */ + trunc(options?: TruncOptions|number): string; } //_.unescape From 7b4ab5384c58f9508d4a6d877dc64b5e3a51fee0 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Fri, 21 Aug 2015 07:12:25 +0500 Subject: [PATCH 125/345] lodash: changed _.clone() and _.cloneDeep() methods --- lodash/lodash-tests.ts | 120 +++++++++++++++++++++++++++-------------- lodash/lodash.d.ts | 112 +++++++++++++++++++++++++++++--------- 2 files changed, 168 insertions(+), 64 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 2cbec6853..ef2d5e457 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1091,41 +1091,89 @@ helloWrap2(); * Lang * ********/ -// _.cloneDeep -interface TestCloneDeepFn { +// _.clone +interface TestCloneCustomizerFn { (value: any): any; } -var testCloneDeepFn: TestCloneDeepFn; -result = _.cloneDeep(1); -result = _.cloneDeep(1, testCloneDeepFn); -result = _.cloneDeep(1, testCloneDeepFn, any); -result = _.cloneDeep('a'); -result = _.cloneDeep('a', testCloneDeepFn); -result = _.cloneDeep('a', testCloneDeepFn, any); -result = _.cloneDeep(true); -result = _.cloneDeep(true, testCloneDeepFn); -result = _.cloneDeep(true, testCloneDeepFn, any); -result = _.cloneDeep([1, 2]); -result = _.cloneDeep([1, 2], testCloneDeepFn); -result = _.cloneDeep([1, 2], testCloneDeepFn, any); -result = <{a: {b: number;}}>_.cloneDeep<{a: {b: number;}}>({a: {b: 2}}); -result = <{a: {b: number;}}>_.cloneDeep<{a: {b: number;}}>({a: {b: 2}}, testCloneDeepFn); -result = <{a: {b: number;}}>_.cloneDeep<{a: {b: number;}}>({a: {b: 2}}, testCloneDeepFn, any); -result = _(1).cloneDeep(); -result = _(1).cloneDeep(testCloneDeepFn); -result = _(1).cloneDeep(testCloneDeepFn, any); -result = _('a').cloneDeep(); -result = _('a').cloneDeep(testCloneDeepFn); -result = _('a').cloneDeep(testCloneDeepFn, any); -result = _(true).cloneDeep(); -result = _(true).cloneDeep(testCloneDeepFn); -result = _(true).cloneDeep(testCloneDeepFn, any); -result = _([1, 2]).cloneDeep(); -result = _([1, 2]).cloneDeep(testCloneDeepFn); -result = _([1, 2]).cloneDeep(testCloneDeepFn, any); -result = <{a: {b: number;}}>_({a: {b: 2}}).cloneDeep(); -result = <{a: {b: number;}}>_({a: {b: 2}}).cloneDeep(testCloneDeepFn); -result = <{a: {b: number;}}>_({a: {b: 2}}).cloneDeep(testCloneDeepFn, any); +var testCloneCustomizerFn: TestCloneCustomizerFn; +{ + let result: number; + result = _.clone(42); + result = _.clone(42, false); + result = _.clone(42, false, testCloneCustomizerFn); + result = _.clone(42, false, testCloneCustomizerFn, any); + result = _.clone(42, testCloneCustomizerFn); + result = _.clone(42, testCloneCustomizerFn, any); + result = _(42).clone(); + result = _(42).clone(false); + result = _(42).clone(false, testCloneCustomizerFn); + result = _(42).clone(false, testCloneCustomizerFn, any); + result = _(42).clone(testCloneCustomizerFn); + result = _(42).clone(testCloneCustomizerFn, any); +} +{ + let result: string[]; + result = _.clone([]); + result = _.clone([], false); + result = _.clone([], false, testCloneCustomizerFn); + result = _.clone([], false, testCloneCustomizerFn, any); + result = _.clone([], testCloneCustomizerFn); + result = _.clone([], testCloneCustomizerFn, any); + result = _([]).clone(); + result = _([]).clone(false); + result = _([]).clone(false, testCloneCustomizerFn); + result = _([]).clone(false, testCloneCustomizerFn, any); + result = _([]).clone(testCloneCustomizerFn); + result = _([]).clone(testCloneCustomizerFn, any); +} +{ + let result: {a: {b: number;}}; + result = _.clone<{a: {b: number;}}>({a: {b: 2}}); + result = _.clone<{a: {b: number;}}>({a: {b: 2}}, false); + result = _.clone<{a: {b: number;}}>({a: {b: 2}}, false, testCloneCustomizerFn); + result = _.clone<{a: {b: number;}}>({a: {b: 2}}, false, testCloneCustomizerFn, any); + result = _.clone<{a: {b: number;}}>({a: {b: 2}}, testCloneCustomizerFn); + result = _.clone<{a: {b: number;}}>({a: {b: 2}}, testCloneCustomizerFn, any); + result = _({a: {b: 2}}).clone(); + result = _({a: {b: 2}}).clone(false); + result = _({a: {b: 2}}).clone(false, testCloneCustomizerFn); + result = _({a: {b: 2}}).clone(false, testCloneCustomizerFn, any); + result = _({a: {b: 2}}).clone(testCloneCustomizerFn); + result = _({a: {b: 2}}).clone(testCloneCustomizerFn, any); +} + +// _.cloneDeep +interface TestCloneDeepCustomizerFn { + (value: any): any; +} +var testCloneDeepCustomizerFn: TestCloneDeepCustomizerFn; +{ + let result: number; + result = _.cloneDeep(42); + result = _.cloneDeep(42, testCloneDeepCustomizerFn); + result = _.cloneDeep(42, testCloneDeepCustomizerFn, any); + result = _(42).cloneDeep(); + result = _(42).cloneDeep(testCloneDeepCustomizerFn); + result = _(42).cloneDeep(testCloneDeepCustomizerFn, any); +} +{ + let result: string[]; + result = _.cloneDeep([]); + result = _.cloneDeep([], testCloneDeepCustomizerFn); + result = _.cloneDeep([], testCloneDeepCustomizerFn, any); + result = _([]).cloneDeep(); + result = _([]).cloneDeep(testCloneDeepCustomizerFn); + result = _([]).cloneDeep(testCloneDeepCustomizerFn, any); +} +{ + let result: {a: {b: number;}}; + result = _.cloneDeep<{a: {b: number;}}>({a: {b: 2}}); + result = _.cloneDeep<{a: {b: number;}}>({a: {b: 2}}, testCloneDeepCustomizerFn); + result = _.cloneDeep<{a: {b: number;}}>({a: {b: 2}}, testCloneDeepCustomizerFn, any); + result = _({a: {b: 2}}).cloneDeep(); + result = _({a: {b: 2}}).cloneDeep(testCloneDeepCustomizerFn); + result = _({a: {b: 2}}).cloneDeep(testCloneDeepCustomizerFn, any); +} // _.gt result = _.gt(1, 2); @@ -1262,12 +1310,6 @@ result = <{}>_(testCreateProto).create(testCreateProps).value(); result = _(testCreateProto).create().value(); result = _(testCreateProto).create(testCreateProps).value(); -result = _.clone(stoogesAges); -result = _.clone(stoogesAges, true); -result = _.clone(stoogesAges, true, function (value) { - return _.isElement(value) ? value.cloneNode(false) : undefined; -}); - interface Food { name: string; type: string; diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index c088f5459..16b39a64d 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -5997,6 +5997,88 @@ declare module _ { * Lang * ********/ + //_.clone + interface LoDashStatic { + /** + * Creates a clone of value. If isDeep is true nested objects are cloned, otherwise they are assigned by + * reference. If customizer is provided it’s invoked to produce the cloned values. If customizer returns + * undefined cloning is handled by the method instead. The customizer is bound to thisArg and invoked with up + * to three argument; (value [, index|key, object]). + * Note: This method is loosely based on the structured clone algorithm. The enumerable properties of arguments + * objects and objects created by constructors other than Object are cloned to plain Object objects. An empty + * object is returned for uncloneable values such as functions, DOM nodes, Maps, Sets, and WeakMaps. + * @param value The value to clone. + * @param isDeep Specify a deep clone. + * @param customizer The function to customize cloning values. + * @param thisArg The this binding of customizer. + * @return Returns the cloned value. + */ + clone( + value: T, + isDeep?: boolean, + customizer?: (value: any) => any, + thisArg?: any): T; + + /** + * @see _.clone + */ + clone( + value: T, + customizer?: (value: any) => any, + thisArg?: any): T; + } + + interface LoDashWrapper { + /** + * @see _.clone + */ + clone( + isDeep?: boolean, + customizer?: (value: any) => any, + thisArg?: any): T; + + /** + * @see _.clone + */ + clone( + customizer?: (value: any) => any, + thisArg?: any): T; + } + + interface LoDashArrayWrapper { + /** + * @see _.clone + */ + clone( + isDeep?: boolean, + customizer?: (value: any) => any, + thisArg?: any): T[]; + + /** + * @see _.clone + */ + clone( + customizer?: (value: any) => any, + thisArg?: any): T[]; + } + + interface LoDashObjectWrapper { + /** + * @see _.clone + */ + clone( + isDeep?: boolean, + customizer?: (value: any) => any, + thisArg?: any): T; + + /** + * @see _.clone + */ + clone( + customizer?: (value: any) => any, + thisArg?: any): T; + } + //_.cloneDeep interface LoDashStatic { /** @@ -6007,13 +6089,13 @@ declare module _ { * objects and objects created by constructors other than Object are cloned to plain Object objects. An empty * object is returned for uncloneable values such as functions, DOM nodes, Maps, Sets, and WeakMaps. * @param value The value to deep clone. - * @param callback The function to customize cloning values. + * @param customizer The function to customize cloning values. * @param thisArg The this binding of customizer. * @return Returns the deep cloned value. */ cloneDeep( value: T, - callback?: (value: any) => any, + customizer?: (value: any) => any, thisArg?: any): T; } @@ -6022,7 +6104,7 @@ declare module _ { * @see _.cloneDeep */ cloneDeep( - callback?: (value: any) => any, + customizer?: (value: any) => any, thisArg?: any): T; } @@ -6031,7 +6113,7 @@ declare module _ { * @see _.cloneDeep */ cloneDeep( - callback?: (value: any) => any, + customizer?: (value: any) => any, thisArg?: any): T[]; } @@ -6040,7 +6122,7 @@ declare module _ { * @see _.cloneDeep */ cloneDeep( - callback?: (value: any) => any, + customizer?: (value: any) => any, thisArg?: any): T; } @@ -6496,26 +6578,6 @@ declare module _ { create(properties?: Object): LoDashObjectWrapper; } - //_.clone - interface LoDashStatic { - /** - * Creates a clone of value. If deep is true nested objects will also be cloned, otherwise - * they will be assigned by reference. If a callback is provided it will be executed to produce - * the cloned values. If the callback returns undefined cloning will be handled by the method - * instead. The callback is bound to thisArg and invoked with one argument; (value). - * @param value The value to clone. - * @param deep Specify a deep clone. - * @param callback The function to customize cloning values. - * @param thisArg The this binding of callback. - * @return The cloned value. - **/ - clone( - value: T, - deep?: boolean, - callback?: (value: any) => any, - thisArg?: any): T; - } - //_.defaults interface LoDashStatic { /** From 3c79b26f0b7fd7b9fdac85c2ecd5fd470c490c67 Mon Sep 17 00:00:00 2001 From: Adam Martin Date: Fri, 21 Aug 2015 12:13:17 +0100 Subject: [PATCH 126/345] Allow for ES6 Import of Restangular --- restangular/restangular.d.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/restangular/restangular.d.ts b/restangular/restangular.d.ts index 0c5f698ca..bce357482 100644 --- a/restangular/restangular.d.ts +++ b/restangular/restangular.d.ts @@ -6,6 +6,13 @@ /// +// Support AMD require (copying angular.d.ts approach) +// allows for import {IRequestConfig} from 'restangular' ES6 approach +declare module 'restangular' { + export = restangular; +} + + declare module restangular { From c88d8c76f5f59da1b1af383cc1daad01331ff17b Mon Sep 17 00:00:00 2001 From: Ritzlgrmft Date: Fri, 21 Aug 2015 13:52:33 +0200 Subject: [PATCH 127/345] Property manufacturer added to Cordova.Device --- cordova/plugins/Device.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/cordova/plugins/Device.d.ts b/cordova/plugins/Device.d.ts index 8365ee70f..f8f0f7ca3 100644 --- a/cordova/plugins/Device.d.ts +++ b/cordova/plugins/Device.d.ts @@ -26,6 +26,8 @@ interface Device { uuid: string; /** Get the operating system version. */ version: string; + /** Get the device's manufacturer. */ + manufacturer: string; } declare var device: Device; \ No newline at end of file From ce9ebf79937f86a674f5425623437ed412c85a69 Mon Sep 17 00:00:00 2001 From: vvakame Date: Fri, 21 Aug 2015 21:08:03 +0900 Subject: [PATCH 128/345] refactor run method, use union types --- react-router/react-router.d.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/react-router/react-router.d.ts b/react-router/react-router.d.ts index 51664b03a..f43f56484 100644 --- a/react-router/react-router.d.ts +++ b/react-router/react-router.d.ts @@ -174,8 +174,7 @@ declare module ReactRouter { function create(options: RouterCreateOption): Router; function run(routes: Route, callback: RouterRunCallback): Router; - function run(routes: Route, location: LocationBase, callback: RouterRunCallback): Router; - function run(routes: Route, location: string, callback: RouterRunCallback): Router; + function run(routes: Route, location: LocationBase | string, callback: RouterRunCallback): Router; // From e0aba55050bb23630d5e09642546224cea65acca Mon Sep 17 00:00:00 2001 From: zenorbi Date: Fri, 21 Aug 2015 14:13:49 +0200 Subject: [PATCH 129/345] Rename apn-test to apn-tests --- apn/{apn-test.ts => apn-tests.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename apn/{apn-test.ts => apn-tests.ts} (100%) diff --git a/apn/apn-test.ts b/apn/apn-tests.ts similarity index 100% rename from apn/apn-test.ts rename to apn/apn-tests.ts From 3c18f330a6bd7864b75e8b6ead8141375fb71729 Mon Sep 17 00:00:00 2001 From: Martijn Schrage Date: Fri, 21 Aug 2015 13:54:18 +0200 Subject: [PATCH 130/345] Add typings & tests for oblo-util-0.6.4 --- oblo-util/oblo-util-tests.ts | 29 +++++++++++++++++++++++++++++ oblo-util/oblo-util.d.ts | 31 +++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 oblo-util/oblo-util-tests.ts create mode 100644 oblo-util/oblo-util.d.ts diff --git a/oblo-util/oblo-util-tests.ts b/oblo-util/oblo-util-tests.ts new file mode 100644 index 000000000..401611ce7 --- /dev/null +++ b/oblo-util/oblo-util-tests.ts @@ -0,0 +1,29 @@ +/// + +util.debug = false; + +util.log('Log message'); + +util.error('Error message'); + +util.clip(0, 100, -15); + +util.square(3); + +util.replicate(10, 'x'); + +util.pad(' ', 10, 'short'); + +util.padZero(4, 247); + +util.addslashes('\\"\''); + +util.showJSON({name: 'Clyde', color: 'orange'}, ' ', 7); + +util.showTime(new Date()); + +util.showDate(new Date()); + +util.readDate('15-10-2004'); + +util.setAttr($('#someElement'), 'attrName', false); diff --git a/oblo-util/oblo-util.d.ts b/oblo-util/oblo-util.d.ts new file mode 100644 index 000000000..431cf36b3 --- /dev/null +++ b/oblo-util/oblo-util.d.ts @@ -0,0 +1,31 @@ +// Type definitions for oblo-util v0.6.4 +// Project: https://github.com/Oblosys/oblo-util +// Definitions by: Martijn Schrage +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +/// + +interface ObloUtilStatic { + debug : boolean; + + log(...args: any[]) : void; + error(...args: any[]) : void; + clip(min : number, max : number, x : number) : number; + square(x : number) : number; + replicate(n : number, x : X) : X[]; + pad(c : string, l : number, str : any) : string; + padZero(l : number, n : number) : string; + addslashes(str : string) : string; + showJSON(json : any, indentStr? : string, maxDepth? : number) : string; + showTime(date : Date) : string; + showDate(date : Date) : string; + readDate(dateStr : string) : Date; + setAttr($elt : JQuery, attrName : string, isSet : boolean) : void; +} + +declare var util: ObloUtilStatic; + +declare module "oblo-util" { + export = util; +} From 712b9068033dc6708f17cb526af2bfc4f4f125f5 Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Fri, 21 Aug 2015 14:35:27 +0100 Subject: [PATCH 131/345] Type definitions and tests for upper-case-first --- upper-case-first/upper-case-first.d.ts | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 upper-case-first/upper-case-first.d.ts diff --git a/upper-case-first/upper-case-first.d.ts b/upper-case-first/upper-case-first.d.ts new file mode 100644 index 000000000..21af3d676 --- /dev/null +++ b/upper-case-first/upper-case-first.d.ts @@ -0,0 +1,9 @@ +// Type definitions for upper-case-first +// Project: https://github.com/blakeembrey/upper-case-first +// Definitions by: Sam Saint-Pettersen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "upper-case-first" { + function upperCaseFirst(string: string): string; + export = upperCaseFirst; +} From 46f889f66674fcfe00787df8bf53696b1799fbd2 Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Fri, 21 Aug 2015 14:36:29 +0100 Subject: [PATCH 132/345] Type definitions and tests for upper-case-first --- upper-case-first/upper-case-first-tests.ts | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 upper-case-first/upper-case-first-tests.ts diff --git a/upper-case-first/upper-case-first-tests.ts b/upper-case-first/upper-case-first-tests.ts new file mode 100644 index 000000000..2ca02dd74 --- /dev/null +++ b/upper-case-first/upper-case-first-tests.ts @@ -0,0 +1,6 @@ +/// + +import upperCaseFirst = require('upper-case-first'); + +console.log(upperCaseFirst(null)); // => "" +console.log(upperCaseFirst('string')); // => "String" From 8a1945e638a64ac9985e558420b9d1d31148b691 Mon Sep 17 00:00:00 2001 From: tkQubo Date: Fri, 21 Aug 2015 04:05:44 +0900 Subject: [PATCH 133/345] Add Orchestrator --- orchestrator/orchestrator-test.ts | 106 ++++++++++++++++++++++++++ orchestrator/orchestrator.d.ts | 122 ++++++++++++++++++++++++++++++ 2 files changed, 228 insertions(+) create mode 100644 orchestrator/orchestrator-test.ts create mode 100644 orchestrator/orchestrator.d.ts diff --git a/orchestrator/orchestrator-test.ts b/orchestrator/orchestrator-test.ts new file mode 100644 index 000000000..af9af745c --- /dev/null +++ b/orchestrator/orchestrator-test.ts @@ -0,0 +1,106 @@ +/// +/// + +'use strict'; + +import Orchestrator from 'orchestrator'; + +var orchestrator = new Orchestrator(); + + +// API: + +// +// orchestrator.add(name[, deps][, function]); +// + +orchestrator.add('thing1', function() { + // do stuff +}); +orchestrator.add('thing2', function() { + // do stuff +}); +orchestrator.add('mytask', ['array', 'of', 'task', 'names'], function() { + // Do stuff +}); +orchestrator.add('thing2', function(callback){ + var err: any = null; + // do stuff + callback(err); +}); + + +var Q = require('q'); + +orchestrator.add('thing3', function(){ + var deferred = Q.defer(); + + // do async stuff + setTimeout(function () { + deferred.resolve(); + }, 1); + + return deferred.promise; +}); + + +//TODO: map-stream currently not on DefinitelyTyped +//var map = require('map-stream'); +// +//orchestrator.add('thing4', function(){ +// var stream = map(function (args, cb) { +// cb(null, args); +// }); +// // do stream stuff +// return stream; +//}); + +// +// orchestrator.hasTask(name); +// + +orchestrator.hasTask('thing1'); + +// +// orchestrator.start(tasks...[, cb]); +// + +orchestrator.start('thing1', 'thing2', 'thing3', 'thing4', function (err) { + // all done +}); +orchestrator.start(['thing1','thing2'], ['thing3','thing4']); + + +// +// orchestrator.stop() +// + +orchestrator.stop(); + +// +// orchestrator.on(event, cb); +// + +orchestrator.on('task_start', function (e) { + var message: string = e.message; + var task: string = e.task; + var err: any = e.err; +}); +orchestrator.on('task_stop', function (e) { + var message: string = e.message; + var task: string = e.task; + var duration: number = e.duration; +}); + +// +// orchestrator.onAll(cb); +// + +orchestrator.onAll(function (e) { + var message: string = e.message; + var task: string = e.task; + var err: any = e.err; + var src: string = e.src; +}); + + diff --git a/orchestrator/orchestrator.d.ts b/orchestrator/orchestrator.d.ts new file mode 100644 index 000000000..2948aa927 --- /dev/null +++ b/orchestrator/orchestrator.d.ts @@ -0,0 +1,122 @@ +// Type definitions for Orchestrator +// Project: https://github.com/orchestrator/orchestrator +// Definitions by: Qubo +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare type Strings = string|string[]; + +export interface AddMethodCallback { + /** + * Accept a callback + * @param callback + */ + (callback?: Function): any; + /** + * Return a promise + */ + (): Q.Promise; + /** + * Return a stream: (task is marked complete when stream ends) + */ + (): any; //TODO: stream type should be here e.g. map-stream +} + +/** + * Define a task + */ +export interface AddMethod { + /** + * Define a task + * @param name The name of the task. + * @param deps An array of task names to be executed and completed before your task will run. + * @param fn The function that performs the task's operations. For asynchronous tasks, you need to provide a hint when the task is complete: + *
        + *
      • Take in a callback
      • + *
      • Return a stream or a promise
      • + *
      + */ + (name: string, deps?: string[], fn?: AddMethodCallback|Function): Orchestrator; + /** + * Define a task + * @param name The name of the task. + * @param fn The function that performs the task's operations. For asynchronous tasks, you need to provide a hint when the task is complete: + *
        + *
      • Take in a callback
      • + *
      • Return a stream or a promise
      • + *
      + */ + (name: string, fn?: AddMethodCallback|Function): Orchestrator; +} + +/** + * Start running the tasks + */ +export interface StartMethod { + /** + * Start running the tasks + * @param tasks Tasks to be executed. You may pass any number of tasks as individual arguments. + * @param cb Callback to call after run completed. + */ + (tasks: Strings, cb?: (error?: any) => any): Orchestrator; + /** + * Start running the tasks + * @param tasks Tasks to be executed. You may pass any number of tasks as individual arguments. + * @param cb Callback to call after run completed. + */ + (...tasks: Strings[]/*, cb?: (error: any) => any */): Orchestrator; + //TODO: TypeScript 1.5.3 cannot express varargs followed by callback as a last argument... + (task1: Strings, task2: Strings, cb?: (error?: any) => any): Orchestrator; + (task1: Strings, task2: Strings, task3: Strings, cb?: (error?: any) => any): Orchestrator; + (task1: Strings, task2: Strings, task3: Strings, task4: Strings, cb?: (error?: any) => any): Orchestrator; + (task1: Strings, task2: Strings, task3: Strings, task4: Strings, task5: Strings, cb?: (error?: any) => any): Orchestrator; + (task1: Strings, task2: Strings, task3: Strings, task4: Strings, task5: Strings, task6: Strings, cb?: (error?: any) => any): Orchestrator; +} + +export interface OnCallbackEvent { + message: string; + task: string; + err: any; + duration?: number; +} + +export interface OnAllCallbackEvent extends OnCallbackEvent { + src: string; +} + +declare class Orchestrator { + add: AddMethod; + /** + * Have you defined a task with this name? + * @param name The task name to query + */ + hasTask(name: string): boolean; + start: StartMethod; + stop(): void; + + /** + * Listen to orchestrator internals + * @param event Event name to listen to: + *
        + *
      • start: from start() method, shows you the task sequence + *
      • stop: from stop() method, the queue finished successfully + *
      • err: from stop() method, the queue was aborted due to a task error + *
      • task_start: from _runTask() method, task was started + *
      • task_stop: from _runTask() method, task completed successfully + *
      • task_err: from _runTask() method, task errored + *
      • task_not_found: from start() method, you're trying to start a task that doesn't exist + *
      • task_recursion: from start() method, there are recursive dependencies in your task list + *
      + * @param cb Passes single argument: e: event details + */ + on(event: string, cb: (e: OnCallbackEvent) => any): Orchestrator; + + /** + * Listen to all orchestrator events from one callback + * @param cb Passes single argument: e: event details + */ + onAll(cb: (e: OnAllCallbackEvent) => any): void; +} + +export default Orchestrator; From 8cc0285d3428eed76c01a9c76b27238b59d7ace8 Mon Sep 17 00:00:00 2001 From: tkQubo Date: Fri, 21 Aug 2015 04:13:03 +0900 Subject: [PATCH 134/345] Add missing type annotations --- orchestrator/orchestrator-test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/orchestrator/orchestrator-test.ts b/orchestrator/orchestrator-test.ts index af9af745c..047e00047 100644 --- a/orchestrator/orchestrator-test.ts +++ b/orchestrator/orchestrator-test.ts @@ -23,7 +23,7 @@ orchestrator.add('thing2', function() { orchestrator.add('mytask', ['array', 'of', 'task', 'names'], function() { // Do stuff }); -orchestrator.add('thing2', function(callback){ +orchestrator.add('thing2', function(callback: any){ var err: any = null; // do stuff callback(err); @@ -65,7 +65,7 @@ orchestrator.hasTask('thing1'); // orchestrator.start(tasks...[, cb]); // -orchestrator.start('thing1', 'thing2', 'thing3', 'thing4', function (err) { +orchestrator.start('thing1', 'thing2', 'thing3', 'thing4', function (err: any) { // all done }); orchestrator.start(['thing1','thing2'], ['thing3','thing4']); From 422b006d39dd37fc667ce5464967ee3ff6135092 Mon Sep 17 00:00:00 2001 From: tkQubo Date: Fri, 21 Aug 2015 12:06:21 +0900 Subject: [PATCH 135/345] Use external module --- orchestrator/orchestrator-test.ts | 3 +- orchestrator/orchestrator.d.ts | 229 +++++++++++++++--------------- 2 files changed, 119 insertions(+), 113 deletions(-) diff --git a/orchestrator/orchestrator-test.ts b/orchestrator/orchestrator-test.ts index 047e00047..6f1a4a79b 100644 --- a/orchestrator/orchestrator-test.ts +++ b/orchestrator/orchestrator-test.ts @@ -3,7 +3,7 @@ 'use strict'; -import Orchestrator from 'orchestrator'; +import Orchestrator = require('orchestrator'); var orchestrator = new Orchestrator(); @@ -104,3 +104,4 @@ orchestrator.onAll(function (e) { }); + diff --git a/orchestrator/orchestrator.d.ts b/orchestrator/orchestrator.d.ts index 2948aa927..24ebec8cb 100644 --- a/orchestrator/orchestrator.d.ts +++ b/orchestrator/orchestrator.d.ts @@ -7,116 +7,121 @@ declare type Strings = string|string[]; -export interface AddMethodCallback { - /** - * Accept a callback - * @param callback - */ - (callback?: Function): any; - /** - * Return a promise - */ - (): Q.Promise; - /** - * Return a stream: (task is marked complete when stream ends) - */ - (): any; //TODO: stream type should be here e.g. map-stream +declare module "orchestrator" { + class Orchestrator { + add: Orchestrator.AddMethod; + /** + * Have you defined a task with this name? + * @param name The task name to query + */ + hasTask(name: string): boolean; + start: Orchestrator.StartMethod; + stop(): void; + + /** + * Listen to orchestrator internals + * @param event Event name to listen to: + *
        + *
      • start: from start() method, shows you the task sequence + *
      • stop: from stop() method, the queue finished successfully + *
      • err: from stop() method, the queue was aborted due to a task error + *
      • task_start: from _runTask() method, task was started + *
      • task_stop: from _runTask() method, task completed successfully + *
      • task_err: from _runTask() method, task errored + *
      • task_not_found: from start() method, you're trying to start a task that doesn't exist + *
      • task_recursion: from start() method, there are recursive dependencies in your task list + *
      + * @param cb Passes single argument: e: event details + */ + on(event: string, cb: (e: Orchestrator.OnCallbackEvent) => any): Orchestrator; + + /** + * Listen to all orchestrator events from one callback + * @param cb Passes single argument: e: event details + */ + onAll(cb: (e: Orchestrator.OnAllCallbackEvent) => any): void; + } + + namespace Orchestrator { + interface AddMethodCallback { + /** + * Accept a callback + * @param callback + */ + (callback?: Function): any; + /** + * Return a promise + */ + (): Q.Promise; + /** + * Return a stream: (task is marked complete when stream ends) + */ + (): any; //TODO: stream type should be here e.g. map-stream + } + + /** + * Define a task + */ + interface AddMethod { + /** + * Define a task + * @param name The name of the task. + * @param deps An array of task names to be executed and completed before your task will run. + * @param fn The function that performs the task's operations. For asynchronous tasks, you need to provide a hint when the task is complete: + *
        + *
      • Take in a callback
      • + *
      • Return a stream or a promise
      • + *
      + */ + (name: string, deps?: string[], fn?: AddMethodCallback|Function): Orchestrator; + /** + * Define a task + * @param name The name of the task. + * @param fn The function that performs the task's operations. For asynchronous tasks, you need to provide a hint when the task is complete: + *
        + *
      • Take in a callback
      • + *
      • Return a stream or a promise
      • + *
      + */ + (name: string, fn?: AddMethodCallback|Function): Orchestrator; + } + + /** + * Start running the tasks + */ + interface StartMethod { + /** + * Start running the tasks + * @param tasks Tasks to be executed. You may pass any number of tasks as individual arguments. + * @param cb Callback to call after run completed. + */ + (tasks: Strings, cb?: (error?: any) => any): Orchestrator; + /** + * Start running the tasks + * @param tasks Tasks to be executed. You may pass any number of tasks as individual arguments. + * @param cb Callback to call after run completed. + */ + (...tasks: Strings[]/*, cb?: (error: any) => any */): Orchestrator; + //TODO: TypeScript 1.5.3 cannot express varargs followed by callback as a last argument... + (task1: Strings, task2: Strings, cb?: (error?: any) => any): Orchestrator; + (task1: Strings, task2: Strings, task3: Strings, cb?: (error?: any) => any): Orchestrator; + (task1: Strings, task2: Strings, task3: Strings, task4: Strings, cb?: (error?: any) => any): Orchestrator; + (task1: Strings, task2: Strings, task3: Strings, task4: Strings, task5: Strings, cb?: (error?: any) => any): Orchestrator; + (task1: Strings, task2: Strings, task3: Strings, task4: Strings, task5: Strings, task6: Strings, cb?: (error?: any) => any): Orchestrator; + } + + interface OnCallbackEvent { + message: string; + task: string; + err: any; + duration?: number; + } + + interface OnAllCallbackEvent extends OnCallbackEvent { + src: string; + } + + } + + export = Orchestrator; } - -/** - * Define a task - */ -export interface AddMethod { - /** - * Define a task - * @param name The name of the task. - * @param deps An array of task names to be executed and completed before your task will run. - * @param fn The function that performs the task's operations. For asynchronous tasks, you need to provide a hint when the task is complete: - *
        - *
      • Take in a callback
      • - *
      • Return a stream or a promise
      • - *
      - */ - (name: string, deps?: string[], fn?: AddMethodCallback|Function): Orchestrator; - /** - * Define a task - * @param name The name of the task. - * @param fn The function that performs the task's operations. For asynchronous tasks, you need to provide a hint when the task is complete: - *
        - *
      • Take in a callback
      • - *
      • Return a stream or a promise
      • - *
      - */ - (name: string, fn?: AddMethodCallback|Function): Orchestrator; -} - -/** - * Start running the tasks - */ -export interface StartMethod { - /** - * Start running the tasks - * @param tasks Tasks to be executed. You may pass any number of tasks as individual arguments. - * @param cb Callback to call after run completed. - */ - (tasks: Strings, cb?: (error?: any) => any): Orchestrator; - /** - * Start running the tasks - * @param tasks Tasks to be executed. You may pass any number of tasks as individual arguments. - * @param cb Callback to call after run completed. - */ - (...tasks: Strings[]/*, cb?: (error: any) => any */): Orchestrator; - //TODO: TypeScript 1.5.3 cannot express varargs followed by callback as a last argument... - (task1: Strings, task2: Strings, cb?: (error?: any) => any): Orchestrator; - (task1: Strings, task2: Strings, task3: Strings, cb?: (error?: any) => any): Orchestrator; - (task1: Strings, task2: Strings, task3: Strings, task4: Strings, cb?: (error?: any) => any): Orchestrator; - (task1: Strings, task2: Strings, task3: Strings, task4: Strings, task5: Strings, cb?: (error?: any) => any): Orchestrator; - (task1: Strings, task2: Strings, task3: Strings, task4: Strings, task5: Strings, task6: Strings, cb?: (error?: any) => any): Orchestrator; -} - -export interface OnCallbackEvent { - message: string; - task: string; - err: any; - duration?: number; -} - -export interface OnAllCallbackEvent extends OnCallbackEvent { - src: string; -} - -declare class Orchestrator { - add: AddMethod; - /** - * Have you defined a task with this name? - * @param name The task name to query - */ - hasTask(name: string): boolean; - start: StartMethod; - stop(): void; - - /** - * Listen to orchestrator internals - * @param event Event name to listen to: - *
        - *
      • start: from start() method, shows you the task sequence - *
      • stop: from stop() method, the queue finished successfully - *
      • err: from stop() method, the queue was aborted due to a task error - *
      • task_start: from _runTask() method, task was started - *
      • task_stop: from _runTask() method, task completed successfully - *
      • task_err: from _runTask() method, task errored - *
      • task_not_found: from start() method, you're trying to start a task that doesn't exist - *
      • task_recursion: from start() method, there are recursive dependencies in your task list - *
      - * @param cb Passes single argument: e: event details - */ - on(event: string, cb: (e: OnCallbackEvent) => any): Orchestrator; - - /** - * Listen to all orchestrator events from one callback - * @param cb Passes single argument: e: event details - */ - onAll(cb: (e: OnAllCallbackEvent) => any): void; -} - -export default Orchestrator; From 0089d2ac52903d4e676414632cb69cdffb71894d Mon Sep 17 00:00:00 2001 From: tkQubo Date: Fri, 21 Aug 2015 20:00:13 +0900 Subject: [PATCH 136/345] Add node-notifier --- node-notifier/node-notifier-test.ts | 162 +++++++++++++++++++++++++++ node-notifier/node-notifier.d.ts | 167 ++++++++++++++++++++++++++++ 2 files changed, 329 insertions(+) create mode 100644 node-notifier/node-notifier-test.ts create mode 100644 node-notifier/node-notifier.d.ts diff --git a/node-notifier/node-notifier-test.ts b/node-notifier/node-notifier-test.ts new file mode 100644 index 000000000..dfc4963ac --- /dev/null +++ b/node-notifier/node-notifier-test.ts @@ -0,0 +1,162 @@ +/// +'use strict'; + +import notifier = require('node-notifier'); +import * as path from 'path'; + +notifier.notify({ + title: 'My awesome title', + message: 'Hello from node, Mr. User!', + icon: path.join(__dirname, 'coulson.jpg'), // absolute path (not balloons) + sound: true, // Only Notification Center or Windows Toasters + wait: true // wait with callback until user action is taken on notification +}, function (err: any, response: any) { + // response is response from notification +}); + +notifier.on('click', function (notifierObject: any, options: any) { + // Happens if `wait: true` and user clicks notification +}); + +notifier.on('timeout', function (notifierObject: any, options: any) { + // Happens if `wait: true` and notification closes +}); + +const options = { }; + + +import NotificationCenter = require('node-notifier/notifiers/notificationcenter'); +new NotificationCenter(options).notify(); + +import NotifySend = require('node-notifier/notifiers/notifysend'); +new NotifySend(options).notify(); + +import WindowsToaster = require('node-notifier/notifiers/toaster'); +new WindowsToaster(options).notify(); + +import Growl = require('node-notifier/notifiers/growl'); +new Growl(options).notify(); + +import WindowsBalloon = require('node-notifier/notifiers/balloon'); +new WindowsBalloon(options).notify(); + + +var nn = require('node-notifier'); + +new nn.NotificationCenter(options).notify(); +new nn.NotifySend(options).notify(); +new nn.WindowsToaster(options).notify(options); +new nn.WindowsBalloon(options).notify(options); +new nn.Growl(options).notify(options); + + +// +// All notification options with their defaults: +// + +var NotificationCenter2 = require('node-notifier').NotificationCenter; + +var notifier2 = new NotificationCenter2({ + withFallback: false, // use Growl if <= 10.8? + customPath: void 0 // Relative path if you want to use your fork of terminal-notifier +}); + +notifier2.notify({ + 'title': void 0, + 'subtitle': void 0, + 'message': void 0, + 'sound': false, // Case Sensitive string of sound file (see below) + 'icon': 'Terminal Icon', // Set icon? (Absolute path to image) + 'contentImage': void 0, // Attach image? (Absolute path) + 'open': void 0, // URL to open on click + 'wait': false // if wait for notification to end +}, function(error: any, response: any) { + console.log(response); +}); + +// +// Usage WindowsToaster +// + +var WindowsToaster2 = require('node-notifier').WindowsToaster; + +var notifier3 = new WindowsToaster2({ + withFallback: false, // Fallback to Growl or Balloons? + customPath: void 0 // Relative path if you want to use your fork of toast.exe +}); + +notifier3.notify({ + title: void 0, + message: void 0, + icon: void 0, // absolute path to an icon + sound: false, // true | false. + wait: false, // if wait for notification to end +}, function(error: any, response: any) { + console.log(response); +}); + +// +// Usage Growl +// + +var Growl2 = require('node-notifier').Growl; +import * as fs from 'fs'; + +var notifier4 = new Growl2({ + name: 'Growl Name Used', // Defaults as 'Node' + host: 'localhost', + port: 23053 +}); + +notifier4.notify({ + title: 'Foo', + message: 'Hello World', + icon: fs.readFileSync(__dirname + "/coulson.jpg"), + wait: false, // if wait for user interaction + + // and other growl options like sticky etc. + sticky: false, + label: void 0, + priority: void 0 +}); + +// +// Usage WindowsBalloon +// + +var WindowsBalloon2 = require('node-notifier').WindowsBalloon; + +var notifier5 = new WindowsBalloon2({ + withFallback: false, // Try Windows 8 and Growl first? + customPath: void 0 // Relative path if you want to use your fork of notifu +}); + +notifier5.notify({ + title: void 0, + message: void 0, + sound: false, // true | false. + time: 5000, // How long to show balloons in ms + wait: false, // if wait for notification to end +}, function(error: any, response: any) { + console.log(response); +}); + +// +// Usage NotifySend +// + +var NotifySend2 = require('node-notifier').NotifySend; + +var notifier6 = new NotifySend2(); + +notifier6.notify({ + title: 'Foo', + message: 'Hello World', + icon: __dirname + "/coulson.jpg", + + // .. and other notify-send flags: + urgency: void 0, + time: void 0, + category: void 0, + hint: void 0, +}); diff --git a/node-notifier/node-notifier.d.ts b/node-notifier/node-notifier.d.ts new file mode 100644 index 000000000..d003001a3 --- /dev/null +++ b/node-notifier/node-notifier.d.ts @@ -0,0 +1,167 @@ +// Type definitions for node-notifier +// Project: https://github.com/mikaelbr/node-notifier +// Definitions by: Qubo +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare module "node-notifier" { + import NotificationCenter = require('node-notifier/notifiers/notificationcenter'); + import NotifySend = require("node-notifier/notifiers/notifysend"); + import WindowsToaster = require("node-notifier/notifiers/toaster"); + import WindowsBalloon = require("node-notifier/notifiers/balloon"); + import Growl = require("node-notifier/notifiers/growl"); + + namespace nodeNotifier { + interface NodeNotifier extends NodeJS.EventEmitter { + notify(notification?: Notification, callback?: NotificationCallback): NodeNotifier; + NotificationCenter: NotificationCenter; + NotifySend: NotifySend; + WindowsToaster: WindowsToaster; + WindowsBalloon: WindowsBalloon; + Growl: Growl; + } + + interface Notification { + title?: string; + message?: string; + /** Absolute path (not balloons) */ + icon?: string; + /** Only Notification Center or Windows Toasters */ + sound?: boolean; + /** Wait with callback until user action is taken on notification */ + wait?: boolean; + } + + interface NotificationCallback { + (err: any, response: any): any; + } + + interface Option { + withFallback?: boolean; + customPath?: string; + } + } + + var nodeNotifier: nodeNotifier.NodeNotifier; + + export = nodeNotifier; +} + +declare module "node-notifier/notifiers/notificationcenter" { + import notifier = require('node-notifier'); + + class NotificationCenter { + constructor(option?: notifier.Option); + notify(notification?: NotificationCenter.Notification, callback?: notifier.NotificationCallback): NotificationCenter; + } + + namespace NotificationCenter { + interface Notification extends notifier.Notification { + subtitle?: string; + /** Attach image? (Absolute path) */ + contentImage?: string; + /** URL to open on click */ + open?: string; + } + } + + export = NotificationCenter; +} + +declare module "node-notifier/notifiers/notifysend" { + import notifier = require('node-notifier'); + + class NotifySend { + constructor(option?: notifier.Option); + notify(notification?: NotifySend.Notification, callback?: notifier.NotificationCallback): NotifySend; + } + + namespace NotifySend { + interface Notification { + title?: string; + message?: string; + icon?: string; + /** Specifies the urgency level (low, normal, critical). */ + urgency?: string; + /** Specifies the timeout in milliseconds at which to expire the notification */ + time?: number; + /** Specifies the notification category */ + category?: string; + /** Specifies basic extra data to pass. Valid types are int, double, string and byte. */ + hint?: string; + } + } + + export = NotifySend; +} + +declare module "node-notifier/notifiers/toaster" { + import notifier = require('node-notifier'); + + class WindowsToaster { + constructor(option?: notifier.Option); + notify(notification?: notifier.Notification, callback?: notifier.NotificationCallback): WindowsToaster; + } + + export = WindowsToaster; +} + +declare module "node-notifier/notifiers/growl" { + import notifier = require('node-notifier'); + + class Growl { + constructor(option?: Growl.Option); + notify(notification?: Growl.Notification, callback?: notifier.NotificationCallback): Growl; + } + + namespace Growl { + interface Option { + name?: string; + host?: string; + port?: number; + } + + interface Notification { + title?: string; + message?: string; + /** Absolute path (not balloons) */ + icon?: string; + /** Wait with callback until user action is taken on notification */ + wait?: boolean; + /** whether or not to sticky the notification (defaults to false) */ + sticky?: boolean; + /** type of notification to use (defaults to the first registered type) */ + label: string; + /** the priority of the notification from lowest (-2) to highest (2) */ + priority: number; + } + } + + export = Growl; +} + +declare module "node-notifier/notifiers/balloon" { + import notifier = require('node-notifier'); + + class WindowsBalloon { + constructor(option?: notifier.Option); + notify(notification?: WindowsBalloon.Notification, callback?: notifier.NotificationCallback): WindowsBalloon; + } + + namespace WindowsBalloon { + interface Notification { + title?: string; + message?: string; + /** Only Notification Center or Windows Toasters */ + sound?: boolean; + /** How long to show balloons in ms */ + time?: number; + /** Wait with callback until user action is taken on notification */ + wait?: boolean; + } + } + + export = WindowsBalloon; +} From 0a9004eb587c8143a65a5eeb48171681e8552a6b Mon Sep 17 00:00:00 2001 From: Nick Chang Date: Mon, 10 Aug 2015 17:44:44 -0700 Subject: [PATCH 137/345] CodeMirror: EditorConfiguration.lint can be boolean --- codemirror/codemirror.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/codemirror/codemirror.d.ts b/codemirror/codemirror.d.ts index 86c01141e..06361684d 100644 --- a/codemirror/codemirror.d.ts +++ b/codemirror/codemirror.d.ts @@ -787,7 +787,7 @@ declare module CodeMirror { viewportMargin?: number; /** Optional lint configuration to be used in conjunction with CodeMirror's linter addon. */ - lint?: LintOptions; + lint?: boolean | LintOptions; } interface TextMarkerOptions { From 58fe0b0e72fbea01c059d507512cdedf30d5272d Mon Sep 17 00:00:00 2001 From: Joe Skeen Date: Fri, 21 Aug 2015 09:17:54 -0600 Subject: [PATCH 138/345] Definitions for gulp-plumber --- gulp-plumber/gulp-plumber-tests.ts | 36 +++++++++++++++++++++ gulp-plumber/gulp-plumber.d.ts | 51 ++++++++++++++++++++++++++++++ 2 files changed, 87 insertions(+) create mode 100644 gulp-plumber/gulp-plumber-tests.ts create mode 100644 gulp-plumber/gulp-plumber.d.ts diff --git a/gulp-plumber/gulp-plumber-tests.ts b/gulp-plumber/gulp-plumber-tests.ts new file mode 100644 index 000000000..cf055dad5 --- /dev/null +++ b/gulp-plumber/gulp-plumber-tests.ts @@ -0,0 +1,36 @@ +/// +/// +/// + +import gulp = require('gulp'); +import plumber = require('gulp-plumber'); + +//default behavior +gulp.src('./src/*.ext') + .pipe(plumber()) + .pipe(gulp.dest('./dist')); + +//error handler function +gulp.src('./src/*.ext') + .pipe(plumber((error) => { + console.log(error); + })) + .pipe(gulp.dest('./dist')); + +gulp.src('./src/*.ext') + .pipe(plumber({})) + .pipe(gulp.dest('./dist')); + +gulp.src('./src/*.ext') + .pipe(plumber({ inherit: false })) + .pipe(gulp.dest('./dist')); + +gulp.src('./src/*.ext') + .pipe(plumber({ errorHandler: (error) => console.log(error) })) + .pipe(gulp.dest('./dist')); + +//plumber.stop() +gulp.src('./src/*.scss') + .pipe(plumber()) + .pipe(plumber.stop()) + .pipe(gulp.dest('./dist')); \ No newline at end of file diff --git a/gulp-plumber/gulp-plumber.d.ts b/gulp-plumber/gulp-plumber.d.ts new file mode 100644 index 000000000..0301affd6 --- /dev/null +++ b/gulp-plumber/gulp-plumber.d.ts @@ -0,0 +1,51 @@ +// Type definitions for gulp-plumber +// Project: https://github.com/floatdrop/gulp-plumber +// Definitions by: Joe Skeen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +/** Prevent pipe breaking caused by errors from gulp plugins */ +declare module 'gulp-plumber' { + + /** Prevent pipe breaking caused by errors from gulp plugins */ + interface GulpPlumber { + /** + * Returns Stream, that fixes pipe methods on Streams that are next in pipeline. + * + * @param options Sets options as described in the Options interface + */ + (options?: Options): NodeJS.ReadWriteStream; + /** + * Returns Stream, that fixes pipe methods on Streams that are next in pipeline. + * + * @param errorHandler the function to be attached to the stream on('error') + */ + (errorHandler: ErrorHandlerFunction): NodeJS.ReadWriteStream; + /** returns default behaviour for pipeline after it was piped */ + stop(): NodeJS.ReadWriteStream; + } + + interface Options { + /** + * Handle errors in underlying streams and output them to console. Default true. + * If function passed, it will be attached to stream on('error') + * If false passed, error handler will not be attached + * If undefined passed, default error handler will be attached + */ + errorHandler?: ErrorHandlerFunction | boolean; + /** Monkeypatch pipe functions in underlying streams in pipeline. Default true. */ + inherit?: boolean; + } + + /** an error handler function to be attached to the stream on('error') */ + interface ErrorHandlerFunction { + /** an error handler function to be attached to the stream on('error') */ + (error): void; + } + + /** Prevent pipe breaking caused by errors from gulp plugins */ + var gulpPlumber: GulpPlumber; + + export = gulpPlumber; +} From 4e950fdf8cbd5a8b001be640046f98935c08ce61 Mon Sep 17 00:00:00 2001 From: Joe Skeen Date: Fri, 21 Aug 2015 09:26:23 -0600 Subject: [PATCH 139/345] add explicit any type for error handler parameter (since any type can be thrown in JS) --- gulp-plumber/gulp-plumber.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gulp-plumber/gulp-plumber.d.ts b/gulp-plumber/gulp-plumber.d.ts index 0301affd6..693c4cbf9 100644 --- a/gulp-plumber/gulp-plumber.d.ts +++ b/gulp-plumber/gulp-plumber.d.ts @@ -41,7 +41,7 @@ declare module 'gulp-plumber' { /** an error handler function to be attached to the stream on('error') */ interface ErrorHandlerFunction { /** an error handler function to be attached to the stream on('error') */ - (error): void; + (error: any): void; } /** Prevent pipe breaking caused by errors from gulp plugins */ From 7ff45ed3e3aa9a01f87461d631b4578139cde287 Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Sat, 22 Aug 2015 00:27:35 +0900 Subject: [PATCH 140/345] Add my name --- selenium-webdriver/selenium-webdriver.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index d54ea62fa..61a920f30 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -1,6 +1,6 @@ // Type definitions for Selenium WebDriverJS 2.44.0 // Project: https://code.google.com/p/selenium/ -// Definitions by: Bill Armstrong +// Definitions by: Bill Armstrong , Yuki Kokubun // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module chrome { From 6de08d270c37a0c5c026c1c2b029b1b552ccc927 Mon Sep 17 00:00:00 2001 From: vvakame Date: Sat, 22 Aug 2015 00:31:02 +0900 Subject: [PATCH 141/345] fix imagesloaded/imagesloaded-tests.ts --- imagesloaded/imagesloaded-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imagesloaded/imagesloaded-tests.ts b/imagesloaded/imagesloaded-tests.ts index ad9d3a3db..7ab773822 100644 --- a/imagesloaded/imagesloaded-tests.ts +++ b/imagesloaded/imagesloaded-tests.ts @@ -1,4 +1,4 @@ -/// +/// function test_ctor() { // element From 00db3ad4b0261ff513a7b688263fffb70bdfc972 Mon Sep 17 00:00:00 2001 From: tkQubo Date: Sat, 22 Aug 2015 00:49:45 +0900 Subject: [PATCH 142/345] Rename test file --- orchestrator/{orchestrator-test.ts => orchestrator-tests.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename orchestrator/{orchestrator-test.ts => orchestrator-tests.ts} (100%) diff --git a/orchestrator/orchestrator-test.ts b/orchestrator/orchestrator-tests.ts similarity index 100% rename from orchestrator/orchestrator-test.ts rename to orchestrator/orchestrator-tests.ts From 3455df2c1449774b389c9052a2fa7e7fdac11898 Mon Sep 17 00:00:00 2001 From: tkQubo Date: Sat, 22 Aug 2015 00:51:02 +0900 Subject: [PATCH 143/345] Rename test file --- node-notifier/{node-notifier-test.ts => node-notifier-tests.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename node-notifier/{node-notifier-test.ts => node-notifier-tests.ts} (100%) diff --git a/node-notifier/node-notifier-test.ts b/node-notifier/node-notifier-tests.ts similarity index 100% rename from node-notifier/node-notifier-test.ts rename to node-notifier/node-notifier-tests.ts From 69c5732a871ce4934b76c7a9c3abce5ef306a08d Mon Sep 17 00:00:00 2001 From: tkQubo Date: Sat, 22 Aug 2015 01:11:43 +0900 Subject: [PATCH 144/345] Add envify --- envify/envify-tests.ts | 21 +++++++++++++++++++++ envify/envify.d.ts | 14 ++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 envify/envify-tests.ts create mode 100644 envify/envify.d.ts diff --git a/envify/envify-tests.ts b/envify/envify-tests.ts new file mode 100644 index 000000000..a8dba932e --- /dev/null +++ b/envify/envify-tests.ts @@ -0,0 +1,21 @@ +/// +/// + +import browserify = require('browserify') +import envify = require('envify/custom'); +import fs = require('fs'); + + +var b = browserify('main.js') + , output = fs.createWriteStream('bundle.js'); + +b.transform(envify({ + NODE_ENV: 'development' +})); +b.bundle().pipe(output); + +b.transform(envify({ + _: 'purge' + , NODE_ENV: 'development' +})); + diff --git a/envify/envify.d.ts b/envify/envify.d.ts new file mode 100644 index 000000000..39479f503 --- /dev/null +++ b/envify/envify.d.ts @@ -0,0 +1,14 @@ +// Type definitions for envify +// Project: https://github.com/hughsk/envify +// Definitions by: Qubo +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "envify" { + var envify: Function; + export = envify; +} + +declare module "envify/custom" { + function envify(environment: { [name: string]: any }): Function; + export = envify; +} From 0472794599e36a5ffd3e70e71c24d11e0a3c43fb Mon Sep 17 00:00:00 2001 From: tkQubo Date: Sat, 22 Aug 2015 01:13:31 +0900 Subject: [PATCH 145/345] Add missing semicolon --- envify/envify-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/envify/envify-tests.ts b/envify/envify-tests.ts index a8dba932e..52387a3e6 100644 --- a/envify/envify-tests.ts +++ b/envify/envify-tests.ts @@ -1,7 +1,7 @@ /// /// -import browserify = require('browserify') +import browserify = require('browserify'); import envify = require('envify/custom'); import fs = require('fs'); From e4eed4a208ce764dd36920cf5a4f668379504f81 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Fri, 21 Aug 2015 13:07:36 -0700 Subject: [PATCH 146/345] Encapsulated interfaces, made typings more precise according to documentation, removed 'ParseDefaultOptions' in 'parse'. --- parse/parse.d.ts | 294 ++++++++++++++++++++++++++++++++--------------- 1 file changed, 204 insertions(+), 90 deletions(-) diff --git a/parse/parse.d.ts b/parse/parse.d.ts index cb4fa8b2b..1f3e6993c 100644 --- a/parse/parse.d.ts +++ b/parse/parse.d.ts @@ -15,53 +15,37 @@ declare module Parse { var serverURL: string; var VERSION: string; - interface ParseDefaultOptions { - wait?: boolean; - silent?: boolean; + interface SuccessOption { success?: Function; + } + + interface ErrorOption { error?: Function; + } + + interface BackboneStyleOptions extends SuccessOption, ErrorOption { + } + + interface WaitOption { + /** + * Set to true to wait for the server to confirm success + * before triggering an event. + */ + wait?: boolean; + } + + interface UseMasterKeyOption { + /** + * In Cloud Code and Node only, causes the Master Key to be used for this request. + */ useMasterKey?: boolean; } - interface CollectionOptions { - model?: Object; - query?: Query; - comparator?: string; - } - - interface CollectionAddOptions { - at?: number; - } - - interface RouterOptions { - routes: any; - } - - interface NavigateOptions { - trigger?: boolean; - } - - interface ViewOptions { - model?: any; - collection?: any; - el?: any; - id?: string; - className?: string; - tagName?: string; - attributes?: any[]; - } - - interface PushData { - channels?: string[]; - push_time?: Date; - expiration_time?: Date; - expiration_interval?: number; - where?: Query; - data?: any; - alert?: string; - badge?: string; - sound?: string; - title?: string; + interface SilentOption { + /** + * Set to true to avoid firing the event. + */ + silent?: boolean; } /** @@ -199,7 +183,7 @@ declare module Parse { constructor(name: string, data: any, type?: string); name(): string; url(): string; - save(options?: ParseDefaultOptions): Promise; + save(options?: BackboneStyleOptions): Promise; } @@ -233,7 +217,7 @@ declare module Parse { constructor(arg1?: any, arg2?: any); - current(options?: ParseDefaultOptions): GeoPoint; + current(options?: BackboneStyleOptions): GeoPoint; radiansTo(point: GeoPoint): number; kilometersTo(point: GeoPoint): number; milesTo(point: GeoPoint): number; @@ -332,10 +316,10 @@ declare module Parse { constructor(attributes?: string[], options?: any); static extend(className: string, protoProps?: any, classProps?: any): any; - static fetchAll(list: Object[], options: ParseDefaultOptions): Promise; - static fetchAllIfNeeded(list: Object[], options: ParseDefaultOptions): Promise; - static destroyAll(list: Object[], options?: ParseDefaultOptions): Promise; - static saveAll(list: Object[], options?: ParseDefaultOptions): Promise; + static fetchAll(list: Object[], options: BackboneStyleOptions): Promise; + static fetchAllIfNeeded(list: Object[], options: BackboneStyleOptions): Promise; + static destroyAll(list: Object[], options?: Object.DestroyAllOptions): Promise; + static saveAll(list: Object[], options?: Object.SaveAllOptions): Promise; initialize(): void; add(attr: string, item: any): Object; @@ -344,12 +328,12 @@ declare module Parse { changedAttributes(diff: any): boolean; clear(options: any): any; clone(): Object; - destroy(options?: ParseDefaultOptions): Promise; + destroy(options?: Object.DestroyOptions): Promise; dirty(attr: String): boolean; dirtyKeys(): string[]; escape(attr: string): string; existed(): boolean; - fetch(options?: ParseDefaultOptions): Promise; + fetch(options?: Object.FetchOptions): Promise; get(attr: string): any; getACL(): ACL; has(attr: string): boolean; @@ -361,12 +345,27 @@ declare module Parse { previousAttributes(): any; relation(attr: string): Relation; remove(attr: string, item: any): any; - save(options?: ParseDefaultOptions, arg2?: any, arg3?: any): Promise; - set(key: string, value: any, options?: ParseDefaultOptions): boolean; - setACL(acl: ACL, options?: ParseDefaultOptions): boolean; + save(options?: Object.SaveOptions, arg2?: any, arg3?: any): Promise; + set(key: string, value: any, options?: Object.SetOptions): boolean; + setACL(acl: ACL, options?: BackboneStyleOptions): boolean; unset(attr: string, options?: any): any; - validate(attrs: any, options?: ParseDefaultOptions): boolean; + validate(attrs: any, options?: BackboneStyleOptions): boolean; + } + namespace Object { + interface DestroyOptions extends BackboneStyleOptions, WaitOption, UseMasterKeyOption { } + + interface DestroyAllOptions extends BackboneStyleOptions, UseMasterKeyOption { } + + interface FetchOptions extends BackboneStyleOptions, UseMasterKeyOption { } + + interface SaveOptions extends BackboneStyleOptions, SilentOption, UseMasterKeyOption, WaitOption { } + + interface SaveAllOptions extends BackboneStyleOptions, UseMasterKeyOption { } + + interface SetOptions extends ErrorOption, SilentOption { + promise?: any; + } } /** @@ -420,24 +419,49 @@ declare module Parse { query: Query; comparator: (object: Object) => any; - constructor(models?: Object[], options?: CollectionOptions); + constructor(models?: Object[], options?: Collection.Options); static extend(instanceProps: any, classProps: any): any; initialize(): void; - add(models: any[], options?: CollectionAddOptions): Collection; + add(models: any[], options?: Collection.AddOptions): Collection; at(index: number): Object; chain(): _Chain>; - fetch(options?: ParseDefaultOptions): Promise; - create(model: Object, options?: ParseDefaultOptions): Object; + fetch(options?: Collection.FetchOptions): Promise; + create(model: Object, options?: Collection.CreateOptions): Object; get(id: string): Object; getByCid(cid: any): any; pluck(attr: string): any[]; - remove(model: any, options?: ParseDefaultOptions): Collection; - remove(models: any[], options?: ParseDefaultOptions): Collection; - reset(models: any[], options?: ParseDefaultOptions): Collection; - sort(options?: ParseDefaultOptions): Collection; + remove(model: any, options?: Collection.RemoveOptions): Collection; + remove(models: any[], options?: Collection.RemoveOptions): Collection; + reset(models: any[], options?: Collection.ResetOptions): Collection; + sort(options?: Collection.SortOptions): Collection; toJSON(): any; + } + namespace Collection { + interface Options { + model?: Object; + query?: Query; + comparator?: string; + } + + interface AddOptions extends SilentOption { + /** + * The index at which to add the models. + */ + at?: number; + } + + interface CreateOptions extends BackboneStyleOptions, WaitOption, SilentOption, UseMasterKeyOption { + } + + interface FetchOptions extends BackboneStyleOptions, SilentOption, UseMasterKeyOption { } + + interface RemoveOptions extends SilentOption { } + + interface ResetOptions extends SilentOption { } + + interface SortOptions extends SilentOption { } } /** @@ -549,23 +573,23 @@ declare module Parse { addDescending(key: string[]): Query; ascending(key: string): Query; ascending(key: string[]): Query; - collection(items?: Object[], options?: ParseDefaultOptions): Collection; + collection(items?: Object[], options?: Collection.Options): Collection; containedIn(key: string, values: any[]): Query; contains(key: string, substring: string): Query; containsAll(key: string, values: any[]): Query; - count(options?: ParseDefaultOptions): Promise; + count(options?: Query.CountOptions): Promise; descending(key: string): Query; descending(key: string[]): Query; doesNotExist(key: string): Query; doesNotMatchKeyInQuery(key: string, queryKey: string, query: Query): Query; doesNotMatchQuery(key: string, query: Query): Query; - each(callback: Function, options?: ParseDefaultOptions): Promise; + each(callback: Function, options?: BackboneStyleOptions): Promise; endsWith(key: string, suffix: string): Query; equalTo(key: string, value: any): Query; exists(key: string): Query; - find(options?: ParseDefaultOptions): Promise; - first(options?: ParseDefaultOptions): Promise; - get(objectId: string, options?: ParseDefaultOptions): Promise; + find(options?: Query.FindOptions): Promise; + first(options?: Query.FirstOptions): Promise; + get(objectId: string, options?: Query.GetOptions): Promise; greaterThan(key: string, value: any): Query; greaterThanOrEqualTo(key: string, value: any): Query; include(key: string): Query; @@ -588,6 +612,13 @@ declare module Parse { withinRadians(key: string, point: GeoPoint, maxDistance: number): Query; } + namespace Query { + interface CountOptions extends BackboneStyleOptions, UseMasterKeyOption { } + interface FindOptions extends BackboneStyleOptions, UseMasterKeyOption { } + interface FirstOptions extends BackboneStyleOptions, UseMasterKeyOption { } + interface GetOptions extends BackboneStyleOptions, UseMasterKeyOption { } + } + /** * Represents a Role on the Parse server. Roles represent groupings of * Users for the purposes of granting permissions (e.g. specifying an ACL @@ -608,7 +639,7 @@ declare module Parse { getRoles(): Relation; getUsers(): Relation; getName(): string; - setName(name: string, options?: ParseDefaultOptions): any; + setName(name: string, options?: BackboneStyleOptions): any; } /** @@ -624,17 +655,31 @@ declare module Parse { */ class Router extends Events { - routes: any[]; + routes: Router.RouteMap; - constructor(options?: RouterOptions); + constructor(options?: Router.Options); static extend(instanceProps: any, classProps: any): any; initialize(): void; - navigate(fragment: string, options?: NavigateOptions): Router; + navigate(fragment: string, options?: Router.NavigateOptions): Router; navigate(fragment: string, trigger?: boolean): Router; route(route: string, name: string, callback: Function): Router; } + namespace Router { + interface Options { + routes: RouteMap; + } + + interface RouteMap { + [url: string]: string; + } + + interface NavigateOptions { + trigger?: boolean; + } + } + /** * @class * @@ -647,27 +692,27 @@ declare module Parse { class User extends Object { static current(): User; - static signUp(username: string, password: string, attrs: any, options?: ParseDefaultOptions): Promise; - static logIn(username: string, password: string, options?: ParseDefaultOptions): Promise; + static signUp(username: string, password: string, attrs: any, options?: BackboneStyleOptions): Promise; + static logIn(username: string, password: string, options?: BackboneStyleOptions): Promise; static logOut(): Promise; static allowCustomUserClass(isAllowed: boolean): void; - static become(sessionToken: string, options?: ParseDefaultOptions): Promise; - static requestPasswordReset(email: string, options?: ParseDefaultOptions): Promise; + static become(sessionToken: string, options?: BackboneStyleOptions): Promise; + static requestPasswordReset(email: string, options?: BackboneStyleOptions): Promise; - signUp(attrs: any, options?: ParseDefaultOptions): Promise; - logIn(options?: ParseDefaultOptions): Promise; - fetch(options?: ParseDefaultOptions): Promise; + signUp(attrs: any, options?: BackboneStyleOptions): Promise; + logIn(options?: BackboneStyleOptions): Promise; + fetch(options?: BackboneStyleOptions): Promise; save(arg1: any, arg2: any, arg3: any): Promise; authenticated(): boolean; isCurrent(): boolean; getEmail(): string; - setEmail(email: string, options: ParseDefaultOptions): boolean; + setEmail(email: string, options: BackboneStyleOptions): boolean; getUsername(): string; - setUsername(username: string, options?: ParseDefaultOptions): boolean; + setUsername(username: string, options?: BackboneStyleOptions): boolean; - setPassword(password: string, options?: ParseDefaultOptions): boolean; + setPassword(password: string, options?: BackboneStyleOptions): boolean; getSessionToken(): string; } @@ -695,7 +740,7 @@ declare module Parse { $el: JQuery; attributes: any; - constructor(options?: ViewOptions); + constructor(options?: View.Options); static extend(properties: any, classProperties?: any): any; @@ -704,12 +749,28 @@ declare module Parse { setElement(element: JQuery, delegate?: boolean): View; render(): View; remove(): View; - make(tagName: any, attributes?: any, content?: any): any; + make(tagName: any, attributes?: View.Attribute[], content?: any): any; delegateEvents(events?: any): any; undelegateEvents(): any; } + namespace View { + interface Options { + model?: any; + collection?: any; + el?: any; + id?: string; + className?: string; + tagName?: string; + attributes?: Attribute[]; + } + + interface Attribute { + [attributeName: string]: string | number | boolean; + } + } + module Analytics { function track(name: string, dimensions: any):Promise; @@ -724,9 +785,9 @@ declare module Parse { function init(options?: any): void; function isLinked(user: User): boolean; - function link(user: User, permissions: any, options?: ParseDefaultOptions): void; - function logIn(permissions: any, options?: ParseDefaultOptions): void; - function unlink(user: User, options?: ParseDefaultOptions): void; + function link(user: User, permissions: any, options?: BackboneStyleOptions): void; + function logIn(permissions: any, options?: BackboneStyleOptions): void; + function unlink(user: User, options?: BackboneStyleOptions): void; } /** @@ -796,10 +857,46 @@ declare module Parse { function beforeDelete(arg1: any, func?: (request: BeforeDeleteRequest, response: BeforeDeleteResponse) => void): void; function beforeSave(arg1: any, func?: (request: BeforeSaveRequest, response: BeforeSaveResponse) => void): void; function define(name: string, func?: (request: FunctionRequest, response: FunctionResponse) => void): void; - function httpRequest(options: ParseDefaultOptions): Promise; + function httpRequest(options: HTTPOptions): Promise; function job(name: string, func?: (request: JobRequest, status: JobStatus) => void): HttpResponse; - function run(name: string, data?: any, options?: ParseDefaultOptions): Promise; + function run(name: string, data?: any, options?: BackboneStyleOptions): Promise; function useMasterKey(): void; + + /** + * To use this Cloud Module in Cloud Code, you must require 'buffer' in your JavaScript file. + * + * import Buffer = require("buffer").Buffer; + */ + let HTTPOptions: { + new (): HTTPOptions; + }; + interface HTTPOptions extends FunctionResponse { + /** + * The body of the request. + * If it is a JSON object, then the Content-Type set in the headers must be application/x-www-form-urlencoded or application/json. + * You can also set this to a Buffer object to send raw bytes. + * If you use a Buffer, you should also set the Content-Type header explicitly to describe what these bytes represent. + */ + body?: string | Buffer | Object; + /** + * Defaults to 'false'. + */ + followRedirects?: boolean; + /** + * The headers for the request. + */ + headers?: { + [headerName: string]: string | number | boolean; + }; + /** + *The method of the request (i.e GET, POST, etc). + */ + method?: string; + /** + * The url to send the request to. + */ + url: string; + } } @@ -919,8 +1016,25 @@ declare module Parse { * @namespace */ module Push { + function send(data: PushData, options?: SendOptions): Promise; - function send(data: PushData, options?: ParseDefaultOptions):Promise; + interface PushData { + channels?: string[]; + push_time?: Date; + expiration_time?: Date; + expiration_interval?: number; + where?: Query; + data?: any; + alert?: string; + badge?: string; + sound?: string; + title?: string; + } + + interface SendOptions { + success?: () => void; + error?: (error: Error) => void; + } } /** From 3f66eb02dbf3bbb3a49f43286a05091d754f2b2c Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Fri, 21 Aug 2015 13:09:08 -0700 Subject: [PATCH 147/345] Use 'namespace' keyword in 'parse'. --- parse/parse.d.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/parse/parse.d.ts b/parse/parse.d.ts index 1f3e6993c..f5f7ad4a0 100644 --- a/parse/parse.d.ts +++ b/parse/parse.d.ts @@ -7,7 +7,7 @@ /// /// -declare module Parse { +declare namespace Parse { var applicationId: string; var javaScriptKey: string; @@ -771,7 +771,7 @@ declare module Parse { } } - module Analytics { + namespace Analytics { function track(name: string, dimensions: any):Promise; } @@ -781,7 +781,7 @@ declare module Parse { * @namespace * Provides a set of utilities for using Parse with Facebook. */ - module FacebookUtils { + namespace FacebookUtils { function init(options?: any): void; function isLinked(user: User): boolean; @@ -797,7 +797,7 @@ declare module Parse { * Some functions are only available from Cloud Code. *

      */ - module Cloud { + namespace Cloud { interface CookieOptions { domain?: string; @@ -980,7 +980,7 @@ declare module Parse { * You should not create subclasses of Parse.Op or instantiate Parse.Op * directly. */ - module Op { + namespace Op { interface BaseOperation extends IBaseObject { objects(): any[]; @@ -1015,7 +1015,7 @@ declare module Parse { * @name Parse.Push * @namespace */ - module Push { + namespace Push { function send(data: PushData, options?: SendOptions): Promise; interface PushData { From 79617fa3aac8254c652cf761e33aabf8aebd7bb3 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Fri, 21 Aug 2015 13:12:30 -0700 Subject: [PATCH 148/345] Marked deprecated fields as such with JSDoc and added comment in 'photoswipe'. See https://github.com/dimsemenov/PhotoSwipe/issues/944 --- photoswipe/photoswipe.d.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/photoswipe/photoswipe.d.ts b/photoswipe/photoswipe.d.ts index 4916c2123..16ce87a68 100644 --- a/photoswipe/photoswipe.d.ts +++ b/photoswipe/photoswipe.d.ts @@ -269,12 +269,16 @@ declare module PhotoSwipe { mainClass?: string; /** - * Undocumented. + * NOTE: this property will be ignored in future versions of PhotoSwipe. + * + * @deprecated */ mainScrollEndFriction?: number; /** - * Undocumented. + * NOTE: this property will be ignored in future versions of PhotoSwipe. + * + * @deprecated */ panEndFriction?: number; From dbc8e087d693ac4cf766555dc23ea5bdca074109 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Fri, 21 Aug 2015 14:16:27 -0700 Subject: [PATCH 149/345] Fixed tests/definitions for 'nouislider'. --- nouislider/nouislider-tests.ts | 15 +- nouislider/nouislider.d.ts | 345 +++++++++++++++++---------------- 2 files changed, 181 insertions(+), 179 deletions(-) diff --git a/nouislider/nouislider-tests.ts b/nouislider/nouislider-tests.ts index 837776dfa..2739e609c 100644 --- a/nouislider/nouislider-tests.ts +++ b/nouislider/nouislider-tests.ts @@ -49,17 +49,14 @@ noUiSlider.create(testHtmlElement, { min: 0, max: 10 }, - mode: 'steps', - density: 3, - filter: function(){return 1}, - format: wNumb({ - decimals: 2, - prefix: '$' - }), pips: { - mode: 'range', + mode: 'steps', density: 3, - values: [50, 552, 4651, 4952, 5000, 7080, 9000] + filter: function () { return 1 }, + format: wNumb({ + decimals: 2, + prefix: '$' + }), } }); diff --git a/nouislider/nouislider.d.ts b/nouislider/nouislider.d.ts index e382059fb..b8d0702af 100644 --- a/nouislider/nouislider.d.ts +++ b/nouislider/nouislider.d.ts @@ -1,170 +1,175 @@ -// Type definitions for nouislider v8.0.2 -// Project: https://github.com/leongersen/noUiSlider -// Definitions by: Patrick Davies -// Definitions: https://github.com/borisyankov/DefinitelyTyped -/// - -declare module noUiSlider { - interface Static { - /** - * To create a slider, call noUiSlider.create() with an element and your options. - */ - create(target: HTMLElement, options: Options): void; - } - - interface Options { - /** - * The start option sets the number of handles and their start positions, relative to range. - */ - start: number | number[] | number[][]; - /** - * The connect setting can be used to control the bar between the handles, - * or the edges of the slider. Use "lower" to connect to the lower side, - * or "upper" to connect to the upper side. Setting true sets the bar between the handles. - */ - range: Object; - /** - * noUiSlider offers several ways to handle user interaction. - * The range can be set to drag, and handles can move to taps. - * All these effects are optional, and can be enable by adding their keyword to the behaviour option. - * This option accepts a "-" separated list of "drag", "tap", "fixed", "snap" or "none". - */ - connect?: string | boolean; - /** - * When using two handles, the minimum distance between the handles can be set using the margin option. - * The margin value is relative to the value set in 'range'. - * This option is only available on standard linear sliders. - */ - margin?: number; - /** - * The limit option is the oposite of the margin option, - * limiting the maximum distance between two handles. - * As with the margin option, the limit option can only be used on linear sliders. - */ - limit?: number; - /** - * By default, the slider slides fluently. - * In order to make the handles jump between intervals, you can use this option. - * The step option is relative to the values provided to range. - */ - step?: number; - /** - * The orientation setting can be used to set the slider to "vertical" or "horizontal". - * Set dimensions! Vertical sliders don't assume a default height, so you'll need to set one. - * You can use any unit you want, including % or px. - */ - orientation?: string; - /** - * By default the sliders are top-to-bottom and left-to-right, - * but you can change this using the direction option, - * which decides where the upper side of the slider is. - */ - direction?: string; - /** - * Set the animate option to false to prevent the slider from animating to a new value with when calling .val(). - */ - animate?: boolean; - /** - * All values on the slider are part of a range. The range has a minimum and maximum value. - */ - behaviour?: string; - /** - * To format the slider output, noUiSlider offers a format option. - * Simply specify to and from functions to encode and decode the values. - * See manual formatting to the right for usage information. - * By default, noUiSlider will format output with 2 decimals. - */ - format?: Object | ((...args:any[]) => any); - - } - - interface PipsOptions { - /** - * The range mode uses the slider range to determine where the pips should be. A pip is generated for every percentage specified. - * - * Like range, the steps mode uses the slider range. In steps mode, a pip is generated for every step. - * The filter option can be used to filter the generated pips. - * The filter function must return 0 (no value), 1 (large value) or 2 (small value). - * - * In positions mode, pips are generated at percentage-based positions on the slider. Optionally, the stepped option can be set to true to match the pips to the slider steps. - * - * The count mode can be used to generate a fixed number of pips. As with positions mode, the stepped option can be used. - * - * The values mode is similar to positions, but it accepts values instead of percentages. The stepped option can be used for this mode. - * - */ - mode: string; - /** - * Range Mode: percentage for range mode - * Step Mode: step number for steps - * Positions Mode: percentage-based positions on the slider - * Count Mode: positions between pips - */ - density?: number; - /** - * Step Mode: The filter option can be used to filter the generated pips. - * The filter function must return 0 (no value), 1 (large value) or 2 (small value). - */ - filter?: (...args:any[]) => number; - /** - * format for step mode - * see noUiSlider format - */ - format?: Object; - /** - * - * values for positions and values mode - * number pips for count mode - */ - values?: number | number[]; - /** - * stepped option for positions, values and count mode - */ - stepped?: boolean; - } - - interface Callback { - /** - * Array for both one-handle and two-handle sliders. It contains the current slider values, - * with formatting applied. - */ - (values: any[], handle: number, unencoded: number): void - } - - - interface noUiSlider { - /** - * Bind event to the slider. - */ - on(eventName: string, callback: Callback): void; - /** - * Unbind event to the slider. - */ - off(eventName: string): void; - /** - * Destroy's the slider. - */ - destroy(): void; - - /** - * To get the current slider value. For one-handle sliders, calling .get() will return the value. - * For two-handle sliders, an array[value, value] will be returned. - */ - get(): number | number[]; - /** - * noUiSlider will keep your values within the slider range, which saves you a bunch of validation. - * If you have configured the slider to use one handle, you can change the current value by passing - * a number to the .set() method. If you have two handles, pass an array. One-handled sliders - * will also accept arrays. Within an array, you can set one position to null - * if you want to leave a handle unchanged. - */ - set(value: number | number[]): void; - } - - interface Instance extends HTMLElement { - noUiSlider: noUiSlider - } -} - -declare var noUiSlider: noUiSlider.Static; - +// Type definitions for nouislider v8.0.2 +// Project: https://github.com/leongersen/noUiSlider +// Definitions by: Patrick Davies +// Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + +declare module noUiSlider { + interface Static { + /** + * To create a slider, call noUiSlider.create() with an element and your options. + */ + create(target: HTMLElement, options: Options): void; + } + + interface Options { + /** + * The start option sets the number of handles and their start positions, relative to range. + */ + start: number | number[] | number[][]; + /** + * The connect setting can be used to control the bar between the handles, + * or the edges of the slider. Use "lower" to connect to the lower side, + * or "upper" to connect to the upper side. Setting true sets the bar between the handles. + */ + range: Object; + /** + * noUiSlider offers several ways to handle user interaction. + * The range can be set to drag, and handles can move to taps. + * All these effects are optional, and can be enable by adding their keyword to the behaviour option. + * This option accepts a "-" separated list of "drag", "tap", "fixed", "snap" or "none". + */ + connect?: string | boolean; + /** + * When using two handles, the minimum distance between the handles can be set using the margin option. + * The margin value is relative to the value set in 'range'. + * This option is only available on standard linear sliders. + */ + margin?: number; + /** + * The limit option is the oposite of the margin option, + * limiting the maximum distance between two handles. + * As with the margin option, the limit option can only be used on linear sliders. + */ + limit?: number; + /** + * By default, the slider slides fluently. + * In order to make the handles jump between intervals, you can use this option. + * The step option is relative to the values provided to range. + */ + step?: number; + /** + * The orientation setting can be used to set the slider to "vertical" or "horizontal". + * Set dimensions! Vertical sliders don't assume a default height, so you'll need to set one. + * You can use any unit you want, including % or px. + */ + orientation?: string; + /** + * By default the sliders are top-to-bottom and left-to-right, + * but you can change this using the direction option, + * which decides where the upper side of the slider is. + */ + direction?: string; + /** + * Set the animate option to false to prevent the slider from animating to a new value with when calling .val(). + */ + animate?: boolean; + /** + * All values on the slider are part of a range. The range has a minimum and maximum value. + */ + behaviour?: string; + /** + * To format the slider output, noUiSlider offers a format option. + * Simply specify to and from functions to encode and decode the values. + * See manual formatting to the right for usage information. + * By default, noUiSlider will format output with 2 decimals. + */ + format?: Object | ((...args:any[]) => any); + + /** + * Allows you to generate points along the slider. + */ + pips: PipsOptions; + } + + interface PipsOptions { + /** + * The 'range' mode uses the slider range to determine where the pips should be. A pip is generated for every percentage specified. + * + * The 'steps', like 'range', uses the slider range. In steps mode, a pip is generated for every step. + * The 'filter' option can be used to filter the generated pips from the 'steps' options' + * The filter function must return 0 (no value), 1 (large value) or 2 (small value). + * + * In 'positions' mode, pips are generated at percentage-based positions on the slider. + * Optionally, the stepped option can be set to true to match the pips to the slider steps. + * + * The 'count' mode can be used to generate a fixed number of pips. As with positions mode, the stepped option can be used. + * + * The 'values' mode is similar to positions, but it accepts values instead of percentages. The stepped option can be used for this mode. + * + */ + mode: string; // "range" | "steps" | "positions" | "count" | "values" + /** + * Range Mode: percentage for range mode + * Step Mode: step number for steps + * Positions Mode: percentage-based positions on the slider + * Count Mode: positions between pips + */ + density?: number; + /** + * Step Mode: The filter option can be used to filter the generated pips. + * The filter function must return 0 (no value), 1 (large value) or 2 (small value). + */ + filter?: (...args: any[]) => number; + /** + * format for step mode + * see noUiSlider format + */ + format?: Object; + /** + * + * values for positions and values mode + * number pips for count mode + */ + values?: number | number[]; + /** + * stepped option for positions, values and count mode + */ + stepped?: boolean; + } + + interface Callback { + /** + * Array for both one-handle and two-handle sliders. It contains the current slider values, + * with formatting applied. + */ + (values: any[], handle: number, unencoded: number): void + } + + + interface noUiSlider { + /** + * Bind event to the slider. + */ + on(eventName: string, callback: Callback): void; + /** + * Unbind event to the slider. + */ + off(eventName: string): void; + /** + * Destroy's the slider. + */ + destroy(): void; + + /** + * To get the current slider value. For one-handle sliders, calling .get() will return the value. + * For two-handle sliders, an array[value, value] will be returned. + */ + get(): number | number[]; + /** + * noUiSlider will keep your values within the slider range, which saves you a bunch of validation. + * If you have configured the slider to use one handle, you can change the current value by passing + * a number to the .set() method. If you have two handles, pass an array. One-handled sliders + * will also accept arrays. Within an array, you can set one position to null + * if you want to leave a handle unchanged. + */ + set(value: number | number[]): void; + } + + interface Instance extends HTMLElement { + noUiSlider: noUiSlider + } +} + +declare var noUiSlider: noUiSlider.Static; + From 0f0a9a25b705c077794dcadd5940165bf0284b4d Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Fri, 21 Aug 2015 14:19:01 -0700 Subject: [PATCH 150/345] Use const enum for 'filter' result in 'nouislider'. --- nouislider/nouislider.d.ts | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/nouislider/nouislider.d.ts b/nouislider/nouislider.d.ts index b8d0702af..9b6a84902 100644 --- a/nouislider/nouislider.d.ts +++ b/nouislider/nouislider.d.ts @@ -5,12 +5,10 @@ /// declare module noUiSlider { - interface Static { - /** - * To create a slider, call noUiSlider.create() with an element and your options. - */ - create(target: HTMLElement, options: Options): void; - } + /** + * To create a slider, call noUiSlider.create() with an element and your options. + */ + function create(target: HTMLElement, options: Options): void; interface Options { /** @@ -110,7 +108,7 @@ declare module noUiSlider { * Step Mode: The filter option can be used to filter the generated pips. * The filter function must return 0 (no value), 1 (large value) or 2 (small value). */ - filter?: (...args: any[]) => number; + filter?: (...args: any[]) => PipFilterResult; /** * format for step mode * see noUiSlider format @@ -128,6 +126,12 @@ declare module noUiSlider { stepped?: boolean; } + const enum PipFilterResult { + NoValue, + LargeValue, + SmallValue, + } + interface Callback { /** * Array for both one-handle and two-handle sliders. It contains the current slider values, @@ -170,6 +174,3 @@ declare module noUiSlider { noUiSlider: noUiSlider } } - -declare var noUiSlider: noUiSlider.Static; - From 371ffebdb032cdaf67d9dcc175a62b8a71946f86 Mon Sep 17 00:00:00 2001 From: tpodolak Date: Fri, 21 Aug 2015 23:21:45 +0200 Subject: [PATCH 151/345] Added support for authenticateAndContinue --- winrt/winrt.d.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/winrt/winrt.d.ts b/winrt/winrt.d.ts index b8b40f7cd..f3be7feac 100644 --- a/winrt/winrt.d.ts +++ b/winrt/winrt.d.ts @@ -1541,6 +1541,7 @@ declare module Windows { device, printTaskSettings, cameraSettings, + webAuthenticationBrokerContinuation } export interface IActivatedEventArgs { kind: Windows.ApplicationModel.Activation.ActivationKind; @@ -8489,11 +8490,17 @@ declare module Windows { export interface IWebAuthenticationBrokerStatics { authenticateAsync(options: Windows.Security.Authentication.Web.WebAuthenticationOptions, requestUri: Windows.Foundation.Uri, callbackUri: Windows.Foundation.Uri): Windows.Foundation.IAsyncOperation; authenticateAsync(options: Windows.Security.Authentication.Web.WebAuthenticationOptions, requestUri: Windows.Foundation.Uri): Windows.Foundation.IAsyncOperation; + authenticateAndContinue(requestUri: Windows.Foundation.Uri): void; + authenticateAndContinue(requestUri: Windows.Foundation.Uri, callbackUri: Windows.Foundation.Uri): void; + authenticateAndContinue(requestUri: Windows.Foundation.Uri, callbackUri: Windows.Foundation.Uri, continuationData: Windows.Foundation.Collections.ValueSet, options: Windows.Security.Authentication.Web.WebAuthenticationOptions): void; getCurrentApplicationCallbackUri(): Windows.Foundation.Uri; } export class WebAuthenticationBroker { static authenticateAsync(options: Windows.Security.Authentication.Web.WebAuthenticationOptions, requestUri: Windows.Foundation.Uri, callbackUri: Windows.Foundation.Uri): Windows.Foundation.IAsyncOperation; static authenticateAsync(options: Windows.Security.Authentication.Web.WebAuthenticationOptions, requestUri: Windows.Foundation.Uri): Windows.Foundation.IAsyncOperation; + static authenticateAndContinue(requestUri: Windows.Foundation.Uri): void; + static authenticateAndContinue(requestUri: Windows.Foundation.Uri, callbackUri: Windows.Foundation.Uri): void; + static authenticateAndContinue(requestUri: Windows.Foundation.Uri, callbackUri: Windows.Foundation.Uri, continuationData: Windows.Foundation.Collections.ValueSet, options: Windows.Security.Authentication.Web.WebAuthenticationOptions): void; static getCurrentApplicationCallbackUri(): Windows.Foundation.Uri; } } From 6838547dc695db2882a8f1e9565b0c154d94ce1b Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Fri, 21 Aug 2015 14:27:52 -0700 Subject: [PATCH 152/345] Fixed 'nodemailer' tests by adding 'service' property in 'nodemailer-smtp-transport'. --- .../nodemailer-smtp-transport.d.ts | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/nodemailer-smtp-transport/nodemailer-smtp-transport.d.ts b/nodemailer-smtp-transport/nodemailer-smtp-transport.d.ts index a12d66991..3a4c626b0 100644 --- a/nodemailer-smtp-transport/nodemailer-smtp-transport.d.ts +++ b/nodemailer-smtp-transport/nodemailer-smtp-transport.d.ts @@ -18,6 +18,40 @@ declare module "nodemailer-smtp-transport" { } export interface SmtpOptions { + /** + * Fills in certain SMTP configurations options (e.g. 'host', 'port', and 'secure') for + * well-known services. Possible values: + * - '1und1' + * - 'AOL' + * - 'DebugMail.io' + * - 'DynectEmail' + * - 'FastMail' + * - 'GandiMail' + * - 'Gmail' + * - 'Godaddy' + * - 'GodaddyAsia' + * - 'GodaddyEurope' + * - 'hot.ee' + * - 'Hotmail' + * - 'iCloud' + * - 'mail.ee' + * - 'Mail.ru' + * - 'Mailgun' + * - 'Mailjet' + * - 'Mandrill' + * - 'Naver' + * - 'Postmark' + * - 'QQ' + * - 'QQex' + * - 'SendCloud' + * - 'SendGrid' + * - 'SES' + * - 'Sparkpost' + * - 'Yahoo' + * - 'Yandex' + * - 'Zoho' + */ + service?: string; /** * is the port to connect to (defaults to 25 or 465) */ From 39907d8c4d6799d92fac0912f6453ae5c56cef25 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Fri, 21 Aug 2015 14:33:07 -0700 Subject: [PATCH 153/345] Added missing options properties in 'node_redis'. --- node_redis/node_redis.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/node_redis/node_redis.d.ts b/node_redis/node_redis.d.ts index 8505556fb..4328e299b 100644 --- a/node_redis/node_redis.d.ts +++ b/node_redis/node_redis.d.ts @@ -17,6 +17,11 @@ declare module 'redis' { socket_nodelay?: boolean; no_ready_check?: boolean; enable_offline_queue?: boolean; + retry_max_delay?: number; + connect_timeout?: boolean; + max_attempts?: number; + auth_pass?: string; + family?: string; // "IPv4" | "IPv6" } interface Command { From 9cca17f21da895e45d04b1618b74ac160910f08c Mon Sep 17 00:00:00 2001 From: Michael Randolph Date: Fri, 21 Aug 2015 17:36:40 -0400 Subject: [PATCH 154/345] Fixed fabric so noImplicitAny would stop complaining --- fabricjs/fabricjs-tests.ts | 38 +++++++++++++++--------------- fabricjs/fabricjs.d.ts | 48 +++++++++++++++++++------------------- 2 files changed, 43 insertions(+), 43 deletions(-) diff --git a/fabricjs/fabricjs-tests.ts b/fabricjs/fabricjs-tests.ts index 89c882b05..5800879f3 100644 --- a/fabricjs/fabricjs-tests.ts +++ b/fabricjs/fabricjs-tests.ts @@ -34,8 +34,8 @@ function sample1() { function sample2() { - var dot, i, - t1, t2, + var dot: fabric.ICircle, i: number, + t1: number, t2: number, startTimer = function() { t1 = new Date().getTime(); return t1; @@ -89,16 +89,16 @@ function sample2() { function sample3() { - var $ = function(id) { return document.getElementById(id) }; + var $: (id: string) => HTMLElement = function(id: string) { return document.getElementById(id) }; - function applyFilter(index, filter) { - var obj = canvas.getActiveObject(); + function applyFilter(index: number, filter: any) { + var obj: fabric.IImage = canvas.getActiveObject(); obj.filters[index] = filter; obj.applyFilters(canvas.renderAll.bind(canvas)); } - function applyFilterValue(index, prop, value) { - var obj = canvas.getActiveObject(); + function applyFilterValue(index: number, prop: string, value: any) { + var obj: fabric.IImage = canvas.getActiveObject(); if (obj.filters[index]) { obj.filters[index][prop] = value; obj.applyFilters(canvas.renderAll.bind(canvas)); @@ -214,7 +214,7 @@ function sample3() { function sample4() { var canvas = new fabric.Canvas('c'); - var $ = function(id) { return document.getElementById(id); }; + var $: (id: string) => HTMLElement = function(id: string) { return document.getElementById(id); }; var rect = new fabric.Rect({ width: 100, @@ -339,10 +339,10 @@ function sample6() { canvas.centerObject(obj); canvas.add(obj); - canvas.add(obj.clone(() => {}).set({ left: 100, top: 100, angle: -15 })); - canvas.add(obj.clone(() => {}).set({ left: 480, top: 100, angle: 15 })); - canvas.add(obj.clone(() => {}).set({ left: 100, top: 400, angle: -15 })); - canvas.add(obj.clone(() => {}).set({ left: 480, top: 400, angle: 15 })); + canvas.add(obj.clone(() => { }).set({ left: 100, top: 100, angle: -15 })); + canvas.add(obj.clone(() => { }).set({ left: 480, top: 100, angle: 15 })); + canvas.add(obj.clone(() => { }).set({ left: 100, top: 400, angle: -15 })); + canvas.add(obj.clone(() => { }).set({ left: 480, top: 400, angle: 15 })); canvas.on('mouse:move', function(options) { var p = canvas.getPointer(options.e); @@ -456,7 +456,7 @@ function sample8() { top = fabric.util.getRandomInt(0 + offset, 500 - offset), angle = fabric.util.getRandomInt(-20, 40), width = fabric.util.getRandomInt(30, 50), - opacity = (function(min, max) { return Math.random() * (max - min) + min; })(0.5, 1); + opacity = (function(min: number, max: number) { return Math.random() * (max - min) + min; })(0.5, 1); switch (className) { @@ -522,7 +522,7 @@ function sample8() { break; case 'shape': - var id = element.id, match; + var id: any = element.id, match: RegExpExecArray; if (match = /\d+$/.exec(id)) { fabric.loadSVGFromURL('../assets/' + match[0] + '.svg', function(objects, options) { var loadedObject = fabric.util.groupSVGElements(objects, options); @@ -586,7 +586,7 @@ function sample8() { } }; - var supportsInputOfType = function(type) { + var supportsInputOfType = function(type: string) { return function() { var el = document.createElement('input'); try { @@ -746,7 +746,7 @@ function sample8() { canvas.on('object:selected', onObjectSelected); canvas.on('group:selected', onObjectSelected); - function onObjectSelected(e) { + function onObjectSelected(e: fabric.IEvent) { var selectedObject = e.target; for (var i = activeObjectButtons.length; i--;) { @@ -1033,7 +1033,7 @@ function sample8() { }; canvas.on('object:selected', function(e: fabric.IEvent) { - slider.value = String((e.target).lineHeight ); + slider.value = String((e.target).lineHeight); }); })(); } @@ -1050,6 +1050,6 @@ function sample8() { function sample9() { var canvas = new fabric.Canvas('c'); - canvas.setBackgroundImage('yolo.jpg',() => { "a" }, { opacity: 45 }); - canvas.setBackgroundImage('yolo.jpg',() => { "a" }); + canvas.setBackgroundImage('yolo.jpg', () => { "a" }, { opacity: 45 }); + canvas.setBackgroundImage('yolo.jpg', () => { "a" }); } diff --git a/fabricjs/fabricjs.d.ts b/fabricjs/fabricjs.d.ts index 503b8c7db..0eb6bacb7 100644 --- a/fabricjs/fabricjs.d.ts +++ b/fabricjs/fabricjs.d.ts @@ -1,6 +1,6 @@ // Type definitions for FabricJS v1.5.0 // Project: http://fabricjs.com/ -// Definitions by: Oliver Klemencic , Joseph Livecchi +// Definitions by: Oliver Klemencic , Joseph Livecchi , Michael Randolph // Definitions: https://github.com/borisyankov/DefinitelyTyped /* tslint:disable:no-unused-variable */ @@ -41,7 +41,7 @@ declare module fabric { * @param {Function} callback * @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created. */ - function loadSVGFromString(string: string, callback: (results: IObject[], options: any) => void, reviver?: Function); + function loadSVGFromString(string: string, callback: (results: IObject[], options: any) => void, reviver?: Function): void; /** * Takes url corresponding to an SVG document, and parses it into a set of fabric objects. * Note that SVG is fetched via XMLHttpRequest, so it needs to conform to SOP (Same Origin Policy) @@ -49,14 +49,14 @@ declare module fabric { * @param {Function} callback * @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created. */ - function loadSVGFromURL(url: string, callback: (results: IObject[], options: any) => void, reviver?: Function); + function loadSVGFromURL(url: string, callback: (results: IObject[], options: any) => void, reviver?: Function): void; /** * Returns CSS rules for a given SVG document * @param {SVGDocument} doc SVG document to parse */ function getCSSRules(doc: SVGElement): any; - function parseElements(elements: any[], callback: Function, options: any, reviver?: Function); + function parseElements(elements: any[], callback: Function, options: any, reviver?: Function): void; /** * Parses "points" attribute, returning an array of values * @param {String} points points attribute string @@ -99,7 +99,7 @@ declare module fabric { * @param {Function} callback Callback to call when parsing is finished; It's being passed an array of elements (parsed from a document). * @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created. */ - function parseSVGDocument(doc: SVGElement, callback: (results: IObject[], options: any) => void, reviver?: Function); + function parseSVGDocument(doc: SVGElement, callback: (results: IObject[], options: any) => void, reviver?: Function): void; /** * Parses "transform" attribute, returning an array of values * @param {String} attributeValue String containing attribute value @@ -111,11 +111,11 @@ declare module fabric { /** * Wrapper around `console.log` (when available) */ - function log(...values: any[]); + function log(...values: any[]): void; /** * Wrapper around `console.warn` (when available) */ - function warn(...values: any[]); + function warn(...values: any[]): void; //////////////////////////////////////////////////// // Classes @@ -438,7 +438,7 @@ declare module fabric { /** * Sets source of this color (where source is an array representation; ex: [200, 200, 100, 1]) */ - setSource(source: number[]); + setSource(source: number[]): void; /** * Returns color represenation in RGB format ex: rgb(0-255,0-255,0-255) @@ -474,7 +474,7 @@ declare module fabric { * Sets value of alpha channel for this color * @param {Number} alpha Alpha value 0-1 */ - setAlpha(alpha: number); + setAlpha(alpha: number): void; /** * Transforms color to its grayscale representation @@ -627,17 +627,17 @@ declare module fabric { /** * Appends a point to intersection */ - appendPoint(point: IPoint); + appendPoint(point: IPoint): void; /** * Appends points to intersection */ - appendPoints(points: IPoint[]); + appendPoints(points: IPoint[]): void; } interface IIntersectionStatic { /** * Intersection class */ - new (status?: string); + new (status?: string): void; /** * Checks if polygon intersects another polygon */ @@ -1313,7 +1313,7 @@ declare module fabric { /** * Callback; invoked right before object is about to be scaled/rotated */ - onBeforeScaleRotate(target: IObject); + onBeforeScaleRotate(target: IObject): void; // Functions from object straighten mixin // -------------------------------------------------------------------------------------------------------------------------------- @@ -1839,12 +1839,12 @@ declare module fabric { filters: IBaseFilter[]; } interface IImage extends IObject, IImageOptions { - initialize(element?: string|HTMLImageElement, options?: IImageOptions); + initialize(element?: string|HTMLImageElement, options?: IImageOptions): void; /** * Applies filters assigned to this image (from "filters" array) * @param {Function} callback Callback is invoked when all filters have been applied and new image is generated */ - applyFilters(callback: Function); + applyFilters(callback: Function): void; /** * Returns a clone of an instance * @param {Function} callback Callback is invoked with a clone as a first argument @@ -1871,7 +1871,7 @@ declare module fabric { * @return {String} Source of an image */ getSrc(): string; - render(ctx: CanvasRenderingContext2D, noTransform: boolean); + render(ctx: CanvasRenderingContext2D, noTransform: boolean): void; /** * Sets image element for this instance to a specified one. @@ -2539,7 +2539,7 @@ declare module fabric { * Sets object's properties from options * @param {Object} [options] Options object */ - setOptions(options: any); + setOptions(options: any): void; /** * Sets sourcePath of an object * @param {String} value Value to set sourcePath to @@ -2850,7 +2850,7 @@ declare module fabric { } interface IPathGroup extends IObject { - initialize(paths: IPath[], options?: IObjectOptions); + initialize(paths: IPath[], options?: IObjectOptions): void; /** * Returns number representation of object's complexity * @return {Number} complexity @@ -2865,7 +2865,7 @@ declare module fabric { * Renders this group on a specified context * @param {CanvasRenderingContext2D} ctx Context to render this instance on */ - render(ctx: CanvasRenderingContext2D); + render(ctx: CanvasRenderingContext2D): void; /** * Returns dataless object representation of this path group * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output @@ -2993,7 +2993,7 @@ declare module fabric { minY?: number; } interface IPolyline extends IObject, IPolylineOptions { - initialize(points: IPoint[], options?: IPolylineOptions); + initialize(points: IPoint[], options?: IPolylineOptions): void; /** * Returns complexity of an instance * @return {Number} complexity of this instance @@ -3158,7 +3158,7 @@ declare module fabric { * Renders text instance on a specified context * @param {CanvasRenderingContext2D} ctx Context to render on */ - render(ctx: CanvasRenderingContext2D, noTransform: boolean); + render(ctx: CanvasRenderingContext2D, noTransform: boolean): void; /** * Returns object representation of an instance * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output @@ -3347,7 +3347,7 @@ declare module fabric { * Returns true if object has no styling */ isEmptyStyles(): boolean; - render(ctx: CanvasRenderingContext2D, noTransform: boolean); + render(ctx: CanvasRenderingContext2D, noTransform: boolean): void; /** * Returns object representation of an instance * @method toObject @@ -4360,13 +4360,13 @@ declare module fabric { * @param {Object} [properties] Properties shared by all instances of this class * (be careful modifying objects defined here as this would affect all instances) */ - createClass(parent: Function, properties?: any); + createClass(parent: Function, properties?: any): void; /** * Helper for creation of "classes". * @param {Object} [properties] Properties shared by all instances of this class * (be careful modifying objects defined here as this would affect all instances) */ - createClass(properties?: any); + createClass(properties?: any): void; } From 891e5f1f9615267fbdddaabe3abdf459f8fda002 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Fri, 21 Aug 2015 14:40:08 -0700 Subject: [PATCH 155/345] Added indexer to 'InterpolationOptions' and fixed 'smart_count' type in 'node_polyglot'. --- node-polyglot/node-polyglot.d.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/node-polyglot/node-polyglot.d.ts b/node-polyglot/node-polyglot.d.ts index 0f5bd8922..7c29b745c 100644 --- a/node-polyglot/node-polyglot.d.ts +++ b/node-polyglot/node-polyglot.d.ts @@ -6,8 +6,10 @@ declare module "node-polyglot" { module Polyglot { interface InterpolationOptions { - smart_count?: number; + smart_count?: number | { length: number }; _?: string; + + [interpolationKey: string]: any; } interface PolyglotOptions { From e7b7130b9587ba8579182d58d0170b65c5c880a4 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Fri, 21 Aug 2015 14:49:10 -0700 Subject: [PATCH 156/345] Added 'extensions' to interface in 'mathjax'. --- mathjax/mathjax.d.ts | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/mathjax/mathjax.d.ts b/mathjax/mathjax.d.ts index 65c10e3ad..d8b1cd0ef 100644 --- a/mathjax/mathjax.d.ts +++ b/mathjax/mathjax.d.ts @@ -587,7 +587,7 @@ declare module jax { * These are found in the MathJax/jax directory. */ jax?:string[]; - /*A comma-separated list of extensions to load at startup. The default directory is MathJax/extensions. The + /*A list of extensions to load at startup. The default directory is MathJax/extensions. The * tex2jax and mml2jax preprocessors can be listed here, as well as a FontWarnings extension that you can use to * inform your user that mathematics fonts are available that they can download to improve their experience of * your site. @@ -1272,7 +1272,14 @@ declare module jax { * of a’s in MathJax’s equation buffer, the MAXBUFFER constant is used to limit the size of the string being * processed by MathJax. It is set to 5KB, which should be sufficient for any reasonable equation. */ - MAXBUFFER?:number; + MAXBUFFER?: number; + + /*A list of extensions to load at startup. The default directory is MathJax/extensions. The + * tex2jax and mml2jax preprocessors can be listed here, as well as a FontWarnings extension that you can use to + * inform your user that mathematics fonts are available that they can download to improve their experience of + * your site. + */ + extensions?: string[]; } export interface IEquationNumbers { From 95ff8e6916c93b40562dc2c427907f46fc115146 Mon Sep 17 00:00:00 2001 From: David Sidlinger Date: Fri, 21 Aug 2015 16:49:48 -0500 Subject: [PATCH 157/345] Remove implicit `any` from Dropzone --- dropzone/dropzone.d.ts | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/dropzone/dropzone.d.ts b/dropzone/dropzone.d.ts index 106e10313..1702ae484 100644 --- a/dropzone/dropzone.d.ts +++ b/dropzone/dropzone.d.ts @@ -33,7 +33,7 @@ interface DropzoneOptions { resize?: ( file?: any ) => any; init?: () => void; acceptedFiles?: string; - accept?: ( file: DropzoneFile, doneCallback: ( ...args ) => void ) => void; + accept?: ( file: DropzoneFile, doneCallback: ( ...args: any[] ) => void ) => void; autoProcessQueue?: boolean; previewTemplate?: string; forceFallback?: boolean; @@ -67,9 +67,9 @@ declare class Dropzone { disable(): void; destroy(): Dropzone; - on( eventName, callback: ( ...args ) => any ); + on( eventName: string, callback: ( ...args: any[] ) => any ): void; - off( eventName ): void; + off( eventName: string ): void; addFile( file: DropzoneFile ): void; @@ -99,24 +99,24 @@ declare class Dropzone { getFilesWithStatus( status: string ): DropzoneFile[]; enqueueFile( file: DropzoneFile ): void; enqueueFiles( file: DropzoneFile[] ): void; - createThumbnail( file: DropzoneFile, callback?: (...any) => {}): any; - createThumbnailFromUrl( file: DropzoneFile, url: string, callback?: ( ...any ) => any ): any; + createThumbnail( file: DropzoneFile, callback?: (...any: any[]) => {}): any; + createThumbnailFromUrl( file: DropzoneFile, url: string, callback?: ( ...any: any[] ) => any ): any; - emit( eventName: string, file: DropzoneFile, str?: string ); - emit( eventName: "thumbnail", file: DropzoneFile, path: string ); - emit( eventName: "addedfile", file: DropzoneFile ); - emit( eventName: "removedfile", file: DropzoneFile ); - emit( eventName: "processing", file: DropzoneFile ); - emit( eventName: "canceled", file: DropzoneFile ); - emit( eventName: "complete", file: DropzoneFile ); + emit( eventName: string, file: DropzoneFile, str?: string ): void; + emit( eventName: "thumbnail", file: DropzoneFile, path: string ): void; + emit( eventName: "addedfile", file: DropzoneFile ): void; + emit( eventName: "removedfile", file: DropzoneFile ): void; + emit( eventName: "processing", file: DropzoneFile ): void; + emit( eventName: "canceled", file: DropzoneFile ): void; + emit( eventName: "complete", file: DropzoneFile ): void; - emit( eventName: string, e: Event ); - emit( eventName: "drop", e: Event ); - emit( eventName: "dragstart", e: Event ); - emit( eventName: "dragend", e: Event ); - emit( eventName: "dragenter", e: Event ); - emit( eventName: "dragover", e: Event ); - emit( eventName: "dragleave", e: Event ); + emit( eventName: string, e: Event ): void; + emit( eventName: "drop", e: Event ): void; + emit( eventName: "dragstart", e: Event ): void; + emit( eventName: "dragend", e: Event ): void; + emit( eventName: "dragenter", e: Event ): void; + emit( eventName: "dragover", e: Event ): void; + emit( eventName: "dragleave", e: Event ): void; } interface JQuery { From c94a7f9e18e6efec287b0e06f6e53430f1d24695 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Fri, 21 Aug 2015 14:51:46 -0700 Subject: [PATCH 158/345] Fixed comments/types of properties in 'mathjax'. --- mathjax/mathjax.d.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/mathjax/mathjax.d.ts b/mathjax/mathjax.d.ts index d8b1cd0ef..3331688bb 100644 --- a/mathjax/mathjax.d.ts +++ b/mathjax/mathjax.d.ts @@ -582,7 +582,7 @@ declare module jax { asciimath2jax?:IAsciimath2jaxPreprocessor; mml2jax?:IMML2jaxPreprocessor; tex2jax?:ITEX2jaxPreprocessor; - /*A comma-separated list of input and output jax to initialize at startup. Their main code is loaded only when + /*A list of input and output jax to initialize at startup. Their main code is loaded only when * they are actually used, so it is not inefficient to include jax that may not actually be used on the page. * These are found in the MathJax/jax directory. */ @@ -593,16 +593,16 @@ declare module jax { * your site. */ extensions?:string[]; - /*A comma-separated list of configuration files to load when MathJax starts up, e.g., to define local macros, + /*A list of configuration files to load when MathJax starts up, e.g., to define local macros, * etc., and there is a sample config file named config/local/local.js. The default directory is the * MathJax/config directory. The MMLorHTML.js configuration is one such configuration file, and there are a * number of other pre-defined configurations (see Using a configuration file for more details). */ config?:string[]; - /*A comma-separated list of CSS stylesheet files to be loaded when MathJax starts up. The default directory is + /*A list of CSS stylesheet files to be loaded when MathJax starts up. The default directory is * the MathJax/config directory. */ - styleSheets?:string; + styleSheets?:string[]; /*CSS styles to be defined dynamically at startup time. These are in the form selector:rules (see CSS Style * Objects for complete details). */ @@ -1274,7 +1274,7 @@ declare module jax { */ MAXBUFFER?: number; - /*A list of extensions to load at startup. The default directory is MathJax/extensions. The + /*A comma-separated list of extensions to load at startup. The default directory is MathJax/extensions. The * tex2jax and mml2jax preprocessors can be listed here, as well as a FontWarnings extension that you can use to * inform your user that mathematics fonts are available that they can download to improve their experience of * your site. From b2057ec97410f338dfae5f2dd8aee22d133420c8 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Fri, 21 Aug 2015 14:53:34 -0700 Subject: [PATCH 159/345] Added 'mpContext' and 'mpMouse' to menu settings type in 'mathjax'. --- mathjax/mathjax.d.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/mathjax/mathjax.d.ts b/mathjax/mathjax.d.ts index 3331688bb..f49a8435b 100644 --- a/mathjax/mathjax.d.ts +++ b/mathjax/mathjax.d.ts @@ -549,7 +549,10 @@ declare module jax { * from “Show Source” and put it into a page that uses MathJax’s MathML input jax and expect to get the same * results as the original TeX. (Without this, there may be some spacing differences.) */ - texHints?:boolean; + texHints?: boolean; + + mpContext?: boolean; + mpMouse?: boolean; } export interface IErrorSettings { From 85cafebc415e89825478aae0cef64ea026539f82 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Fri, 21 Aug 2015 15:02:04 -0700 Subject: [PATCH 160/345] Adds missing properties of interface in 'jquerymobile'. --- jquerymobile/jquerymobile.d.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/jquerymobile/jquerymobile.d.ts b/jquerymobile/jquerymobile.d.ts index f07c73fc3..393c3d972 100644 --- a/jquerymobile/jquerymobile.d.ts +++ b/jquerymobile/jquerymobile.d.ts @@ -161,7 +161,7 @@ interface CheckboxRadioOptions { } interface CheckboxRadioEvents { - createp?: JQueryMobileEvent; + create?: JQueryMobileEvent; } interface SelectMenuOptions { @@ -184,7 +184,11 @@ interface SelectMenuEvents { } interface ListViewOptions { + autodividers?: boolean; + autodividersSelector?: (jq?: JQuery) => string; countTheme?: string; + defaults?: boolean; + disabled?: boolean; dividerTheme?: string; filter?: boolean; filterCallback?: Function; From ef1525d01ed85f67619fcaed491b66ec49320133 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Fri, 21 Aug 2015 15:06:42 -0700 Subject: [PATCH 161/345] Fixed definitions/tests for 'jquery.gridster'. --- jquery.gridster/gridster-tests.ts | 2 +- jquery.gridster/gridster.d.ts | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/jquery.gridster/gridster-tests.ts b/jquery.gridster/gridster-tests.ts index 72c90a6f0..80c71e535 100644 --- a/jquery.gridster/gridster-tests.ts +++ b/jquery.gridster/gridster-tests.ts @@ -16,7 +16,7 @@ var options: GridsterOptions = { } }; -var gridster = $('.gridster ul').gridster(options).data('grister'); +let gridster: Gridster = $('.gridster ul').gridster(options).data('gridster'); gridster.add_widget('
    • The HTML of the widget...
    • ', 2, 1); gridster.remove_widget($('gridster li').eq(3).get(0)); var json = gridster.serialize(); diff --git a/jquery.gridster/gridster.d.ts b/jquery.gridster/gridster.d.ts index e003f0ebc..abbb4c8e0 100644 --- a/jquery.gridster/gridster.d.ts +++ b/jquery.gridster/gridster.d.ts @@ -248,3 +248,7 @@ interface Gridster { **/ disable(): Gridster; } + +interface JQuery { + data(key: "gridster"): Gridster; +} \ No newline at end of file From 5dfb8d9e90e019cdc712efce11ef4f421697372c Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Fri, 21 Aug 2015 15:09:20 -0700 Subject: [PATCH 162/345] Reorder overloads for better error experience in 'jquery.fancytree'. --- jquery.fancytree/jquery.fancytree.d.ts | 48 +++++++++++++------------- 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/jquery.fancytree/jquery.fancytree.d.ts b/jquery.fancytree/jquery.fancytree.d.ts index 34a9f1422..0167e80ed 100644 --- a/jquery.fancytree/jquery.fancytree.d.ts +++ b/jquery.fancytree/jquery.fancytree.d.ts @@ -217,30 +217,6 @@ declare module Fancytree { //#endregion //#region Methods - /** - * Append (or insert) a single child node. - * - * @param child node to add - * @param insertBefore child node to insert this node before. If omitted, the new child is appended. - * @returns The child added. - */ - addChildren(child: Fancytree.NodeData, insertBefore?: FancytreeNode): FancytreeNode; - /** - * Append (or insert) a single child node. - * - * @param child node to add - * @param insertBefore key of the child node to insert this node before. If omitted, the new child is appended. - * @returns The child added. - */ - addChildren(child: Fancytree.NodeData, insertBefore?: string): FancytreeNode; - /** - * Append (or insert) a single child node. - * - * @param child node to add - * @param insertBefore index of the child node to insert this node before. If omitted, the new child is appended. - * @returns The child added. - */ - addChildren(child: Fancytree.NodeData, insertBefore?: number): FancytreeNode; /** * Append (or insert) a list of child nodes. * @@ -265,6 +241,30 @@ declare module Fancytree { * @returns The first child added. */ addChildren(children: Fancytree.NodeData[], insertBefore?: number): FancytreeNode; + /** + * Append (or insert) a single child node. + * + * @param child node to add + * @param insertBefore child node to insert this node before. If omitted, the new child is appended. + * @returns The child added. + */ + addChildren(child: Fancytree.NodeData, insertBefore?: FancytreeNode): FancytreeNode; + /** + * Append (or insert) a single child node. + * + * @param child node to add + * @param insertBefore key of the child node to insert this node before. If omitted, the new child is appended. + * @returns The child added. + */ + addChildren(child: Fancytree.NodeData, insertBefore?: string): FancytreeNode; + /** + * Append (or insert) a single child node. + * + * @param child node to add + * @param insertBefore index of the child node to insert this node before. If omitted, the new child is appended. + * @returns The child added. + */ + addChildren(child: Fancytree.NodeData, insertBefore?: number): FancytreeNode; /** Append or prepend a node, or append a child node. This a convenience function that calls addChildren() From b2b1359d8bd396e1b937771de131ec3d17a43515 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Fri, 21 Aug 2015 15:11:50 -0700 Subject: [PATCH 163/345] Add 'icon' property to an interface in 'jquery.fancytree'. --- jquery.fancytree/jquery.fancytree.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/jquery.fancytree/jquery.fancytree.d.ts b/jquery.fancytree/jquery.fancytree.d.ts index 0167e80ed..32b8d2479 100644 --- a/jquery.fancytree/jquery.fancytree.d.ts +++ b/jquery.fancytree/jquery.fancytree.d.ts @@ -780,6 +780,7 @@ declare module Fancytree { interface NodeData { /** node text (may contain HTML tags) */ title: string; + icon?: string; /** unique key for this node (auto-generated if omitted) */ key?: string; /** (reserved) */ From de6783d45dc4dcf75779bc27f1deee7e23b459cd Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Fri, 21 Aug 2015 15:14:04 -0700 Subject: [PATCH 164/345] Added 'ignoreUndefined' property for rename options interface in 'joi'. --- joi/joi.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/joi/joi.d.ts b/joi/joi.d.ts index b784ad23d..d3cc138f0 100644 --- a/joi/joi.d.ts +++ b/joi/joi.d.ts @@ -33,6 +33,8 @@ declare module 'joi' { 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 { From c134c51a8fe8bd324bd82ef7eca377b567c097b1 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Fri, 21 Aug 2015 15:17:40 -0700 Subject: [PATCH 165/345] JSDoc - time to jump for 'joi'. --- joi/joi.d.ts | 86 ++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 64 insertions(+), 22 deletions(-) diff --git a/joi/joi.d.ts b/joi/joi.d.ts index d3cc138f0..8c97e1216 100644 --- a/joi/joi.d.ts +++ b/joi/joi.d.ts @@ -8,63 +8,105 @@ declare module 'joi' { export interface ValidationOptions { - // when true, stops validation on the first error, otherwise returns all the errors found. Defaults to true. + /** + * 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. + /** + * 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. + /** + * 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. + /** + * 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. + /** + * 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 ({}). + /** + * overrides individual error messages. Defaults to no override ({}). + */ language?: Object; - // sets the default presence requirements. Supported modes: 'optional', 'required', and 'forbidden'. Defaults to 'optional'. + /** + * 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 + /** + * 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. + /** + * 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. + /** + * 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. + /** + * 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. + /** + * 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 + /** + * Numerical threshold at which an email address is considered invalid + */ errorLevel?: number | boolean; - // Specifies a list of acceptable TLDs. + /** + * 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. + /** + * 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 + /** + * 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 + /** + * 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). + /** + * 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. + /** + * the required condition joi type. + */ is: Schema; - // the alternative schema type if the condition is true. Required if otherwise is missing. + /** + * 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 + /** + * the alternative schema type if the condition is false. Required if then is missing + */ otherwise?: Schema; } From 93767f845ccc4c814ed66a3c94dd84078ab93e9e Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Fri, 21 Aug 2015 15:27:25 -0700 Subject: [PATCH 166/345] Added 'backlight' property to LCD options for 'johnny-five'. --- johnny-five/johnny-five.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/johnny-five/johnny-five.d.ts b/johnny-five/johnny-five.d.ts index 9dd1477eb..e2c2c1c30 100644 --- a/johnny-five/johnny-five.d.ts +++ b/johnny-five/johnny-five.d.ts @@ -251,10 +251,12 @@ declare module "johnny-five" { export interface LCDI2COption extends LCDGeneralOption{ controller: string; + backlight?: number; } export interface LCDParallelOption extends LCDGeneralOption{ pins: Array; + backlight?: number; } export class LCD{ From 7d8e08c9b53ecba5e8988ea5cd386d0eadd322df Mon Sep 17 00:00:00 2001 From: "chocolatechipui@sourcebits.com" Date: Fri, 21 Aug 2015 15:42:09 -0700 Subject: [PATCH 167/345] Updated types for ChocolateChipJS to 4.0.3. Updated types to match refactored versions of "prop" and "removeProp". --- chocolatechipjs/chocolatechipjs-tests.ts | 6 ++++-- chocolatechipjs/chocolatechipjs.d.ts | 25 +++++++++++++++--------- 2 files changed, 20 insertions(+), 11 deletions(-) diff --git a/chocolatechipjs/chocolatechipjs-tests.ts b/chocolatechipjs/chocolatechipjs-tests.ts index 06b581769..111e69f63 100644 --- a/chocolatechipjs/chocolatechipjs-tests.ts +++ b/chocolatechipjs/chocolatechipjs-tests.ts @@ -102,12 +102,14 @@ $('ul').insert("
    • 1
    • 2
    • 3
    • ", 3); $('ul').insert("
    • 1
    • 2
    • 3
    • "); $('ul').html('
    • 1
    • <2/li>
    • 3
    • '); $('ul').html(''); +var listContent = $('ul').html(); $('ul').prepend('
    • The title
    • '); $('ul').append('
    • The Last Item
    • '); var inputName = $('input').attr('name'); $('input').attr('name', 'wobba'); -var inputName = $('input').prop('name'); -$('input').prop('name', 'wobba'); +var inputProperty = $('input').prop('disabled'); +$('input[type=checked]').prop('checked', true); +$('input').removeProp('disabled'); $('input').hasAttr('disabled').css('border', 'solid 1px red'); $('input').removeAttr('disabled'); $('article').hasClass('current').css('display', 'block'); diff --git a/chocolatechipjs/chocolatechipjs.d.ts b/chocolatechipjs/chocolatechipjs.d.ts index 3c84558af..6a45863b0 100644 --- a/chocolatechipjs/chocolatechipjs.d.ts +++ b/chocolatechipjs/chocolatechipjs.d.ts @@ -1,4 +1,4 @@ -// Type definitions for chocolatechip v4.0.2 +// Type definitions for chocolatechip v4.0.3 // Project: https://github.com/chocolatechipui/ChocolateChipJS // Definitions by: Robert Biggs // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -176,7 +176,8 @@ interface ChocolateChipStatic { * @param response The response from a Promise. * @result */ - json(reponse: Response): JSON; + json(reponse: Response): JSON; + /** * This method will defer the execution of a function until the call stack is clear. * @@ -198,7 +199,7 @@ interface ChocolateChipStatic { * This method makes sure a method always returns an array. If no values are available to return, it returns and empty array. This is to make sure that methods that expect a chainable array will not throw and exception. * * @param result The result of a method to test if it can be returned in an array. - * @return An array hold the results of a method, otherwise an empty array. + * @return An array holding the results of a method, otherwise an empty array. */ returnResult(result: HTMLElement[]): any[]; @@ -836,12 +837,12 @@ interface ChocolateChipElementArray extends Array { hasAttr(attributeName: string): ChocolateChipElementArray; /** - * Get the value of an attribute for the first element in the set of matched elements. + * Test whether an attribute exists on the first element in the set of matched elements. The value returned is a boolean. * * @param attributeName The name of the attribute to get. - * @return string + * @return boolean */ - prop(attributeName: string): string; + prop(propertyName: string): boolean; /** * Set an property for the set of matched elements. @@ -850,7 +851,15 @@ interface ChocolateChipElementArray extends Array { * @param value A string indicating the value to set the property to. * @return HTMLElement[] */ - prop(propertyName: string, value: string): ChocolateChipElementArray; + prop(propertyName: string, value: any | boolean): ChocolateChipElementArray; + + /** + * Remove an element property. + * + * @param property The property to remove. + * @return HTMLElement[] + */ + removeProp(property: string): ChocolateChipElementArray; /** * Adds the specified class(es) to each of the set of matched elements. @@ -1471,5 +1480,3 @@ interface Window { } declare var $: ChocolateChipStatic; declare var fetch: fetch; - -declare var chocolatechipjs: ChocolateChipStatic; \ No newline at end of file From 985b3ce3a4c97dd249beaab20b2e6d1ec6fa8b39 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Fri, 21 Aug 2015 15:45:46 -0700 Subject: [PATCH 168/345] Add 'metadataStore' property to 'breeze'. --- breeze/breeze.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/breeze/breeze.d.ts b/breeze/breeze.d.ts index 4821ed427..139a30629 100644 --- a/breeze/breeze.d.ts +++ b/breeze/breeze.d.ts @@ -459,6 +459,7 @@ declare module breeze { interface EntityManagerProperties { serviceName?: string; dataService?: DataService; + metadataStore?: MetadataStore; queryOptions?: QueryOptions; saveOptions?: SaveOptions; validationOptions?: ValidationOptions; From 85a7ed0fec48ed5e3c0ba85faf91b4b7f6d311eb Mon Sep 17 00:00:00 2001 From: Scott Southwood Date: Fri, 21 Aug 2015 16:21:59 -0700 Subject: [PATCH 169/345] update to version 0.15.5 --- applicationinsights/applicationinsights.d.ts | 40 ++++++++++++++++++-- 1 file changed, 36 insertions(+), 4 deletions(-) diff --git a/applicationinsights/applicationinsights.d.ts b/applicationinsights/applicationinsights.d.ts index 6b80adc2a..12dffdd81 100644 --- a/applicationinsights/applicationinsights.d.ts +++ b/applicationinsights/applicationinsights.d.ts @@ -4,21 +4,25 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped interface AutoCollectConsole { + constructor(client: Client): AutoCollectConsole; enable(isEnabled: boolean): void; isInitialized(): boolean; } interface AutoCollectExceptions { + constructor(client:Client): AutoCollectExceptions; isInitialized(): boolean; enable(isEnabled:boolean): void; } interface AutoCollectPerformance { + constructor(client: Client): AutoCollectPerformance; enable(isEnabled: boolean): void; isInitialized(): boolean; } interface AutoCollectRequests { + constructor(client: Client): AutoCollectRequests; enable(isEnabled: boolean): void; isInitialized(): boolean; } @@ -85,14 +89,17 @@ declare module ContractsModule { sampleRate: string; internalSdkVersion: string; internalAgentVersion: string; + constructor(): ContextTagKeys; } interface Domain { ver: number; properties: any; + constructor(): Domain; } interface Data { baseType: string; baseData: TDomain; + constructor(): Data; } interface Envelope { ver: number; @@ -112,18 +119,21 @@ declare module ContractsModule { [key: string]: string; }; data: Data; + constructor(): Envelope; } interface EventData extends ContractsModule.Domain { ver: number; name: string; properties: any; measurements: any; + constructor(): EventData; } interface MessageData extends ContractsModule.Domain { ver: number; message: string; severityLevel: ContractsModule.SeverityLevel; properties: any; + constructor(): MessageData; } interface ExceptionData extends ContractsModule.Domain { ver: number; @@ -134,6 +144,7 @@ declare module ContractsModule { crashThreadId: number; properties: any; measurements: any; + constructor(): ExceptionData; } interface StackFrame { level: number; @@ -141,6 +152,7 @@ declare module ContractsModule { assembly: string; fileName: string; line: number; + constructor(): StackFrame; } interface ExceptionDetails { id: number; @@ -150,6 +162,7 @@ declare module ContractsModule { hasFullStack: boolean; stack: string; parsedStack: StackFrame[]; + constructor(): ExceptionDetails; } interface DataPoint { name: string; @@ -159,11 +172,13 @@ declare module ContractsModule { min: number; max: number; stdDev: number; + constructor(): DataPoint; } interface MetricData extends ContractsModule.Domain { ver: number; metrics: DataPoint[]; properties: any; + constructor(): MetricData; } interface PageViewData extends ContractsModule.EventData { ver: number; @@ -172,6 +187,7 @@ declare module ContractsModule { duration: string; properties: any; measurements: any; + constructor(): PageViewData; } interface PageViewPerfData extends ContractsModule.PageViewData { ver: number; @@ -185,6 +201,7 @@ declare module ContractsModule { domProcessing: string; properties: any; measurements: any; + constructor(): PageViewPerfData; } interface RemoteDependencyData extends ContractsModule.Domain { ver: number; @@ -202,6 +219,7 @@ declare module ContractsModule { commandName: string; dependencyTypeName: string; properties: any; + constructor(): RemoteDependencyData; } interface AjaxCallData extends ContractsModule.PageViewData { ver: number; @@ -218,6 +236,7 @@ declare module ContractsModule { success: boolean; properties: any; measurements: any; + constructor(): AjaxCallData; } interface RequestData extends ContractsModule.Domain { ver: number; @@ -231,10 +250,12 @@ declare module ContractsModule { url: string; properties: any; measurements: any; + constructor(): RequestData; } interface SessionStateData extends ContractsModule.Domain { ver: number; state: ContractsModule.SessionState; + constructor(): SessionStateData; } interface PerformanceCounterData extends ContractsModule.Domain { ver: number; @@ -248,6 +269,7 @@ declare module ContractsModule { stdDev: number; value: number; properties: any; + constructor(): PerformanceCounterData; } } @@ -309,10 +331,14 @@ interface Client { * Log a numeric value that is not associated with a specific event. Typically used to send regular reports of performance indicators. * To send a single measurement, use just the first two parameters. If you take measurements very frequently, you can reduce the * telemetry bandwidth by aggregating multiple measurements and sending the resulting average at intervals. - * @param name A string that identifies the metric. - * @param value The value of the metric + * @param name A string that identifies the metric. + * @param value The value of the metric + * @param count the number of samples used to get this value + * @param min the min sample for this set + * @param max the max sample for this set + * @param stdDev the standard deviation of the set */ - trackMetric(name: string, value: number): void; + trackMetric(name: string, value: number, count?:number, min?: number, max?: number, stdDev?: number): void; trackRequest(request: any /* http.ServerRequest */, response: any /* http.ServerResponse */, properties?: { [key: string]: string; }): void; @@ -381,10 +407,16 @@ declare class ApplicationInsights { private static _performance; private static _requests; private static _isStarted; + /** + * Initializes a client with the given instrumentation key, if this is not specified, the value will be + * read from the environment variable APPINSIGHTS_INSTRUMENTATIONKEY + * @returns {ApplicationInsights/Client} a new client + */ + static getClient(instrumentationKey?: string): Client; /** * Initializes the default client of the client and sets the default configuration * @param instrumentationKey the instrumentation key to use. Optional, if this is not specified, the value will be - * read from the environment variable APPINSIGHTS_INSTRUMENTATION_KEY + * read from the environment variable APPINSIGHTS_INSTRUMENTATIONKEY * @returns {ApplicationInsights} this interface */ static setup(instrumentationKey?: string): typeof ApplicationInsights; From 2ffc0452e5ffaf40b0ebee29094f39a87c5e3aac Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Fri, 21 Aug 2015 16:27:21 -0700 Subject: [PATCH 170/345] Fixed definitions for 'js-data'. --- js-data/js-data.d.ts | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/js-data/js-data.d.ts b/js-data/js-data.d.ts index bec41d331..e17c4ae0d 100644 --- a/js-data/js-data.d.ts +++ b/js-data/js-data.d.ts @@ -115,7 +115,17 @@ declare module JSData { } interface DSAdapterOperationConfiguration extends DSConfiguration { - adapter?: string + adapter?: string; + bypassCache?: boolean; + cacheResponse?: boolean; + findStrategy?: string; + findFallbackAdapters?: string[]; + strategy?: string; + fallbackAdapters?: string[]; + + params: { + [paramName: string]: string | number | boolean; + }; } interface DSSaveConfiguration extends DSAdapterOperationConfiguration { @@ -156,7 +166,8 @@ declare module JSData { digest():void; eject(id:string | number, options?:DSConfiguration):T; ejectAll(params:DSFilterParams, options?:DSConfiguration):Array; - filter(params:DSFilterParams, options?:DSConfiguration):Array; + filter(params: DSFilterParams, options?: DSConfiguration): Array; + filter(params: DSFilterParamsForAllowSimpleWhere, options?: DSConfiguration): Array; get(id:string | number, options?:DSConfiguration):T; getAll(ids?:Array):Array; hasChanges(id:string | number):boolean; @@ -184,6 +195,10 @@ declare module JSData { sort?: string | Array | Array>; } + interface DSFilterParamsForAllowSimpleWhere { + [key: string]: string | number; + } + interface IDSResourceLifecycleValidateEventHandlers { beforeValidate?: (resourceName:string, data:any, cb:(err:any, data?:any)=>void)=>void; validate?: (resourceName:string, data:any, cb:(err:any, data?:any)=>void)=>void; From 35380afde2b007834344b6d1c9213ca8ab9369d3 Mon Sep 17 00:00:00 2001 From: Scott Southwood Date: Fri, 21 Aug 2015 17:13:02 -0700 Subject: [PATCH 171/345] adding definitions for project oxford --- project-oxford/project-oxford-tests.ts | 480 +++++++++++++++++++++++ project-oxford/project-oxford.d.ts | 522 +++++++++++++++++++++++++ 2 files changed, 1002 insertions(+) create mode 100644 project-oxford/project-oxford-tests.ts create mode 100644 project-oxford/project-oxford.d.ts diff --git a/project-oxford/project-oxford-tests.ts b/project-oxford/project-oxford-tests.ts new file mode 100644 index 000000000..3d662d504 --- /dev/null +++ b/project-oxford/project-oxford-tests.ts @@ -0,0 +1,480 @@ +/// +/// +/// +/// + +import oxford = require("project-oxford"); + +import assert = require('assert'); +import _Promise = require('bluebird'); +import fs = require('fs'); + +var client = new oxford.Client(process.env.OXFORD_KEY); + +// Store variables, no point in calling the api too often +var billFaces = []; +var personGroupId = "uuid.v4()"; +var personGroupId2 = "uuid.v4()"; +var billPersonId: string; + +describe('Project Oxford Face API Test', function () { + afterEach(function() { + // delay after each test to prevent throttling + var now = +new Date() + 250; + while(now > +new Date()); + }); + + describe('#detect()', function () { + it('detects a face in a stream', function (done) { + client.face.detect({ + stream: fs.createReadStream('./test/images/face1.jpg'), + analyzesFaceLandmarks: true, + analyzesAge: true, + analyzesGender: true, + analyzesHeadPose: true + }).then(function (response) { + assert.ok(response[0].faceId); + assert.ok(response[0].faceRectangle); + assert.ok(response[0].faceLandmarks); + assert.ok(response[0].attributes.gender); + assert.ok(response[0].attributes.headPose); + + assert.equal(response[0].attributes.gender, 'male'); + done(); + }); + }); + + it('detects a face in a local file', function (done) { + client.face.detect({ + path: './test/images/face1.jpg', + analyzesFaceLandmarks: true, + analyzesAge: true, + analyzesGender: true, + analyzesHeadPose: true + }).then(function (response) { + assert.ok(response[0].faceId); + assert.ok(response[0].faceRectangle); + assert.ok(response[0].faceLandmarks); + assert.ok(response[0].attributes.gender); + assert.ok(response[0].attributes.headPose); + + assert.equal(response[0].attributes.gender, 'male'); + done(); + }); + }); + + it('detects a face in a remote file', function (done) { + client.face.detect({ + url: 'https://upload.wikimedia.org/wikipedia/commons/1/19/Bill_Gates_June_2015.jpg', + analyzesFaceLandmarks: true, + analyzesAge: true, + analyzesGender: true, + analyzesHeadPose: true + }).then(function (response) { + assert.ok(response[0].faceId); + assert.ok(response[0].faceRectangle); + assert.ok(response[0].faceLandmarks); + assert.ok(response[0].attributes.gender); + assert.ok(response[0].attributes.headPose); + + assert.equal(response[0].attributes.gender, 'male'); + done(); + }); + }); + }); + + describe('#similar()', function () { + it('detects similar faces', function (done) { + var detects = []; + + this.timeout(10000); + + detects.push(client.face.detect({ + path: './test/images/face1.jpg', + }).then(function(response) { + assert.ok(response[0].faceId) + billFaces.push(response[0].faceId); + })); + + detects.push(client.face.detect({ + path: './test/images/face2.jpg', + }).then(function(response) { + assert.ok(response[0].faceId) + billFaces.push(response[0].faceId); + })); + + _Promise.all(detects).then(function() { + client.face.similar(billFaces[0], [billFaces[1]]).then(function(response) { + done(); + }); + }); + }); + }); + + describe('#grouping()', function () { + it('detects groups faces', function (done) { + var faceIds = []; + + this.timeout(10000); + + client.face.detect({ + path: './test/images/face-group.jpg', + }).then(function(response) { + response.forEach(function (face) { + faceIds.push(face.faceId); + }); + + assert.equal(faceIds.length, 6); + }).then(function() { + client.face.grouping(faceIds).then(function (response) { + assert.ok(response.messyGroup); + done(); + }); + }); + }); + }); + + describe('#verify()', function () { + it('verifies a face against another face', function (done) { + this.timeout(10000); + + assert.equal(billFaces.length, 2); + + client.face.verify(billFaces).then(function (response) { + assert.ok(response); + assert.ok((response.isIdentical === true || response.isIdentical === false)); + assert.ok(response.confidence); + done(); + }); + }); + }); + + describe('#PersonGroup', function () { + before(function(done) { + this.timeout(5000); + // In order to test the + // training feature, we have to start trainign - sadly, we can't + // delete the group then. So we clean up before we run tests - and to wait + // for cleanup to finish, we're just using done(). + client.face.personGroup.list().then(function (response) { + var promises = []; + + response.forEach(function (personGroup) { + if (personGroup.name.indexOf('po-node-test-group') > -1) { + promises.push(client.face.personGroup.delete(personGroup.personGroupId)); + } + }); + + _Promise.all(promises).then(function () { + done(); + }); + }); + }); + + it('creates a PersonGroup', function (done) { + client.face.personGroup.create(personGroupId, 'po-node-test-group', 'test-data').then(function (response) { + assert.ok(true, "void response expected"); + done(); + }) + .catch(function (error) { + assert.ok(false, JSON.stringify(error)); + done(); + }); + }); + + it('lists PersonGroups', function (done) { + client.face.personGroup.list().then(function (response) { + assert.ok(response); + assert.ok((response.length > 0)); + assert.ok(response[0].personGroupId); + done(); + }); + }); + + it('gets a PersonGroup', function (done) { + client.face.personGroup.get(personGroupId).then(function (response) { + assert.equal(response.personGroupId, personGroupId); + assert.equal(response.name, 'po-node-test-group'); + assert.equal(response.userData, 'test-data'); + done(); + }); + }); + + it('updates a PersonGroup', function (done) { + client.face.personGroup.update(personGroupId, 'po-node-test-group2', 'test-data2').then(function (response) { + assert.ok(true, "void response expected");; + done(); + }).catch(function (response) { + assert.equal(response, 'PersonGroupTrainingNotFinished') + }); + }); + + it('gets a PersonGroup\'s training status', function (done) { + client.face.personGroup.trainingStatus(personGroupId).then(function (response) { + done(); + }).catch(function (response) { + assert.equal(response.code, 'PersonGroupNotTrained'); + done(); + }); + }); + + it('starts a PersonGroup\'s training', function (done) { + client.face.personGroup.trainingStart(personGroupId).then(function (response) { + assert.equal(response.status, 'running'); + done(); + }).catch(function (response) { + assert.equal(response.status, 'running'); + done(); + }); + }); + + it('deletes a PersonGroup', function (done) { + client.face.personGroup.delete(personGroupId).then(function (response) { + assert.ok(true, "void response"); + done(); + }).catch(function (response) { + assert.equal(response.code, 'PersonGroupTrainingNotFinished'); + done(); + }); + }); + }); + + describe('#Person', function () { + + it('creates a PersonGroup for the Person', function (done) { + client.face.personGroup.create(personGroupId2, 'po-node-test-group', 'test-data') + .then(function (response) { + assert.ok(true, "void response expected"); + done(); + }) + .catch(function (error) { + assert.ok(false, JSON.stringify(error)); + done(); + }); + }); + + it('creates a Person', function (done) { + client.face.person.create(personGroupId2, [billFaces[0]], 'test-bill', 'test-data') + .then(function (response) { + assert.ok(response.personId); + billPersonId = response.personId; + done(); + }) + .catch(function (error) { + assert.ok(false, JSON.stringify(error)); + done(); + }); + }); + + it('gets a Person', function (done) { + client.face.person.get(personGroupId2, billPersonId).then(function (response) { + assert.ok(response.personId); + done(); + }) + .catch(function (error) { + assert.ok(false, JSON.stringify(error)); + done(); + }); + }); + + it('updates a Person', function (done) { + client.face.person.update(personGroupId2, billPersonId, [billFaces[0]], 'test-bill', 'test-data') + .then(function (response) { + assert.ok(true, "void response expected"); + done(); + }) + }); + + it('adds a face to a Person', function (done) { + client.face.person.addFace(personGroupId2, billPersonId, billFaces[1], 'test-data') + .then(function (response) { + assert.ok(true, "void response expected"); + done(); + }) + .catch(function (error) { + assert.ok(false, JSON.stringify(error)); + done(); + }); + }); + + it('gets a face from a Person', function (done) { + client.face.person.getFace(personGroupId2, billPersonId, billFaces[1]) + .then(function (response) { + assert.ok(response.userData); + assert.equal(response.userData, 'test-data'); + done(); + }) + .catch(function (error) { + assert.ok(false, JSON.stringify(error)); + done(); + }); + }); + + it('updates a face on a Person', function (done) { + client.face.person.updateFace(personGroupId2, billPersonId, billFaces[1], 'test-data') + .then(function (response) { + assert.ok(true, "void response expected"); + done(); + }) + .catch(function (error) { + assert.ok(false, JSON.stringify(error)); + done(); + }); + }); + + it('deletes a face on a Person', function (done) { + client.face.person.deleteFace(personGroupId2, billPersonId, billFaces[1]) + .then(function (response) { + assert.ok(true, "void response expected"); + done(); + }) + .catch(function (error) { + assert.ok(false, JSON.stringify(error)); + done(); + }); + }); + + it('lists Persons', function (done) { + client.face.person.list(personGroupId2) + .then(function (response) { + assert.ok(response[0].personId); + done(); + }) + .catch(function (error) { + assert.ok(false, JSON.stringify(error)); + done(); + }); + }); + + it('deletes a Person', function (done) { + client.face.person.delete(personGroupId2, billPersonId) + .then(function (response) { + assert.ok(true, "void response expected"); + done(); + }) + .catch(function (error) { + assert.ok(false, JSON.stringify(error)); + done(); + }); + }); + }); +}); + +describe('Project Oxford Vision API Test', function () { + before(function() { + // ensure the output directory exists + if(!fs.existsSync('./test/output')){ + fs.mkdirSync('./test/output', 0766); + } + }); + + afterEach(function() { + // delay after each test to prevent throttling + var now = +new Date() + 250; + while(now > +new Date()); + }); + + it('analyzes a local image', function (done) { + this.timeout(10000); + client.vision.analyzeImage({ + path: './test/images/vision.jpg', + ImageType: true, + Color: true, + Faces: true, + Adult: true, + Categories: true + }) + .then(function (response) { + assert.ok(response); + assert.ok(response.categories); + assert.ok(response.adult); + assert.ok(response.metadata); + assert.ok(response.faces); + assert.ok(response.color); + assert.ok(response.imageType); + done(); + }) + }); + + it('analyzes an online image', function (done) { + this.timeout(10000); + client.vision.analyzeImage({ + url: 'https://upload.wikimedia.org/wikipedia/commons/1/19/Bill_Gates_June_2015.jpg', + ImageType: true, + Color: true, + Faces: true, + Adult: true, + Categories: true + }) + .then(function (response) { + assert.ok(response); + assert.ok(response.categories); + assert.ok(response.adult); + assert.ok(response.metadata); + assert.ok(response.faces); + assert.ok(response.color); + assert.ok(response.imageType); + done(); + }); + }); + + it('creates a thumbnail for a local image', function (done) { + this.timeout(10000); + client.vision.thumbnail({ + path: './test/images/vision.jpg', + pipe: fs.createWriteStream('./test/output/thumb2.jpg'), + width: 100, + height: 100, + smartCropping: true + }) + .then(function (response) { + var stats = fs.statSync('./test/output/thumb2.jpg'); + assert.ok((stats.size > 0)); + done(); + }); + }); + + it('creates a thumbnail for an online image', function (done) { + this.timeout(10000); + client.vision.thumbnail({ + url: 'https://upload.wikimedia.org/wikipedia/commons/1/19/Bill_Gates_June_2015.jpg', + pipe: fs.createWriteStream('./test/output/thumb1.jpg'), + width: 100, + height: 100, + smartCropping: true + }) + .then(function (response) { + var stats = fs.statSync('./test/output/thumb1.jpg'); + assert.ok((stats.size > 0)); + done(); + }); + }); + + it('runs OCR on a local image', function (done) { + this.timeout(10000); + client.vision.ocr({ + path: './test/images/vision.jpg', + language: 'en', + detectOrientation: true + }) + .then(function (response) { + assert.ok(response.language); + assert.ok(response.regions); + done(); + }); + }); + + it('runs OCR on an online image', function (done) { + this.timeout(10000); + client.vision.ocr({ + url: 'https://upload.wikimedia.org/wikipedia/commons/1/19/Bill_Gates_June_2015.jpg', + language: 'en', + detectOrientation: true + }) + .then(function (response) { + assert.ok(response.language); + assert.ok(response.orientation); + done(); + }); + }); +}); \ No newline at end of file diff --git a/project-oxford/project-oxford.d.ts b/project-oxford/project-oxford.d.ts new file mode 100644 index 000000000..dffecc361 --- /dev/null +++ b/project-oxford/project-oxford.d.ts @@ -0,0 +1,522 @@ +// Type definitions for project-oxford v0.1.3 +// Project: https://github.com/felixrieseberg/project-oxford +// Definitions by: Scott Southwood +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare module "project-oxford" { + import Promise = require("bluebird"); + import stream = require("stream"); + + export class Client { + constructor(apiKey: string); + private _key: string; + public face: FaceAPI; + public vision: VisionAPI; + } + + export class FaceAPI { + + /** + * Call the Face Detected API + * Detects human faces in an image and returns face locations, face landmarks, and + * optional attributes including head-pose, gender, and age. Detection is an essential + * API that provides faceId to other APIs like Identification, Verification, + * and Find Similar. + * + * @param {object} options - Options object + * @param {string} options.url - URL to image to be used + * @param {string} options.path - Path to image to be used + * @param {stream} options.stream - Stream for image to be used + * @param {boolean} options.analyzesFaceLandmarks - Analyze face landmarks? + * @param {boolean} options.analyzesAge - Analyze age? + * @param {boolean} options.analyzesGender - Analyze gender? + * @param {boolean} options.analyzesHeadPose - Analyze headpose? + * @return {Promise} - Promise resolving with the resulting JSON + */ + public detect(options: Options.Detect): Promise<[FaceResponses.Detect]>; + + /** + * Detect similar faces using faceIds (as returned from the detect API) + * @param {string} sourceFace - String of faceId for the source face + * @param {string[]} candidateFaces - Array of faceIds to use as candidates + * @return {Promise} - Promise resolving with the resulting JSON + */ + public similar(sourceFaceId: string, candidateFacesIds: string[]): Promise; + + /** + * Divides candidate faces into groups based on face similarity using faceIds. + * The output is one or more disjointed face groups and a MessyGroup. + * A face group contains the faces that have similar looking, often of the same person. + * There will be one or more face groups ranked by group size, i.e. number of face. + * Faces belonging to the same person might be split into several groups in the result. + * The MessyGroup is a special face group that each face is not similar to any other + * faces in original candidate faces. The messyGroup will not appear in the result if + * all faces found their similar counterparts. The candidate face list has a + * limit of 100 faces. + * + * @param {string[]} faces - Array of faceIds to use + * @return {Promise} - Promise resolving with the resulting JSON + */ + public grouping(faces: string[]): Promise; + + /** + * Identifies persons from a person group by one or more input faces. + * To recognize which person a face belongs to, Face Identification needs a person group + * that contains number of persons. Each person contains one or more faces. After a person + * group prepared, it should be trained to make it ready for identification. Then the + * identification API compares the input face to those persons' faces in person group and + * returns the best-matched candidate persons, ranked by confidence. + * + * @param {string[]} faces - Array of faceIds to use + * @return {Promise} - Promise resolving with the resulting JSON + */ + public identify(faceIDs: string[], options: Options.Identify): Promise; + + /** + * Analyzes two faces and determine whether they are from the same person. + * Verification works well for frontal and near-frontal faces. + * For the scenarios that are sensitive to accuracy please use with own judgment. + * @param {string[]} faces - Array containing two faceIds to use + * @return {Promise} - Promise resolving with the resulting JSON + */ + public verify(faces: string[]): Promise; + + /** + * @namespace + * @memberof face + */ + public personGroup: PersonGroup; + public person: Person; + } + + export class VisionAPI { + /** + * This operation does a deep analysis on the given image and then extracts a + * set of rich visual features based on the image content. + * + * @param {Object} options - Options object describing features to extract + * @param {string} options.url - Url to image to be analyzed + * @param {string} options.path - Path to image to be analyzed + * @param {boolean} options.ImageType - Detects if image is clipart or a line drawing. + * @param {boolean} options.Color - Determines the accent color, dominant color, if image is black&white. + * @param {boolean} options.Faces - Detects if faces are present. If present, generate coordinates, gender and age. + * @param {boolean} options.Adult - Detects if image is pornographic in nature (nudity or sex act). Sexually suggestive content is also detected. + * @param {boolean} options.Categories - Image categorization; taxonomy defined in documentation. + * @return {Promise} - Promise resolving with the resulting JSON + */ + public analyzeImage(options: Options.Analyze): Promise; + + /** + * Generate a thumbnail image to the user-specified width and height. By default, the + * service analyzes the image, identifies the region of interest (ROI), and generates + * smart crop coordinates based on the ROI. Smart cropping is designed to help when you + * specify an aspect ratio that differs from the input image. + * + * @param {Object} options - Options object describing features to extract + * @param {string} options.url - Url to image to be thumbnailed + * @param {string} options.path - Path to image to be thumbnailed + * @param {number} options.width - Width of the thumb in pixels + * @param {number} options.height - Height of the thumb in pixels + * @param {boolean} options.smartCropping - Should SmartCropping be enabled? + * @param {Object} options.pipe - We'll pipe the returned image to this object + * @return {Promise} - Promise resolving with the resulting JSON + */ + public thumbnail(options: Options.Thumbnail): Promise; + + /** + * Optical Character Recognition (OCR) detects text in an image and extracts the recognized + * characters into a machine-usable character stream. + * + * @param {Object} options - Options object describing features to extract + * @param {string} options.url - Url to image to be analyzed + * @param {string} options.path - Path to image to be analyzed + * @param {string} options.language - BCP-47 language code of the text to be detected in the image. Default value is "unk", then the service will auto detect the language of the text in the image. + * @param {string} options.detectOrientation - Detect orientation of text in the image + * @return {Promise} - Promise resolving with the resulting JSON + */ + public ocr(options: Options.Ocr): Promise; + } + + export class PersonGroup { + /** + * Creates a new person group with a user-specified ID. + * A person group is one of the most important parameters for the Identification API. + * The Identification searches person faces in a specified person group. + * + * @param {string} personGroupId - Numbers, en-us letters in lower case, '-', '_'. Max length: 64 + * @param {string} name - Person group display name. The maximum length is 128. + * @param {string} userData - User-provided data attached to the group. The size limit is 16KB. + * @return {Promise} - Promise resolving with the resulting JSON + */ + public create(personGroupId: string, name: string, userData: string): Promise; + + /** + * Deletes an existing person group. + * + * @param {string} personGroupId - Name of person group to delete + * @return {Promise} - Promise resolving with the resulting JSON + */ + public delete(personGroupId: string): Promise; + + /** + * Gets an existing person group. + * + * @param {string} personGroupId - Name of person group to get + * @return {Promise} - Promise resolving with the resulting JSON + */ + public get(personGroupId: string): Promise; + + /** + * Retrieves the training status of a person group. Training is triggered by the Train PersonGroup API. + * The training will process for a while on the server side. This API can query whether the training + * is completed or ongoing. + * + * @param {string} personGroupId - Name of person group to get + * @return {Promise} - Promise resolving with the resulting JSON + */ + public trainingStatus(personGroupId: string): Promise; + + /** + * Starts a person group training. + * Training is a necessary preparation process of a person group before identification. + * Each person group needs to be trained in order to call Identification. The training + * will process for a while on the server side even after this API has responded. + * + * @param {string} personGroupId - Name of person group to get + * @return {Promise} - Promise resolving with the resulting JSON + */ + public trainingStart(personGroupId: string): Promise; + + /** + * Updates an existing person group's display name and userData. + * + * @param {string} personGroupId - Numbers, en-us letters in lower case, '-', '_'. Max length: 64 + * @param {string} name - Person group display name. The maximum length is 128. + * @param {string} userData - User-provided data attached to the group. The size limit is 16KB. + * @return {Promise} - Promise resolving with the resulting JSON + */ + public update(personGroupId: string, name: string, userData: string): Promise; + + /** + * Lists all person groups in the current subscription. + * @return {Promise} - Promise resolving with the resulting JSON + */ + public list(): Promise; + } + + export class Person { + /** + * Adds a face to a person for identification. The maximum face count for each person is 32. + * The face ID must be added to a person before its expiration. Typically a face ID expires + * 24 hours after detection. + * + * @param {string} personGroupId - The target person's person group. + * @param {string} personId - The target person that the face is added to. + * @param {string} faceId - The ID of the face to be added. The maximum face amount for each person is 32. + * @param {string} userData - Optional. Attach user data to person's face. The maximum length is 1024. + * @return {Promise} - Promise resolving with the resulting JSON + */ + public addFace(personGroupId: string, personId: string, faceId: string, userData?: string): Promise; + + /** + * Deletes a face from a person. + * + * @param {string} personGroupId - The target person's person group. + * @param {string} personId - The target person that the face is removed from. + * @param {string} faceId - The ID of the face to be deleted. + * @return {Promise} - Promise resolving with the resulting JSON + */ + public deleteFace(personGroupId: string, personId: string, faceId: string): Promise; + + /** + * Updates a face for a person. + * + * @param {string} personGroupId - The target person's person group. + * @param {string} personId - The target person that the face is updated on. + * @param {string} faceId - The ID of the face to be updated. + * @param {string} userData - Optional. Attach user data to person's face. The maximum length is 1024. + * @return {Promise} - Promise resolving with the resulting JSON + */ + public updateFace(personGroupId: string, personId: string, faceId: string, userData: string): Promise; + + /** + * Get a face for a person. + * + * @param {string} personGroupId - The target person's person group. + * @param {string} personId - The target person that the face is to get from. + * @param {string} faceId - The ID of the face to get. + * @return {Promise} - Promise resolving with the resulting JSON + */ + public getFace(personGroupId: string, personId: string, faceId: string): Promise; + + /** + * Creates a new person in a specified person group for identification. + * The number of persons has a subscription limit. Free subscription amount is 1000 persons. + * The maximum face count for each person is 32. + * + * @param {string} personGroupId - The target person's person group. + * @param {string[]} faces - Array of face id's for the target person + * @param {string} name - Target person's display name. The maximum length is 128. + * @param {string} userData - Optional fields for user-provided data attached to a person. Size limit is 16KB. + * @return {Promise} - Promise resolving with the resulting JSON + */ + public create(personGroupId: string, faces: string[], name: string, userData: string): Promise<{ personId: string }>; + + /** + * Deletes an existing person from a person group. + * + * @param {string} personGroupId - The target person's person group. + * @param {string} personId - The target person to delete. + * @return {Promise} - Promise resolving with the resulting JSON + */ + public delete(personGroupId: string, personId: string): Promise; + + /** + * Gets an existing person from a person group. + * + * @param {string} personGroupId - The target person's person group. + * @param {string} personId - The target person to get. + * @return {Promise} - Promise resolving with the resulting JSON + */ + public get(personGroupId: string, personId: string): Promise; + + /** + * Updates a person's information. + * + * @param {string} personGroupId - The target person's person group. + * @param {string[]} faces - Array of face id's for the target person + * @param {string} name - Target person's display name. The maximum length is 128. + * @param {string} userData - Optional fields for user-provided data attached to a person. Size limit is 16KB. + * @return {Promise} - Promise resolving with the resulting JSON + */ + public update(personGroupId: string, personId: string, faces: string[], name: string, userData: string): Promise; + + /** + * Lists all persons in a person group, with the person information. + * + * @param {string} personGroupId - The target person's person group. + * @return {Promise} - Promise resolving with the resulting JSON + */ + public list(personGroupId: string): Promise; + } + + module Options { + interface Detect { + url?: string; // URL to image to be used + path?: string; // Path to image to be used + stream?: stream.Stream; // Stream of an image to be used + analyzesFaceLandmarks?: boolean; // Analyze face landmarks? + analyzesAge?: boolean; // Analyze age? + analyzesGender?: boolean; // Analyze gender? + analyzesHeadPose?: boolean; //Analyze headpose? + } + + interface Identify { + personGroupId: string; + maxNumOfCandidatesReturned: number; // range is 1-10 + } + + interface Analyze { + url?: string; // Url to image to be analyzed + path?: string; // Path to image to be analyzed + ImageType?: boolean; // Detects if image is clipart or a line drawing. + Color?: boolean; // Determines the accent color, dominant color, if image is black& white. + Faces?: boolean; // Detects if faces are present.If present, generate coordinates, gender and age. + Adult?: boolean; // Detects if image is pornographic in nature(nudity or sex act).Sexually suggestive content is also detected. + Categories?: boolean; // Image categorization; taxonomy defined in documentation. + } + + interface Thumbnail { + url?: string; // Url to image to be thumbnailed + path?: string; // Path to image to be thumbnailed + width?: number; // Width of the thumb in pixels + height?: number; // Height of the thumb in pixels + smartCropping?: boolean; // Should SmartCropping be enabled? + pipe?: stream.Writable; // We'll pipe the returned image to this object + } + + interface Ocr { + url?: string; // URL to image to be analyzed + path?: string; // Path to image to be analyzed + language?: string; //BCP - 47 language code of the text to be detected in the image.Default value is "unk", then the service will auto detect the language of the text in the image. + detectOrientation?: boolean; // Detect orientation of text in the image + } + } + + module FaceResponses { + interface FaceRectangle { + top: number; + left: number; + width: number; + height: number; + } + + interface point { + x: number; + y: number; + } + + interface FaceLandmarks { + "pupilLeft": point; + "pupilRight": point; + "noseTip": point; + "mouthLeft": point; + "mouthRight": point; + "eyebrowLeftOuter": point; + "eyebrowLeftInner": point; + "eyeLeftOuter": point; + "eyeLeftTop": point; + "eyeLeftBottom": point; + "eyeLeftInner": point; + "eyebrowRightInner": point; + "eyebrowRightOuter": point; + "eyeRightInner": point; + "eyeRightTop": point; + "eyeRightBottom": point; + "eyeRightOuter": point; + "noseRootLeft": point; + "noseRootRight": point; + "noseLeftAlarTop": point; + "noseRightAlarTop": point; + "noseLeftAlarOutTip": point; + "noseRightAlarOutTip": point; + "upperLipTop": point; + "upperLipBottom": point; + "underLipTop": point; + "underLipBottom": point; + } + + interface Attributes { + "headPose": { "pitch": number, "roll": number, "yaw": number }; + "gender": string; + "age": number; + } + + export interface Detect { + "faceId": string; + "faceRectangle": FaceRectangle; + "faceLandmarks": FaceLandmarks; + "attributes": Attributes; + } + + export interface Similar { + "faceIds": string[]; + } + + export interface Grouping { + "groups": string[]; + "messyGroup": string[]; + } + + export interface Identify { + "faceId": string; + "candidates": [{ + personId: string; + confidence: number; + }]; + } + + export interface Verify { + "isIdentical": boolean; + "confidence": number; + } + } + + module PersonGroupResponses { + + export interface PersonGroup { + "personGroupId": string; + "name": string; + "userData": string; + } + + export interface TrainingStatus { + "personGroupId": string; + "status": string; + "startTime": string; + "endTime": string; + } + } + + module PersonResponses { + export interface Create { + "personId": string; + } + + export interface Person { + "personId": string; + "faceIds": string[]; + "name": string; + "userData": string; + } + + export interface Face { + "faceId": string; + "userData": string; + } + } + + module VisionResponses { + export interface Analyze { + "categories": [{ + "name": string; + "score": number; + }], + "adult": { + "isAdultContent": boolean; + "isRacyContent": boolean; + "adultScore": number; + "racyScore": number; + }, + "requestId": string; + "metadata": { + "width": number; + "height": number; + "format": string; + }, + "faces": [ + { + "age": number; + "gender": string; + "faceRectangle": { + "left": number; + "top": number; + "width": number; + "height": number; + } + } + ], + "color": { + "dominantColorForeground": string; + "dominantColorBackground": string; + "dominantColors": string[]; + "accentColor": string; + "isBWImg": boolean; + }, + "imageType": { + "clipArtType": number; + "lineDrawingType": number; + } + } + + + export interface Ocr { + "language": string; + "textAngle": number; + "orientation": string; + "regions": [{ + "boundingBox": string; + "lines": [{ + "boundingBox": string; + "words": [{ + "boundingBox": string; + "text": string; + }] + }] + }] + } + } +} \ No newline at end of file From 59797782303f5a2eeaede3dc2b1680ae1cb41179 Mon Sep 17 00:00:00 2001 From: Oguzhan Ergin Date: Sat, 22 Aug 2015 03:25:06 +0300 Subject: [PATCH 172/345] Added fs-ext tests --- fs-ext/fs-ext-tests.ts | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 fs-ext/fs-ext-tests.ts diff --git a/fs-ext/fs-ext-tests.ts b/fs-ext/fs-ext-tests.ts new file mode 100644 index 000000000..aba507c6d --- /dev/null +++ b/fs-ext/fs-ext-tests.ts @@ -0,0 +1,28 @@ +/// +/// + +import fs = require('fs-ext'); + +var num:number; +var str:string; + +//from node.js 'fs' module +fs.appendFileSync(str, "data"); + +fs.flock(num, str, (err)=>{ +}); +fs.flockSync(num, str); + +fs.fcntl(num, str, num, (err, res)=>{ +}); +fs.fcntl(num, str, (err, res)=>{ +}); +fs.fcntlSync(num, str, num); + +fs.seek(num, num, num, (err, pos)=>{ +}); +fs.seekSync(num, num, num); + +fs.utime(str, num, num, (err)=>{ +}); +fs.utimeSync(str, num, num); From 7ed5ae7715b98719e4fad15fc0fdaa1a72d2a494 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Fri, 21 Aug 2015 17:36:47 -0700 Subject: [PATCH 173/345] Add indexer for 'node-azure'. --- node-azure/azure.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/node-azure/azure.d.ts b/node-azure/azure.d.ts index 7e52a8be3..c7818d0b6 100644 --- a/node-azure/azure.d.ts +++ b/node-azure/azure.d.ts @@ -1627,6 +1627,7 @@ declare module "azure" { RowKey: string; Timestamp?: Date; etag?: string; + [property: string]: string | number | boolean | Date; } //#endregion //#region BlobService Interfaces From 58a1b6b8487a4532d528dd1d334694d59863562c Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Fri, 21 Aug 2015 17:44:51 -0700 Subject: [PATCH 174/345] Added index signatures to prototype objects in 'blocks'. --- blocks/blocks.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/blocks/blocks.d.ts b/blocks/blocks.d.ts index ad492333e..6e57ec762 100644 --- a/blocks/blocks.d.ts +++ b/blocks/blocks.d.ts @@ -579,6 +579,8 @@ interface ViewPrototype { route?: any; url?: string }; + + [propertyName: string]: any; } ///////////////////////////////////////// @@ -643,6 +645,8 @@ interface ModelPrototype { destroy?: { url?: string }; update?: { url?: string }; }; + + [propertyName: string]: string | boolean | Object | Validator; } ///////////////////////////////////////// @@ -682,6 +686,7 @@ interface CollectionPrototype { destroy?: { url?: string }; update?: { url?: string }; }; + [propertyName: string]: any; } interface Extendable { From 8423202086f79d9f13609fb228eb26ee5e6756d0 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Fri, 21 Aug 2015 18:23:07 -0700 Subject: [PATCH 175/345] Added what appears to be an undocumented but used property in 'ace'. --- ace/ace.d.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/ace/ace.d.ts b/ace/ace.d.ts index f0668da3c..bedcfee54 100644 --- a/ace/ace.d.ts +++ b/ace/ace.d.ts @@ -18,7 +18,9 @@ declare module AceAjax { bindKey:any; - exec:Function; + exec: Function; + + readOnly?: boolean; } export interface CommandManager { From 683a463333639e64a69dde18f8dba53f84aafd8b Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Fri, 21 Aug 2015 18:28:42 -0700 Subject: [PATCH 176/345] Fixed types for 'globalization.dateToString' in 'cordova'. --- cordova/plugins/Globalization.d.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/cordova/plugins/Globalization.d.ts b/cordova/plugins/Globalization.d.ts index bb9cd2f4a..f49e2bf4b 100644 --- a/cordova/plugins/Globalization.d.ts +++ b/cordova/plugins/Globalization.d.ts @@ -41,12 +41,17 @@ interface Globalization { * @param onError Called on error with a GlobalizationError object. * The error's expected code is GlobalizationError.FORMATTING_ERROR. * @param options Optional format parameters. Default {formatLength:'short', selector:'date and time'} + * - 'formatLength' can be "short", "medium", "long", or "full". + * - 'selector' can be "date", "time", or "date and time". */ dateToString( date: Date, onSuccess: (date: { value: string; }) => void, onError: (error: GlobalizationError) => void, - options?: { type?: string; item?: string; }): void; + options?: { + formatLength?: string; // "short" | "medium" | "long" | "full" + selector?: string; // "date" | "time" | "date and time" + }): void; /** * Parses a date formatted as a string, according to the client's user preferences * and calendar using the time zone of the client, and returns the corresponding date object. From 5f2a6b0dc360fdbd09a9b8e16ad3e6aad919837a Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Fri, 21 Aug 2015 18:37:40 -0700 Subject: [PATCH 177/345] Fixed tests, use proper interface, in 'peerjs'. --- peerjs/peerjs-tests.ts | 11 +++++++---- peerjs/peerjs.d.ts | 2 +- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/peerjs/peerjs-tests.ts b/peerjs/peerjs-tests.ts index 3b99471c7..dee76d9e2 100644 --- a/peerjs/peerjs-tests.ts +++ b/peerjs/peerjs-tests.ts @@ -4,8 +4,10 @@ var peerByOption: PeerJs.Peer = new Peer({ key: 'peerKey', debug: 3, - logFunction: ()=>{ - } +}); + +peerByOption.on("connection", dataConnection => { + var type: string = dataConnection.type; }); peerByOption.listAllPeers(function(items){ @@ -21,9 +23,10 @@ var peerByIdAndOption: PeerJs.Peer = new Peer( { key: 'peerKey', debug: 3, - logFunction: ()=>{ - } }); +peerByIdAndOption.on("call", mediaConnection => { + var isOpen: boolean = mediaConnection.open; +}); var id = peerByOption.id; var connections = peerByOption.connections; diff --git a/peerjs/peerjs.d.ts b/peerjs/peerjs.d.ts index b87d3bc87..7db935ffb 100644 --- a/peerjs/peerjs.d.ts +++ b/peerjs/peerjs.d.ts @@ -78,7 +78,7 @@ declare module PeerJs{ * @param id The brokering ID of the remote peer (their peer.id). * @param options for specifying details about Peer Connection */ - connect(id: string, options?: PeerJs.PeerJSOption): PeerJs.DataConnection; + connect(id: string, options?: PeerJs.PeerConnectOption): PeerJs.DataConnection; /** * Connects to the remote peer specified by id and returns a data connection. * @param id The brokering ID of the remote peer (their peer.id). From 0871a4a59731d96e77bd4c41a6e025ca23378b96 Mon Sep 17 00:00:00 2001 From: zgmnkv Date: Sat, 22 Aug 2015 13:07:42 +0400 Subject: [PATCH 178/345] Added 'defaultFormat' to Moment.js definition --- moment/moment-node.d.ts | 2 ++ moment/moment-tests.ts | 2 ++ 2 files changed, 4 insertions(+) diff --git a/moment/moment-node.d.ts b/moment/moment-node.d.ts index 48f00ed98..b109893a3 100644 --- a/moment/moment-node.d.ts +++ b/moment/moment-node.d.ts @@ -467,6 +467,8 @@ declare module moment { */ ISO_8601(): void; + defaultFormat: string; + } } diff --git a/moment/moment-tests.ts b/moment/moment-tests.ts index 04c075352..29712c115 100644 --- a/moment/moment-tests.ts +++ b/moment/moment-tests.ts @@ -459,3 +459,5 @@ moment.locale('en', { }); console.log(moment.version); + +moment.defaultFormat = 'YYYY-MM-DD HH:mm'; From e78260ef9b39498a6a1bb513eeb4e0ba37203c25 Mon Sep 17 00:00:00 2001 From: Marcin Porebski Date: Sat, 22 Aug 2015 14:31:43 +0200 Subject: [PATCH 179/345] added empty module to string_score --- string_score/string_score.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/string_score/string_score.d.ts b/string_score/string_score.d.ts index 5e3ee05d5..6b3944c4e 100644 --- a/string_score/string_score.d.ts +++ b/string_score/string_score.d.ts @@ -3,6 +3,11 @@ // Definitions by: Marcin Porębski // Definitions: https://github.com/borisyankov/DefinitelyTyped +declare module "string_score" +{ + // nothing here as it's only extending the build in String class +} + interface String { score: (word: string, fuzzy?: number) => number; } From 762a789651c795de9a2669a812ec45dbaca3604a Mon Sep 17 00:00:00 2001 From: Aya Morisawa Date: Sun, 23 Aug 2015 00:20:29 +0900 Subject: [PATCH 180/345] Add gulp-dtsm.d.ts --- gulp-dtsm/gulp-dtsm-tests.ts | 11 +++++++++++ gulp-dtsm/gulp-dtsm.d.ts | 13 +++++++++++++ 2 files changed, 24 insertions(+) create mode 100644 gulp-dtsm/gulp-dtsm-tests.ts create mode 100644 gulp-dtsm/gulp-dtsm.d.ts diff --git a/gulp-dtsm/gulp-dtsm-tests.ts b/gulp-dtsm/gulp-dtsm-tests.ts new file mode 100644 index 000000000..f97f8705e --- /dev/null +++ b/gulp-dtsm/gulp-dtsm-tests.ts @@ -0,0 +1,11 @@ +/// +/// +/// + +import dtsm = require('gulp-dtsm'); +import gulp = require('gulp'); + +var stream: NodeJS.WritableStream = dtsm(); + +gulp.task('dtsm', () => gulp.src('./dtsm.json').pipe(dtsm())); + diff --git a/gulp-dtsm/gulp-dtsm.d.ts b/gulp-dtsm/gulp-dtsm.d.ts new file mode 100644 index 000000000..a8fe7878f --- /dev/null +++ b/gulp-dtsm/gulp-dtsm.d.ts @@ -0,0 +1,13 @@ +// Type definitions for gulp-dtsm 0.0.0 +// Project: https://github.com/9joneg/gulp-dtsm +// Definitions by: Aya Morisawa +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "gulp-dtsm" { + function dtsm(): NodeJS.WritableStream; + + export = dtsm; +} + From 06274a0a71092026b61d4cf764a0b84bbcf9bc97 Mon Sep 17 00:00:00 2001 From: TeamworkGuy2 Date: Sat, 22 Aug 2015 18:51:52 +0000 Subject: [PATCH 181/345] Added type definition for translate() 'options' parameter based on the source code from https://github.com/jamuhl/i18next/ --- i18next/i18next.d.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/i18next/i18next.d.ts b/i18next/i18next.d.ts index 060335af0..feb6658c8 100644 --- a/i18next/i18next.d.ts +++ b/i18next/i18next.d.ts @@ -17,6 +17,10 @@ interface IResourceStoreKey { [key: string]: any; } +interface I18nTranslateOptions extends I18nextOptions { + defaultValue?: any; // normally a string +} + interface I18nextOptions { lng?: string; // Default value: undefined load?: string; // Default value: 'all' @@ -108,8 +112,8 @@ interface I18nextStatic { load: (languages: string[], options: I18nextOptions, callback: (err: Error, store: IResourceStore) => void ) => void; postMissing: (language: string, namespace: string, key: string, defaultValue: any, languages: string[]) => void; }; - t(key: string, options?: any): string; - translate(key: string, options?: any): string; + t(key: string, options?: I18nTranslateOptions): string; + translate(key: string, options?: I18nTranslateOptions): string; exists(key: string, options?: any): boolean; } From 24e08c7acccd80a1a9b87df9d1307f71422035fd Mon Sep 17 00:00:00 2001 From: Necroskillz Date: Sat, 22 Aug 2015 23:00:53 +0200 Subject: [PATCH 182/345] Update minimist definition to 1.1.3 - Add indexer to ParsedArgs - Add new options and options types --- minimist/minimist-tests.ts | 15 +++++++++++++++ minimist/minimist.d.ts | 16 ++++++++++++---- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/minimist/minimist-tests.ts b/minimist/minimist-tests.ts index 1f714fd3e..2266d2739 100644 --- a/minimist/minimist-tests.ts +++ b/minimist/minimist-tests.ts @@ -9,8 +9,12 @@ var strArr: string[]; var args: string[]; var obj: minimist.ParsedArgs; var opts: Opts; +var arg: any; +opts.string = str; opts.string = strArr; +opts.boolean = true; +opts.boolean = str; opts.boolean = strArr; opts.alias = { foo: strArr @@ -21,8 +25,19 @@ opts.default = { opts.default = { foo: num }; +opts.unknown = (arg: string) => { + if(/xyz/.test(arg)){ + return true; + } + + return false; +}; +opts.stopEarly = true; +opts['--'] = true; obj = minimist(); obj = minimist(strArr); obj = minimist(strArr, opts); var remainingArgCount = obj._.length; + +arg = obj['foo']; diff --git a/minimist/minimist.d.ts b/minimist/minimist.d.ts index 98d0f37a8..abbc5f028 100644 --- a/minimist/minimist.d.ts +++ b/minimist/minimist.d.ts @@ -1,6 +1,6 @@ -// Type definitions for minimist 0.0.8 +// Type definitions for minimist 1.1.3 // Project: https://github.com/substack/minimist -// Definitions by: Bart van der Schoor +// Definitions by: Bart van der Schoor , Necroskillz // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module 'minimist' { @@ -10,18 +10,26 @@ declare module 'minimist' { export interface Opts { // a string or array of strings argument names to always treat as strings // string?: string; - string?: string[]; + string?: string|string[]; // a string or array of strings to always treat as booleans // boolean?: string; - boolean?: string[]; + boolean?: boolean|string|string[]; // an object mapping string names to strings or arrays of string argument names to use // alias?: {[key:string]: string}; alias?: {[key:string]: string[]}; // an object mapping string argument names to default values default?: {[key:string]: any}; + // when true, populate argv._ with everything after the first non-option + stopEarly?: boolean; + // a function which is invoked with a command line parameter not defined in the opts configuration object. + // If the function returns false, the unknown option is not added to argv + unknown?: (arg: string) => boolean; + // when true, populate argv._ with everything before the -- and argv['--'] with everything after the -- + '--'?: boolean; } export interface ParsedArgs { + [arg: string]: any; _: string[]; } } From f13c2224e8fd065961b595b9dfa9d0dacfe56eb8 Mon Sep 17 00:00:00 2001 From: satoru kimura Date: Sun, 23 Aug 2015 17:28:53 +0900 Subject: [PATCH 183/345] Removed a reference to waa.d.ts in SoundJS definition. --- soundjs/soundjs.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/soundjs/soundjs.d.ts b/soundjs/soundjs.d.ts index 90e50200d..899063467 100644 --- a/soundjs/soundjs.d.ts +++ b/soundjs/soundjs.d.ts @@ -14,7 +14,6 @@ /// /// -/// declare module createjs { From c71755a6ab800b3776b9e23ce9817b5f0ccbb7e6 Mon Sep 17 00:00:00 2001 From: satoru kimura Date: Sun, 23 Aug 2015 17:32:56 +0900 Subject: [PATCH 184/345] Removed a reference to waa.d.ts in three.js definition. --- threejs/three.d.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/threejs/three.d.ts b/threejs/three.d.ts index 826d6332f..1e97210d5 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -3,8 +3,6 @@ // Definitions by: Kon , Satoru Kimura // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// - interface WebGLRenderingContext {} declare module THREE { From 690513a198642797773236fd1a3b667faa1dc463 Mon Sep 17 00:00:00 2001 From: vvakame Date: Sun, 23 Aug 2015 21:08:48 +0900 Subject: [PATCH 185/345] fix `npm run all` failed. sequelize-fixtures --- sequelize-fixtures/sequelize-fixtures-tests.ts | 3 ++- sequelize-fixtures/sequelize-fixtures.d.ts | 10 +++++----- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/sequelize-fixtures/sequelize-fixtures-tests.ts b/sequelize-fixtures/sequelize-fixtures-tests.ts index 567cf5967..c6edfd28f 100644 --- a/sequelize-fixtures/sequelize-fixtures-tests.ts +++ b/sequelize-fixtures/sequelize-fixtures-tests.ts @@ -15,7 +15,8 @@ SequelizeFixtures.loadFiles([], {}, { log: m => { } }).then(() => { }); SequelizeFixtures.loadFixture({}, {}).then(() => { }); sequelize.transaction(function (tx) { SequelizeFixtures.loadFixture({}, {}, { transaction: tx }).then(() => { }); + return null; }); SequelizeFixtures.loadFixtures([], {}).then(() => { }); -SequelizeFixtures.loadFixtures([], {}, { transformFixtureDataFn: (data) => { return data; } }).then(() => { }); \ No newline at end of file +SequelizeFixtures.loadFixtures([], {}, { transformFixtureDataFn: (data) => { return data; } }).then(() => { }); diff --git a/sequelize-fixtures/sequelize-fixtures.d.ts b/sequelize-fixtures/sequelize-fixtures.d.ts index 3cdf3fe8d..5358110f1 100644 --- a/sequelize-fixtures/sequelize-fixtures.d.ts +++ b/sequelize-fixtures/sequelize-fixtures.d.ts @@ -18,14 +18,14 @@ declare module "sequelize-fixtures" } interface SequelizeFixturesStatic { - loadFile(file: string, models: any, options?: Options): Sequelize.Promise; - loadFiles(files: string[], models: any, options?: Options): Sequelize.Promise; - loadFixture(fixture: any, models: any, options?: Options): Sequelize.Promise; - loadFixtures(fixtures: any[], models: any, options?: Options): Sequelize.Promise; + loadFile(file: string, models: any, options?: Options): Promise; + loadFiles(files: string[], models: any, options?: Options): Promise; + loadFixture(fixture: any, models: any, options?: Options): Promise; + loadFixtures(fixtures: any[], models: any, options?: Options): Promise; } } var sequelizeFixtures: SequelizeFixtures.SequelizeFixturesStatic; export = sequelizeFixtures; -} \ No newline at end of file +} From ae3ce43c89688bf0367f7649e578b4a7c47ee487 Mon Sep 17 00:00:00 2001 From: inker Date: Sun, 23 Aug 2015 19:51:32 +0300 Subject: [PATCH 186/345] A fix for the victor.js TS definition file The Victor class is now correctly exported as default. --- victor/victor.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/victor/victor.d.ts b/victor/victor.d.ts index 4206ffeb6..7812abcee 100644 --- a/victor/victor.d.ts +++ b/victor/victor.d.ts @@ -353,3 +353,7 @@ declare class Victor verticalAngleDeg():number; } + +declare module "victor" { + export = Victor; +} From c4e5067c3c3628828b6232deccc8e8cda87e3f0c Mon Sep 17 00:00:00 2001 From: Paulo Cesar Date: Sun, 23 Aug 2015 15:54:58 -0300 Subject: [PATCH 187/345] add bowser --- bowser/bowser-tests.ts | 7 ++++++ bowser/bowser.d.ts | 54 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 bowser/bowser-tests.ts create mode 100644 bowser/bowser.d.ts diff --git a/bowser/bowser-tests.ts b/bowser/bowser-tests.ts new file mode 100644 index 000000000..07d9f18cb --- /dev/null +++ b/bowser/bowser-tests.ts @@ -0,0 +1,7 @@ +import Bowser = require('bowser'); + +Bowser.msedge === true; +Bowser.test(['msie']) === true; +Bowser.a === Bowser.c; +Bowser.osversion > 10; +Bowser.osversion === '10.1A'; \ No newline at end of file diff --git a/bowser/bowser.d.ts b/bowser/bowser.d.ts new file mode 100644 index 000000000..afd15fa5d --- /dev/null +++ b/bowser/bowser.d.ts @@ -0,0 +1,54 @@ +// Type definitions for Bowser 1.x +// Project: https://github.com/ded/bowser +// Definitions by: Paulo Cesar +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module 'bowser' { + var def: BowserModule.IBowser; + export = def; +} + +declare module BowserModule { + + export interface IBowserUA { + msie: boolean; + chrome: boolean; + webkit: boolean; + phantom: boolean; + opera: boolean; + safari: boolean; + android: boolean; + ios: boolean; + webos: boolean; + msedge: boolean; + seamonkey: boolean; + firefox: boolean; + yandexbrowser: boolean; + blackberry: boolean; + tablet: boolean; + mobile: boolean; + silk: boolean; + bada: boolean; + tizen: boolean; + windowsphone: boolean; + firefoxos: boolean; + gecko: boolean; + sailfish: boolean; + chromeBook: boolean; + /** Grade A browser */ + a: boolean; + /** Grade C browser */ + c: boolean; + /** Grade X browser */ + x: boolean; + name: string; + version: string; + osversion: string|number; + } + + export interface IBowser extends IBowserUA { + test(browserList: string[]): boolean; + _detect(ua: string): IBowser; + } + +} From 62d90e23aa0c0855c0959052e561170832a86e94 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Sun, 23 Aug 2015 06:35:29 +0500 Subject: [PATCH 188/345] lodash: changed _.camelCase() method --- lodash/lodash-tests.ts | 3 +++ lodash/lodash.d.ts | 18 +++++++++++++++++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 00ca144fd..cd74cd625 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1725,7 +1725,10 @@ result = _.uniqueId(); * String *********/ +// _.camelCase result = _.camelCase('Foo Bar'); +result = _('Foo Bar').camelCase(); + result = _.capitalize('fred'); // _.deburr diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 77daeca2a..719247480 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -7525,8 +7525,24 @@ declare module _ { * String * **********/ + //_.camelCase + interface LoDashStatic { + /** + * Converts string to camel case. + * @param string The string to convert. + * @return Returns the camel cased string. + */ + camelCase(string?: string): string; + } + + interface LoDashWrapper { + /** + * @see _.camelCase + */ + camelCase(): string; + } + interface LoDashStatic { - camelCase(str?: string): string; capitalize(str?: string): string; } From 5b205217f73ee21a84d7936f770ccf67875ce278 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Sat, 22 Aug 2015 14:29:59 +0500 Subject: [PATCH 189/345] lodash: changed _.isDate() method --- lodash/lodash-tests.ts | 8 ++++++-- lodash/lodash.d.ts | 27 +++++++++++++++++---------- 2 files changed, 23 insertions(+), 12 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 00ca144fd..61fb8170e 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1201,6 +1201,12 @@ result = _(1).isArray(); result = _([]).isArray(); result = _({}).isArray(); +// _.isDate +result = _.isDate(any); +result = _(42).isDate(); +result = _([]).isDate(); +result = _({}).isDate(); + // _.isEmpty result = _.isEmpty([1, 2, 3]); result = _.isEmpty({}); @@ -1441,8 +1447,6 @@ result = _.invert({ 'first': 'moe', 'second': 'larry' }); result = _.isBoolean(null); -result = _.isDate(new Date()); - result = _.isElement(document.body); // _.isEqual (alias: _.eq) diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 77daeca2a..8da8a1938 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -6179,6 +6179,23 @@ declare module _ { isArray(): boolean; } + //_.isDate + interface LoDashStatic { + /** + * Checks if value is classified as a Date object. + * @param value The value to check. + * @return Returns true if value is correctly classified, else false. + **/ + isDate(value?: any): boolean; + } + + interface LoDashWrapperBase { + /** + * @see _.isDate + */ + isDate(): boolean; + } + //_.isEmpty interface LoDashStatic { /** @@ -6979,16 +6996,6 @@ declare module _ { isBoolean(value?: any): boolean; } - //_.isDate - interface LoDashStatic { - /** - * Checks if value is a date. - * @param value The value to check. - * @return True if the value is a date, else false. - **/ - isDate(value?: any): boolean; - } - //_.isElement interface LoDashStatic { /** From f569128818c2b4bb9a7f3e7243edf618f213eae1 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Sat, 22 Aug 2015 14:38:19 +0500 Subject: [PATCH 190/345] lodash: changed _.isNumber() method --- lodash/lodash-tests.ts | 8 ++++++-- lodash/lodash.d.ts | 30 ++++++++++++++++++------------ 2 files changed, 24 insertions(+), 14 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 00ca144fd..860af6550 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1236,6 +1236,12 @@ result = _(undefined).isNaN(); result = _.isNative(Array.prototype.push); result = _(Array.prototype.push).isNative(); +// _.isNumber +result = _.isNumber(any); +result = _(1).isNumber(); +result = _([]).isNumber(); +result = _({}).isNumber(); + // _.isRegExp result = _.isRegExp(any); result = _(1).isRegExp(); @@ -1475,8 +1481,6 @@ result = _.isFunction(_); result = _.isNull(null); result = _.isNull(undefined); -result = _.isNumber(8.4 * 5); - result = _.isObject({}); result = _.isObject([1, 2, 3]); result = _.isObject(1); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 77daeca2a..b275a5b33 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -6277,6 +6277,24 @@ declare module _ { isNative(): boolean; } + //_.isNumber + interface LoDashStatic { + /** + * Checks if value is classified as a Number primitive or object. + * Note: To exclude Infinity, -Infinity, and NaN, which are classified as numbers, use the _.isFinite method. + * @param value The value to check. + * @return Returns true if value is correctly classified, else false. + */ + isNumber(value?: any): boolean; + } + + interface LoDashWrapperBase { + /** + * see _.isNumber + */ + isNumber(): boolean; + } + //_.isRegExp interface LoDashStatic { /** @@ -7110,18 +7128,6 @@ declare module _ { isNull(value?: any): boolean; } - //_.isNumber - interface LoDashStatic { - /** - * Checks if value is a number. - * - * Note: NaN is considered a number. See http://es5.github.io/#x8.5. - * @param value The value to check. - * @return True if the value is a number, else false. - **/ - isNumber(value?: any): boolean; - } - //_.isObject interface LoDashStatic { /** From 3bb67023949e0a303efaaeca7e59357cf14782a5 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Sat, 22 Aug 2015 14:47:40 +0500 Subject: [PATCH 191/345] lodash: changed _.isString() method --- lodash/lodash-tests.ts | 8 ++++++-- lodash/lodash.d.ts | 27 +++++++++++++++++---------- 2 files changed, 23 insertions(+), 12 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 00ca144fd..f81217255 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1242,6 +1242,12 @@ result = _(1).isRegExp(); result = _([]).isRegExp(); result = _({}).isRegExp(); +// _.isString +result = _.isString(any); +result = _(1).isString(); +result = _([]).isString(); +result = _({}).isString(); + // _.isTypedArray result = _.isTypedArray([]); result = _([]).isTypedArray(); @@ -1492,8 +1498,6 @@ result = _.isPlainObject(new Stooge('moe', 40)); result = _.isPlainObject([1, 2, 3]); result = _.isPlainObject({ 'name': 'moe', 'age': 40 }); -result = _.isString('moe'); - result = _.keys({ 'one': 1, 'two': 2, 'three': 3 }); result = _({ 'one': 1, 'two': 2, 'three': 3 }).keys().value(); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 77daeca2a..b1082a459 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -6294,6 +6294,23 @@ declare module _ { isRegExp(): boolean; } + //_.isString + interface LoDashStatic { + /** + * Checks if value is classified as a String primitive or object. + * @param value The value to check. + * @return Returns true if value is correctly classified, else false. + **/ + isString(value?: any): boolean; + } + + interface LoDashWrapperBase { + /** + * see _.isString + */ + isString(): boolean; + } + //_.isTypedArray interface LoDashStatic { /** @@ -7143,16 +7160,6 @@ declare module _ { isPlainObject(value?: any): boolean; } - //_.isString - interface LoDashStatic { - /** - * Checks if value is a string. - * @param value The value to check. - * @return True if the value is a string, else false. - **/ - isString(value?: any): boolean; - } - //_.keys interface LoDashStatic { /** From 8fc36468726f50b2be2a7ef5e3dece312ba80f66 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Fri, 21 Aug 2015 06:19:06 +0500 Subject: [PATCH 192/345] lodash: changed _.repeat() method --- lodash/lodash-tests.ts | 6 ++++-- lodash/lodash.d.ts | 16 +++++++++++++++- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 00ca144fd..8183c54a5 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1768,14 +1768,16 @@ result = _('abc').padRight(); result = _('abc').padRight(6); result = _('abc').padRight(6, '_-'); -result = _.repeat('*', 3); - // _.parseInt result = _.parseInt('08'); result = _.parseInt('08', 10); result = _('08').parseInt(); result = _('08').parseInt(10); +// _.repeat +result = _.repeat('*', 3); +result = _('*').repeat(3); + // _.snakeCase result = _.snakeCase('Foo Bar'); result = _('Foo Bar').snakeCase(); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 77daeca2a..5c57d76f3 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -7672,8 +7672,22 @@ declare module _ { parseInt(radix?: number): number; } + //_.repeat interface LoDashStatic { - repeat(str?: string, n?: number): string; + /** + * Repeats the given string n times. + * @param string The string to repeat. + * @param n The number of times to repeat the string. + * @return Returns the repeated string. + */ + repeat(string?: string, n?: number): string; + } + + interface LoDashWrapper { + /** + * @see _.repeat + */ + repeat(n?: number): string; } //_.snakeCase From 527298c48e0ed3a84c46a58ea15c7c0ce27bf7ec Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Sun, 23 Aug 2015 06:30:41 +0500 Subject: [PATCH 193/345] lodash: changed _.startCase() method --- lodash/lodash-tests.ts | 2 ++ lodash/lodash.d.ts | 15 ++++++++++++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 00ca144fd..4369803ba 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1780,7 +1780,9 @@ result = _('08').parseInt(10); result = _.snakeCase('Foo Bar'); result = _('Foo Bar').snakeCase(); +// _.startCase result = _.startCase('--foo-bar'); +result = _('--foo-bar').startCase(); // _.startsWith result = _.startsWith('abc', 'a'); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 77daeca2a..188556e6e 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -7693,8 +7693,21 @@ declare module _ { snakeCase(): string; } + //_.startCase interface LoDashStatic { - startCase(str?: string): string; + /** + * Converts string to start case. + * @param string The string to convert. + * @return Returns the start cased string. + */ + startCase(string?: string): string; + } + + interface LoDashWrapper { + /** + * @see _.startCase + */ + startCase(): string; } //_.startsWith From cf410b943a4c55b3dab8f0b925c5790633244670 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Sun, 23 Aug 2015 06:23:09 +0500 Subject: [PATCH 194/345] lodash: changed _.words() method --- lodash/lodash-tests.ts | 3 +++ lodash/lodash.d.ts | 16 +++++++++++++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 00ca144fd..3bc21ed4e 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1825,8 +1825,11 @@ result = _('hi-diddly-ho there, neighborino').trunc({ 'omission': ' [… result = _.unescape('fred, barney, & pebbles'); result = _('fred, barney, & pebbles').unescape(); +// _.words result = _.words('fred, barney, & pebbles'); result = _.words('fred, barney, & pebbles', /[^, ]+/g); +result = _('fred, barney, & pebbles').words(); +result = _('fred, barney, & pebbles').words(/[^, ]+/g); /********** * Utilities * diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 77daeca2a..0e86d6651 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -7816,8 +7816,22 @@ declare module _ { unescape(): string; } + //_.words interface LoDashStatic { - words(str?: string, pattern?: string|RegExp): string[]; + /** + * Splits string into an array of its words. + * @param string The string to inspect. + * @param pattern The pattern to match words. + * @return Returns the words of string. + */ + words(string?: string, pattern?: string|RegExp): string[]; + } + + interface LoDashWrapper { + /** + * @see _.words + */ + words(pattern?: string|RegExp): string[]; } /*********** From 61c54e2b00b53570d2fbace9b59e2ff1240875e6 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Mon, 24 Aug 2015 00:25:56 +0500 Subject: [PATCH 195/345] lodash: changed _.isArguments() method --- lodash/lodash-tests.ts | 8 ++++++-- lodash/lodash.d.ts | 27 +++++++++++++++++---------- 2 files changed, 23 insertions(+), 12 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 00ca144fd..9003a5e00 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1195,6 +1195,12 @@ result = _(1).gte(2); result = _([]).gte(2); result = _({}).gte(2); +// _.isArguments +result = _.isArguments(any); +result = _(1).isArguments(); +result = _([]).isArguments(); +result = _({}).isArguments(); + // _.isArray result = _.isArray(any); result = _(1).isArray(); @@ -1437,8 +1443,6 @@ interface FirstSecond { } result = _.invert({ 'first': 'moe', 'second': 'larry' }); -(function (...args: any[]) { return _.isArguments(arguments); })(1, 2, 3); - result = _.isBoolean(null); result = _.isDate(new Date()); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 77daeca2a..62b5c0f89 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -6162,6 +6162,23 @@ declare module _ { gte(other: any): boolean; } + //_.isArguments + interface LoDashStatic { + /** + * Checks if value is classified as an arguments object. + * @param value The value to check. + * @return Returns true if value is correctly classified, else false. + */ + isArguments(value?: any): boolean; + } + + interface LoDashWrapperBase { + /** + * @see _.isArguments + */ + isArguments(): boolean; + } + //_.isArray interface LoDashStatic { /** @@ -6959,16 +6976,6 @@ declare module _ { invert(object: any): any; } - //_.isArguments - interface LoDashStatic { - /** - * Checks if value is an arguments object. - * @param value The value to check. - * @return True if the value is an arguments object, else false. - **/ - isArguments(value?: any): boolean; - } - //_.isBoolean interface LoDashStatic { /** From ac5487ad224705c215855ffd0fd322ba8c52d7f9 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Mon, 24 Aug 2015 00:33:26 +0500 Subject: [PATCH 196/345] lodash: changed _.isError() method --- lodash/lodash-tests.ts | 6 ++++++ lodash/lodash.d.ts | 29 ++++++++++++++++++----------- 2 files changed, 24 insertions(+), 11 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 00ca144fd..80f6f72ae 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1209,6 +1209,12 @@ result = _([1, 2, 3]).isEmpty(); result = _({}).isEmpty(); result = _('').isEmpty(); +// _.isError +result = _.isError(any); +result = _(1).isError(); +result = _([]).isError(); +result = _({}).isError(); + // _.isFinite result = _.isFinite(any); result = _(1).isFinite(); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 77daeca2a..cbd802e78 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -6197,6 +6197,24 @@ declare module _ { isEmpty(): boolean; } + //_.isError + interface LoDashStatic { + /** + * Checks if value is an Error, EvalError, RangeError, ReferenceError, SyntaxError, TypeError, or URIError + * object. + * @param value The value to check. + * @return Returns true if value is an error object, else false. + */ + isError(value: any): boolean; + } + + interface LoDashWrapperBase { + /** + * @see _.isError + */ + isError(): boolean; + } + //_.isFinite interface LoDashStatic { /** @@ -6999,17 +7017,6 @@ declare module _ { isElement(value?: any): boolean; } - //_.isError - interface LoDashStatic { - /** - * Checks if value is an Error, EvalError, RangeError, ReferenceError, SyntaxError, TypeError, - * or URIError object. - * @param value The value to check. - * @return True if value is an error object, else false. - */ - isError(value: any): boolean; - } - //_.isEqual interface EqCustomizer { (value: any, other: any, indexOrKey?: number|string): boolean; From e47ef31f9b1e46596a50ff5342d58f2fcf3203a0 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Mon, 24 Aug 2015 00:37:36 +0500 Subject: [PATCH 197/345] lodash: changed _.isFunction() method --- lodash/lodash-tests.ts | 8 ++++++-- lodash/lodash.d.ts | 27 +++++++++++++++++---------- 2 files changed, 23 insertions(+), 12 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 00ca144fd..544529d01 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1215,6 +1215,12 @@ result = _(1).isFinite(); result = _([]).isFinite(); result = _({}).isFinite(); +// _.isFunction +result = _.isFunction(any); +result = _(1).isFunction(); +result = _([]).isFunction(); +result = _({}).isFunction(); + // _.isMatch var testIsMatchCustiomizerFn: (value: any, other: any, indexOrKey: number|string) => boolean; result = _.isMatch({}, {}); @@ -1470,8 +1476,6 @@ result = _(testEqArray).isEqual(testEqOtherArray, testEqCustomizerFn); result = _.eq(testEqArray, testEqOtherArray, testEqCustomizerFn); result = _(testEqArray).eq(testEqOtherArray, testEqCustomizerFn); -result = _.isFunction(_); - result = _.isNull(null); result = _.isNull(undefined); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 77daeca2a..d5b6707f8 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -6215,6 +6215,23 @@ declare module _ { isFinite(): boolean; } + //_.isFunction + interface LoDashStatic { + /** + * Checks if value is classified as a Function object. + * @param value The value to check. + * @return Returns true if value is correctly classified, else false. + **/ + isFunction(value?: any): boolean; + } + + interface LoDashWrapperBase { + /** + * @see _.isFunction + */ + isFunction(): boolean; + } + //_.isMatch interface isMatchCustomizer { (value: any, other: any, indexOrKey?: number|string): boolean; @@ -7090,16 +7107,6 @@ declare module _ { thisArg?: any): boolean; } - //_.isFunction - interface LoDashStatic { - /** - * Checks if value is a function. - * @param value The value to check. - * @return True if the value is a function, else false. - **/ - isFunction(value?: any): boolean; - } - //_.isNull interface LoDashStatic { /** From 1c48442b68e06a817c8c9a2f8131bc91759970eb Mon Sep 17 00:00:00 2001 From: lp Date: Sat, 8 Aug 2015 00:08:41 +0100 Subject: [PATCH 198/345] Fixed param for dynatree and added tests Made includeRoot optional changed flag param from string -> boolean Added test file --- jquery.dynatree/jquery.dynatree-tests.ts | 15 +++++++++++++++ jquery.dynatree/jquery.dynatree.d.ts | 10 +++++----- 2 files changed, 20 insertions(+), 5 deletions(-) create mode 100644 jquery.dynatree/jquery.dynatree-tests.ts diff --git a/jquery.dynatree/jquery.dynatree-tests.ts b/jquery.dynatree/jquery.dynatree-tests.ts new file mode 100644 index 000000000..df1a17f10 --- /dev/null +++ b/jquery.dynatree/jquery.dynatree-tests.ts @@ -0,0 +1,15 @@ +/// + +var dynatree = $('element').dynatree(); + +dynatree.visit((node)=>{ + return false; +}); + +dynatree.visit((node)=>{ + return false; +}, true); + +var node = dynatree.getActiveNode(); + +node.select(true); \ No newline at end of file diff --git a/jquery.dynatree/jquery.dynatree.d.ts b/jquery.dynatree/jquery.dynatree.d.ts index c2dc0f928..e8604d2a0 100644 --- a/jquery.dynatree/jquery.dynatree.d.ts +++ b/jquery.dynatree/jquery.dynatree.d.ts @@ -41,7 +41,7 @@ interface DynaTree { selectKey(key: string, flag: string): DynaTreeNode; serializeArray(stopOnParents: boolean): any[]; toDict(includeRoot?: boolean): any; - visit(fn: (node: DynaTreeNode) =>boolean, includeRoot: boolean): void; + visit(fn: (node: DynaTreeNode) =>boolean, includeRoot?: boolean): void; } @@ -54,7 +54,7 @@ interface DynaTreeNode { appendAjax(ajaxOptions: JQueryAjaxSettings): void; countChildren(): number; deactivate(): void; - expand(flag: string): void; + expand(flag: boolean): void; focus(): void; getChildren(): DynaTreeNode[]; getEventTargetType(event: Event): string; @@ -83,11 +83,11 @@ interface DynaTreeNode { removeChildren(): void; render(useEffects: boolean, includeInvisible: boolean): void; resetLazy(): void; - scheduleAction(mode: string, ms: number); - select(flag: string): void; + scheduleAction(mode: string, ms: number): void; + select(flag: boolean): void; setLazyNodeStatus(status: number): void; setTitle(title: string): void; - sortChildren(cmp?: (a: DynaTreeNode, b: DynaTreeNode) =>number, deep?: boolean); + sortChildren(cmp?: (a: DynaTreeNode, b: DynaTreeNode) =>number, deep?: boolean): void; toDict(recursive: boolean, callback?: (node: any) =>any): any; toggleExpand(): void; toggleSelect(): void; From 637aaf1d9aeac46386a20f7f75256cd967552111 Mon Sep 17 00:00:00 2001 From: fpellet Date: Mon, 24 Aug 2015 00:43:23 +0200 Subject: [PATCH 199/345] Add jquery.ajaxfile definition --- jquery.ajaxfile/jquery.ajaxFile-tests.ts | 54 ++++++++++ jquery.ajaxfile/jquery.ajaxFile.d.ts | 119 +++++++++++++++++++++++ 2 files changed, 173 insertions(+) create mode 100644 jquery.ajaxfile/jquery.ajaxFile-tests.ts create mode 100644 jquery.ajaxfile/jquery.ajaxFile.d.ts diff --git a/jquery.ajaxfile/jquery.ajaxFile-tests.ts b/jquery.ajaxfile/jquery.ajaxFile-tests.ts new file mode 100644 index 000000000..4a98706a4 --- /dev/null +++ b/jquery.ajaxfile/jquery.ajaxFile-tests.ts @@ -0,0 +1,54 @@ +/// +/// +/// + +function testRawApi(){ + var inputElement:HTMLInputElement = null; + var resultPromise = AjaxFile.send({ + method: 'POST', + url: '/', + desiredResponseDataType: JQueryAjaxFile.DataType.Json, + files: [ + { name: 'joeFile', element: inputElement } + ], + data: { + name: 'joe' + }, + timeoutInSeconds: 30 + }) + .then(result => console.log('Result: ' + result.data), result => console.log('Error: ' + result.error)) + .done(result => console.log('Result: ' + result.data)) + .fail(result => console.log('Error: ' + result.error + " " + result.status.code + " " + result.status.text + " " + result.status.isSuccess)) + .always(result => console.log('end')) + .abord(); +} + +function testJQuery() { + var inputElement: HTMLInputElement = null; + var extension: JQueryAjaxFile.IAjaxFileJQueryExtension = $.fn.ajaxWithFile; + var option: JQueryAjaxFile.IJQueryOption = { + type: 'POST', + url: '/', + dataType: "json", + files: [ + { name: 'joeFile', element: inputElement } + ], + data: { + name: 'joe' + }, + success(result) { console.log('Result: ' + result); }, + error(jqXhr, textStatus, errorThrown) { console.log('Error: ' + errorThrown); }, + complete(jqXhr, textStatus) { console.log('end'); }, + global: true, + timeout: 60 + }; + extension.ajaxWithFile(option); +} + +function testKnockoutExtension(){ + var fileHandler:KnockoutBindingHandler = ko.bindingHandlers.file; +} + +testKnockoutExtension(); +testJQuery(); +testRawApi(); \ No newline at end of file diff --git a/jquery.ajaxfile/jquery.ajaxFile.d.ts b/jquery.ajaxfile/jquery.ajaxFile.d.ts new file mode 100644 index 000000000..459287a27 --- /dev/null +++ b/jquery.ajaxfile/jquery.ajaxFile.d.ts @@ -0,0 +1,119 @@ +// Type definitions for jquery.ajaxfile v0.1.0 +// Project: https://github.com/fpellet/jquery.ajaxFile +// Definitions by: Florent PELLET +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare namespace JQueryAjaxFile { + export enum DataType { + Json, + Xml, + Text + } + + interface IFileData { + name: string; + element: HTMLInputElement; + } + + interface IOption { + method?: string; + url?: string; + + data?: any; + files?: IFileData[]; + desiredResponseDataType?: DataType; + + timeoutInSeconds?: number; + } + + interface IResponseStatus { + code: number; + text: string; + isSuccess: boolean; + } + + interface IAjaxFileResult { + error?: any; + data?: any; + status?: IResponseStatus; + } + + interface IAjaxFileResultCallback { + (result: IAjaxFileResult): void; + } + + interface IAjaxFilePromise { + then(success: IAjaxFileResultCallback, error?: IAjaxFileResultCallback): IAjaxFilePromise; + done(success: IAjaxFileResultCallback): IAjaxFilePromise; + fail(error: IAjaxFileResultCallback): IAjaxFilePromise; + always(error: IAjaxFileResultCallback): IAjaxFilePromise; + + abord(): void; + } + + interface IAjaxFileStatic { + send(option: IOption): IAjaxFilePromise; + } + + interface IJQueryXHR { + readyState: any; + status: number; + statusText: string; + responseXML: Document; + responseText: string; + statusCode?: { [key: string]: any; }; + + abort(statusText?: string): void; + + setRequestHeader(header: string, value: string): void; + getAllResponseHeaders(): string; + getResponseHeader(header: string): string; + + beforeSend?(jqXHR: IJQueryXHR, settings: JQueryAjaxSettings): any; + dataFilter?(data: any, ty: any): any; + success?(data: any, textStatus: string, jqXHR: IJQueryXHR): any; + error?(jqXHR: IJQueryXHR, textStatus: string, errorThrown: string): any; + complete?(jqXHR: IJQueryXHR, textStatus: string): any; + } + + interface IJQueryOption { + type?: string; + url?: string; + + data?: any; + files?: IFileData[]; + dataType?: string; + + timeout?: number; + + global?: boolean; + + error?(jqXHR: IJQueryXHR, textStatus: string, errorThrown: string): any; + success?(data: any, textStatus: string, jqXHR: IJQueryXHR): any; + complete?(jqXHR: IJQueryXHR, textStatus: string): any; + } + + interface IAjaxFileJQueryExtension { + ajaxWithFile(jqueryOption: IJQueryOption): JQueryDeferred; + } +} + +declare var AjaxFile: JQueryAjaxFile.IAjaxFileStatic; + +declare module 'ajaxfile' { + export = AjaxFile; +} + +declare namespace AjaxFileKnockout { + interface IFileInputWrapper { + getElement(): HTMLInputElement; + fileSelected(): boolean; + } +} + +interface KnockoutBindingHandlers { + file: KnockoutBindingHandler; +} From fe2856e93dc82f65de501e061a63f792f09b9e0f Mon Sep 17 00:00:00 2001 From: xyb Date: Sun, 23 Aug 2015 15:38:12 -0700 Subject: [PATCH 200/345] Definitions for expression-less --- express-less/express-less-tests.ts | 12 ++++++++++++ express-less/express-less.d.ts | 21 +++++++++++++++++++++ 2 files changed, 33 insertions(+) create mode 100644 express-less/express-less-tests.ts create mode 100644 express-less/express-less.d.ts diff --git a/express-less/express-less-tests.ts b/express-less/express-less-tests.ts new file mode 100644 index 000000000..3fee687f2 --- /dev/null +++ b/express-less/express-less-tests.ts @@ -0,0 +1,12 @@ +/// + +import express = require('express'); +import expressLess = require('express-less'); + +var app = express(); +var lessOptions: expressLess.Options = {}; +lessOptions.compress = true; +lessOptions.debug = true; + +app.use('/less-css', expressLess(__dirname)); +app.use('/less-css-with-options', expressLess(__dirname + "/less", lessOptions)); diff --git a/express-less/express-less.d.ts b/express-less/express-less.d.ts new file mode 100644 index 000000000..b3c7008cd --- /dev/null +++ b/express-less/express-less.d.ts @@ -0,0 +1,21 @@ +// Type definitions for express-less +// Project: https://www.npmjs.com/package/express-less +// Definitions by: xyb +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "express-less" { + import express = require('express'); + + function less(root: string, options?: less.Options): express.RequestHandler; + + module less { + export interface Options { + debug?: boolean; + compress?: boolean; + } + } + + export = less; +} From 375b76186f0e0f04448c597ce448f8973656b60d Mon Sep 17 00:00:00 2001 From: Joe Herman Date: Sun, 23 Aug 2015 21:11:17 -0400 Subject: [PATCH 201/345] async: Corrected and updated to 1.4.2 --- async/async-tests.ts | 137 +++++++++++++++++--- async/async.d.ts | 291 ++++++++++++++++++++++++------------------- 2 files changed, 283 insertions(+), 145 deletions(-) diff --git a/async/async-tests.ts b/async/async-tests.ts index 4fddea875..a6dff0af8 100644 --- a/async/async-tests.ts +++ b/async/async-tests.ts @@ -5,8 +5,19 @@ var fs, path; function callback() {} async.map(['file1', 'file2', 'file3'], fs.stat, function (err, results) { }); +async.mapSeries(['file1', 'file2', 'file3'], fs.stat, function (err, results) { }); +async.mapLimit(['file1', 'file2', 'file3'], 2, fs.stat, function (err, results) { }); async.filter(['file1', 'file2', 'file3'], path.exists, function (results) { }); +async.filterSeries(['file1', 'file2', 'file3'], path.exists, function (results) { }); +async.filterLimit(['file1', 'file2', 'file3'], 2, path.exists, function (results) { }); +async.select(['file1', 'file2', 'file3'], path.exists, function (results) { }); +async.selectSeries(['file1', 'file2', 'file3'], path.exists, function (results) { }); +async.selectLimit(['file1', 'file2', 'file3'], 2, path.exists, function (results) { }); + +async.reject(['file1', 'file2', 'file3'], path.exists, function (results) { }); +async.rejectSeries(['file1', 'file2', 'file3'], path.exists, function (results) { }); +async.rejectLimit(['file1', 'file2', 'file3'], 2, path.exists, function (results) { }); async.parallel([ function () { }, @@ -25,6 +36,11 @@ async.map(data, asyncProcess, function (err, results) { }); var openFiles = ['file1', 'file2']; +var openFilesObj = { + file1: "fileOne", + file2: "fileTwo" +} + var saveFile = function () { } async.each(openFiles, saveFile, function (err) { }); async.eachSeries(openFiles, saveFile, function (err) { }); @@ -32,18 +48,34 @@ async.eachSeries(openFiles, saveFile, function (err) { }); var documents, requestApi; async.eachLimit(documents, 20, requestApi, function (err) { }); -async.map(['file1', 'file2', 'file3'], fs.stat, function (err, results) { }); - -async.filter(['file1', 'file2', 'file3'], path.exists, function (results) { }); +// forEachOf* functions. May accept array or object. +function forEachOfIterator(item, key, forEachOfIteratorCallback) { + console.log("ForEach: item=" + item + ", key=" + key); + forEachOfIteratorCallback(); +} +async.forEachOf(openFiles, forEachOfIterator, function (err) { }); +async.forEachOf(openFilesObj, forEachOfIterator, function (err) { }); +async.forEachOfSeries(openFiles, forEachOfIterator, function (err) { }); +async.forEachOfSeries(openFilesObj, forEachOfIterator, function (err) { }); +async.forEachOfLimit(openFiles, 2, forEachOfIterator, function (err) { }); +async.forEachOfLimit(openFilesObj, 2, forEachOfIterator, function (err) { }); var process; -async.reduce([1, 2, 3], 0, function (memo, item, callback) { +var numArray = [1, 2, 3]; +function reducer(memo, item, callback) { process.nextTick(function () { callback(null, memo + item) }); -}, function (err, result) { }); +} +async.reduce(numArray, 0, reducer, function (err, result) { }); +async.inject(numArray, 0, reducer, function (err, result) { }); +async.foldl(numArray, 0, reducer, function (err, result) { }); +async.reduceRight(numArray, 0, reducer, function (err, result) { }); +async.foldr(numArray, 0, reducer, function (err, result) { }); async.detect(['file1', 'file2', 'file3'], path.exists, function (result) { }); +async.detectSeries(['file1', 'file2', 'file3'], path.exists, function (result) { }); +async.detectLimit(['file1', 'file2', 'file3'], 2, path.exists, function (result) { }); async.sortBy(['file1', 'file2', 'file3'], function (file, callback) { fs.stat(file, function (err, stats) { @@ -52,10 +84,18 @@ async.sortBy(['file1', 'file2', 'file3'], function (file, callback) { }, function (err, results) { }); async.some(['file1', 'file2', 'file3'], path.exists, function (result) { }); +async.someLimit(['file1', 'file2', 'file3'], 2, path.exists, function (result) { }); +async.any(['file1', 'file2', 'file3'], path.exists, function (result) { }); async.every(['file1', 'file2', 'file3'], path.exists, function (result) { }); +async.everyLimit(['file1', 'file2', 'file3'], 2, path.exists, function (result) { }); +async.all(['file1', 'file2', 'file3'], path.exists, function (result) { }); async.concat(['dir1', 'dir2', 'dir3'], fs.readdir, function (err, files) { }); +async.concatSeries(['dir1', 'dir2', 'dir3'], fs.readdir, function (err, files) { }); + + +// Control Flow // async.series([ function (callback) { @@ -77,7 +117,6 @@ async.series([ ], function (err, results) { }); - async.series({ one: function (callback) { setTimeout(function () { @@ -173,21 +212,47 @@ async.parallel({ }, 100); }, }, -function (err, results) { }); + function (err, results) { }); - -var count = 0; - -async.whilst( - function () { return count < 5; }, - function (callback) { - count++; - setTimeout(callback, 1000); +async.parallelLimit({ + one: function (callback) { + setTimeout(function () { + callback(null, 1); + }, 200); }, - function (err) { } + two: function (callback) { + setTimeout(function () { + callback(null, 2); + }, 100); + }, +}, + 2, + function (err, results) { } ); +function whileFn(callback) { + count++; + setTimeout(callback, 1000); +} + +function whileTest() { return count < 5; } +var count = 0; +async.whilst(whileTest, whileFn, function (err) { }); +async.until(whileTest, whileFn, function (err) { }); +async.doWhilst(whileFn, whileTest, function (err) { }); +async.doUntil(whileFn, whileTest, function (err) { }); + +async.during(function (testCallback) { testCallback(new Error(), false); }, function (callback) { callback() }, function (error) { console.log(error) }); +async.doDuring(function (callback) { callback() }, function (testCallback) { testCallback(new Error(), false); }, function (error) { console.log(error) }); +async.forever(function (errBack) { + errBack(new Error("Not going on forever.")); +}, + function (error) { + console.log(error); + } +); + async.waterfall([ function (callback) { callback(null, 'one', 'two'); @@ -279,6 +344,26 @@ q2.unshift(['task3', 'task4', 'task5'], function (error) { console.log('Finished tasks'); }); +// create a cargo object with payload 2 +var cargo = async.cargo(function (tasks, callback) { + for (var i = 0; i < tasks.length; i++) { + console.log('hello ' + tasks[i].name); + } + callback(); +}, 2); + + +// add some items +cargo.push({ name: 'foo' }, function (err) { + console.log('finished processing foo'); +}); +cargo.push({ name: 'bar' }, function (err) { + console.log('finished processing bar'); +}); +cargo.push({ name: 'baz' }, function (err) { + console.log('finished processing baz'); +}); + var filename = ''; async.auto({ get_data: function (callback) { }, @@ -291,6 +376,9 @@ async.auto({ email_link: ['write_file', function (callback, results) { }] }); +async.retry(3, function (callback, results) { }, function (err, result) { }); +async.retry({ times: 3, interval: 200 }, function (callback, results) { }, function (err, result) { }); + async.parallel([ function (callback) { }, @@ -336,3 +424,20 @@ var slow_fn = function (name, callback) { }; var fn = async.memoize(slow_fn); fn('some name', function () {}); +async.unmemoize(fn); +async.ensureAsync(function () { }); +async.constant(42); +async.asyncify(function () { }); + +async.log(function (name, callback) { + setTimeout(function () { + callback(null, 'hello ' + name); + }, 0); +}, "world" + ); + +async.dir(function (name, callback) { + setTimeout(function () { + callback(null, { hello: name }); + }, 1000); +}, "world"); diff --git a/async/async.d.ts b/async/async.d.ts index 56370c15d..b90876915 100644 --- a/async/async.d.ts +++ b/async/async.d.ts @@ -1,132 +1,165 @@ -// Type definitions for Async 0.9.2 -// Project: https://github.com/caolan/async +// Type definitions for Async 1.4.2 +// Project: https://github.com/caolan/async // Definitions by: Boris Yankov , Arseniy Maximov -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -interface Dictionary { [key: string]: T; } - -// Common interface between Arrays and Array-like objects -interface List { - [index: number]: T; - length: number; +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface Dictionary { [key: string]: T; } + +interface ErrorCallback { (err?: Error): void; } +interface AsyncResultCallback { (err: Error, result: T): void; } +interface AsyncResultArrayCallback { (err: Error, results: T[]): void; } +interface AsyncResultObjectCallback { (err: Error, results: Dictionary): void; } + +interface AsyncFunction { (callback: (err: Error, result?: T) => void): void; } +interface AsyncIterator { (item: T, callback: ErrorCallback): void; } +interface AsyncForEachOfIterator { (item: T, key: number, callback: ErrorCallback): void; } +interface AsyncResultIterator { (item: T, callback: AsyncResultCallback): void; } +interface AsyncMemoIterator { (memo: R, item: T, callback: AsyncResultCallback): void; } +interface AsyncBooleanIterator { (item: T, callback: (truthValue: boolean) => void): void; } + +interface AsyncWorker { (task: T, callback: ErrorCallback): void; } +interface AsyncVoidFunction { (callback: ErrorCallback): void; } + +interface AsyncQueue { + length(): number; + started: boolean; + running(): number; + idle(): boolean; + concurrency: number; + push(task: T, callback?: ErrorCallback): void; + push(task: T[], callback?: ErrorCallback): void; + unshift(task: T, callback?: ErrorCallback): void; + unshift(task: T[], callback?: ErrorCallback): void; + saturated: () => any; + empty: () => any; + drain: () => any; + paused: boolean; + pause(): void + resume(): void; + kill(): void; } -interface ErrorCallback { (err?: Error): void; } -interface AsyncResultCallback { (err: Error, result: T): void; } -interface AsyncResultArrayCallback { (err: Error, results: T[]): void; } -interface AsyncResultObjectCallback { (err: Error, results: Dictionary): void; } - -interface AsyncIterator { (item: T, callback: ErrorCallback): void; } -interface AsyncForEachOfIterator { (item: T, index: number, callback: ErrorCallback): void; } -interface AsyncResultIterator { (item: T, callback: AsyncResultCallback): void; } -interface AsyncMemoIterator { (memo: R, item: T, callback: AsyncResultCallback): void; } - -interface AsyncWorker { (task: T, callback: ErrorCallback): void; } - -interface AsyncFunction { (callback: AsyncResultCallback): void; } -interface AsyncVoidFunction { (callback: ErrorCallback): void; } - -interface AsyncQueue { - length(): number; - concurrency: number; - started: boolean; - paused: boolean; - push(task: T, callback?: ErrorCallback): void; - push(task: T[], callback?: ErrorCallback): void; - unshift(task: T, callback?: ErrorCallback): void; - unshift(task: T[], callback?: ErrorCallback): void; - saturated: () => any; - empty: () => any; - drain: () => any; - running(): number; - idle(): boolean; - pause(): void; - resume(): void; - kill(): void; -} - -interface AsyncPriorityQueue { - length(): number; - concurrency: number; - started: boolean; - paused: boolean; - push(task: T, priority: number, callback?: AsyncResultArrayCallback): void; - push(task: T[], priority: number, callback?: AsyncResultArrayCallback): void; - saturated: () => any; - empty: () => any; - drain: () => any; - running(): number; - idle(): boolean; - pause(): void; - resume(): void; - kill(): void; -} - -interface Async { - - // Collections - each(arr: T[], iterator: AsyncIterator, callback: ErrorCallback): void; - eachSeries(arr: T[], iterator: AsyncIterator, callback: ErrorCallback): void; - eachLimit(arr: T[], limit: number, iterator: AsyncIterator, callback: ErrorCallback): void; - forEachOf(obj: List, iterator: AsyncForEachOfIterator, callback: ErrorCallback): void; - forEachOfSeries(obj: List, iterator: AsyncForEachOfIterator, callback: ErrorCallback): void; - forEachOfLimit(obj: List, limit: number, iterator: AsyncForEachOfIterator, callback: ErrorCallback): void; - map(arr: T[], iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): any; - mapSeries(arr: T[], iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): any; - mapLimit(arr: T[], limit: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): any; - filter(arr: T[], iterator: AsyncResultIterator, callback: (results: T[]) => any): any; - select(arr: T[], iterator: AsyncResultIterator, callback: (results: T[]) => any): any; - filterSeries(arr: T[], iterator: AsyncResultIterator, callback: (results: T[]) => any): any; - selectSeries(arr: T[], iterator: AsyncResultIterator, callback: (results: T[]) => any): any; - reject(arr: T[], iterator: AsyncResultIterator, callback: (results: T[]) => any): any; - rejectSeries(arr: T[], iterator: AsyncResultIterator, callback: (results: T[]) => any): any; - reduce(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncResultCallback): any; - inject(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncResultCallback): any; - foldl(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncResultCallback): any; - reduceRight(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncResultCallback): any; - foldr(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncResultCallback): any; - detect(arr: T[], iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): any; - detectSeries(arr: T[], iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): any; - sortBy(arr: T[], iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): any; - some(arr: T[], iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): any; - any(arr: T[], iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): any; - every(arr: T[], iterator: AsyncResultIterator, callback: (result: boolean) => any): any; - all(arr: T[], iterator: AsyncResultIterator, callback: (result: boolean) => any): any; - concat(arr: T[], iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): any; - concatSeries(arr: T[], iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): any; - - // Control Flow - series(tasks: Array>, callback?: AsyncResultArrayCallback): void; - series(tasks: Dictionary>, callback?: AsyncResultObjectCallback): void; - parallel(tasks: Array>, callback?: AsyncResultArrayCallback): void; - parallel(tasks: Dictionary>, callback?: AsyncResultObjectCallback): void; - parallelLimit(tasks: Array>, limit: number, callback?: AsyncResultArrayCallback): void; - parallelLimit(tasks: Dictionary>, limit: number, callback?: AsyncResultObjectCallback): void; - whilst(test: () => boolean, fn: AsyncVoidFunction, callback: (err: any) => void): void; - doWhilst(fn: AsyncVoidFunction, test: () => boolean, callback: (err: any) => void): void; - until(test: () => boolean, fn: AsyncVoidFunction, callback: (err: any) => void): void; - doUntil(fn: AsyncVoidFunction, test: () => boolean, callback: (err: any) => void): void; - waterfall(tasks: Function[], callback?: (err: any, ...arguments: any[]) => void): void; - queue(worker: AsyncWorker, concurrency: number): AsyncQueue; - priorityQueue(worker: AsyncWorker, concurrency: number): AsyncPriorityQueue; - auto(tasks: any, callback?: AsyncResultArrayCallback): void; - iterator(tasks: Function[]): Function; - apply(fn: Function, ...arguments: any[]): AsyncFunction; - nextTick(callback: Function): void; - - times (n: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; - timesSeries (n: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; - - // Utils - memoize(fn: Function, hasher?: Function): Function; - unmemoize(fn: Function): Function; - log(fn: Function, ...arguments: any[]): void; - dir(fn: Function, ...arguments: any[]): void; - noConflict(): Async; -} - -declare var async: Async; - -declare module "async" { - export = async; -} +interface AsyncPriorityQueue { + length(): number; + concurrency: number; + started: boolean; + paused: boolean; + push(task: T, priority: number, callback?: AsyncResultArrayCallback): void; + push(task: T[], priority: number, callback?: AsyncResultArrayCallback): void; + saturated: () => any; + empty: () => any; + drain: () => any; + running(): number; + idle(): boolean; + pause(): void; + resume(): void; + kill(): void; +} + +interface AsyncCargo { + length(): number; + payload: number; + push(task: any, callback? : Function): void; + push(task: any[], callback? : Function): void; + saturated(): void; + empty(): void; + drain(): void; + idle(): boolean; + pause(): void; + resume(): void; + kill(): void; +} + +interface Async { + + // Collections + each(arr: T[], iterator: AsyncIterator, callback?: ErrorCallback): void; + eachSeries(arr: T[], iterator: AsyncIterator, callback?: ErrorCallback): void; + eachLimit(arr: T[], limit: number, iterator: AsyncIterator, callback?: ErrorCallback): void; + forEachOf(obj: any, iterator: (item: any, key: [string|number], callback?: ErrorCallback) => void, callback: ErrorCallback): void; + forEachOf(obj: T[], iterator: AsyncForEachOfIterator, callback?: ErrorCallback): void; + forEachOfSeries(obj: any, iterator: (item: any, key: [string|number], callback?: ErrorCallback) => void, callback: ErrorCallback): void; + forEachOfSeries(obj: T[], iterator: AsyncForEachOfIterator, callback?: ErrorCallback): void; + forEachOfLimit(obj: any, limit: number, iterator: (item: any, key: [string|number], callback?: ErrorCallback) => void, callback: ErrorCallback): void; + forEachOfLimit(obj: T[], limit: number, iterator: AsyncForEachOfIterator, callback?: ErrorCallback): void; + map(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; + mapSeries(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; + mapLimit(arr: T[], limit: number, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; + filter(arr: T[], iterator: AsyncResultIterator, callback?: (results: T[]) => any): any; + select(arr: T[], iterator: AsyncResultIterator, callback?: (results: T[]) => any): any; + filterSeries(arr: T[], iterator: AsyncResultIterator, callback?: (results: T[]) => any): any; + selectSeries(arr: T[], iterator: AsyncResultIterator, callback?: (results: T[]) => any): any; + filterLimit(arr: T[], limit: number, iterator: AsyncResultIterator, callback?: (results: T[]) => any): any; + selectLimit(arr: T[], limit: number, iterator: AsyncResultIterator, callback?: (results: T[]) => any): any; + reject(arr: T[], iterator: AsyncResultIterator, callback?: (results: T[]) => any): any; + rejectSeries(arr: T[], iterator: AsyncResultIterator, callback?: (results: T[]) => any): any; + rejectLimit(arr: T[], limit: number, iterator: AsyncResultIterator, callback?: (results: T[]) => any): any; + reduce(arr: T[], memo: R, iterator: AsyncMemoIterator, callback?: AsyncResultCallback): any; + inject(arr: T[], memo: R, iterator: AsyncMemoIterator, callback?: AsyncResultCallback): any; + foldl(arr: T[], memo: R, iterator: AsyncMemoIterator, callback?: AsyncResultCallback): any; + reduceRight(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncResultCallback): any; + foldr(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncResultCallback): any; + detect(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: T) => void): any; + detectSeries(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: T) => void): any; + detectLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: (result: T) => void): any; + sortBy(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; + some(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: boolean) => void): any; + someLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: (result: boolean) => void): any; + any(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: boolean) => void): any; + every(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: boolean) => any): any; + everyLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: (result: boolean) => any): any; + all(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: boolean) => any): any; + concat(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; + concatSeries(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; + + // Control Flow + series(tasks: AsyncFunction[], callback?: AsyncResultArrayCallback): void; + series(tasks: Dictionary>, callback?: AsyncResultObjectCallback): void; + parallel(tasks: Array>, callback?: AsyncResultArrayCallback): void; + parallel(tasks: Dictionary>, callback?: AsyncResultObjectCallback): void; + parallelLimit(tasks: Array>, limit: number, callback?: AsyncResultArrayCallback): void; + parallelLimit(tasks: Dictionary>, limit: number, callback?: AsyncResultObjectCallback): void; + whilst(test: () => boolean, fn: AsyncVoidFunction, callback: (err: any) => void): void; + doWhilst(fn: AsyncVoidFunction, test: () => boolean, callback: (err: any) => void): void; + until(test: () => boolean, fn: AsyncVoidFunction, callback: (err: any) => void): void; + doUntil(fn: AsyncVoidFunction, test: () => boolean, callback: (err: any) => void): void; + during(test: (testCallback : (error: Error, truth: boolean) => void) => void, fn: AsyncVoidFunction, callback: (err: any) => void): void; + doDuring(fn: AsyncVoidFunction, test: (testCallback: (error: Error, truth: boolean) => void) => void, callback: (err: any) => void): void; + forever(next: (errCallback : (err: Error) => void) => void, errBack: (err: Error) => void) : void; + waterfall(tasks: Function[], callback?: (err: Error, result: any) => void): void; + compose(...fns: Function[]): void; + seq(...fns: Function[]): void; + applyEach(fns: Function[], argsAndCallback: any[]): void; // applyEach(fns, args..., callback). TS does not support ... for a middle argument. Callback is optional. + applyEachSeries(fns: Function[], argsAndCallback: any[]): void; // applyEachSeries(fns, args..., callback). TS does not support ... for a middle argument. Callback is optional. + queue(worker: AsyncWorker, concurrency?: number): AsyncQueue; + priorityQueue(worker: AsyncWorker, concurrency: number): AsyncPriorityQueue; + cargo(worker : (tasks: any[], callback : ErrorCallback) => void, payload? : number) : AsyncCargo; + auto(tasks: any, callback?: (error: Error, results: any) => void): void; + retry(opts: number, task: (callback : AsyncResultCallback, results: any) => void, callback: (error: Error, results: any) => void): void; + retry(opts: { times: number, interval: number }, task: (callback: AsyncResultCallback, results : any) => void, callback: (error: Error, results: any) => void): void; + iterator(tasks: Function[]): Function; + apply(fn: Function, ...arguments: any[]): AsyncFunction; + nextTick(callback: Function): void; + setImmediate(callback: Function): void; + + times (n: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; + timesSeries(n: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; + timesLimit(n: number, limit: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; + + // Utils + memoize(fn: Function, hasher?: Function): Function; + unmemoize(fn: Function): Function; + ensureAsync(fn: (... argsAndCallback: any[]) => void): Function; + constant(...values: any[]): Function; + asyncify(fn: Function): Function; + wrapSync(fn: Function): Function; + log(fn: Function, ...arguments: any[]): void; + dir(fn: Function, ...arguments: any[]): void; + noConflict(): Async; +} + +declare var async: Async; + +declare module "async" { + export = async; +} From 16cfba413649cdf1ce9bbea2223b8120e25c6b23 Mon Sep 17 00:00:00 2001 From: Yuichi Nukiyama Date: Mon, 24 Aug 2015 06:55:28 +0000 Subject: [PATCH 202/345] Modify Bootstrap.d.ts I change properties to more strictly typed. and add some missing properties. --- bootstrap/bootstrap.d.ts | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/bootstrap/bootstrap.d.ts b/bootstrap/bootstrap.d.ts index 47a992fba..71b38d0b0 100644 --- a/bootstrap/bootstrap.d.ts +++ b/bootstrap/bootstrap.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Bootstrap 2.2 +// Type definitions for Bootstrap 3.3.5 // Project: http://twitter.github.com/bootstrap/ // Definitions by: Boris Yankov // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -27,24 +27,28 @@ interface ScrollSpyOptions { interface TooltipOptions { animation?: boolean; html?: boolean; - placement?: any; + placement?: string | Function; selector?: string; - title?: any; + title?: string | Function; trigger?: string; - delay?: any; - container?: any; + template?: string; + delay?: number | Object; + container?: string | boolean; + viewport?: string | Function | Object; } interface PopoverOptions { animation?: boolean; html?: boolean; - placement?: any; + placement?: string | Function; selector?: string; trigger?: string; - title?: any; + title?: string | Function; + template?: string; content?: any; - delay?: any; - container?: any; + delay?: number | Object; + container?: string | boolean; + viewport?: string | Function | Object; } interface CollapseOptions { @@ -55,6 +59,8 @@ interface CollapseOptions { interface CarouselOptions { interval?: number; pause?: string; + wrap: boolean; + keybord: boolean; } interface TypeaheadOptions { @@ -68,7 +74,8 @@ interface TypeaheadOptions { } interface AffixOptions { - offset?: any; + offset?: number | Function | Object; + target?: any; } interface JQuery { From 88c35e2c751c2b1676abe267418ac5353f4124d2 Mon Sep 17 00:00:00 2001 From: Yuichi Nukiyama Date: Mon, 24 Aug 2015 07:22:31 +0000 Subject: [PATCH 203/345] UpdateBootstrap --- bootstrap/bootstrap.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bootstrap/bootstrap.d.ts b/bootstrap/bootstrap.d.ts index 71b38d0b0..3545eb310 100644 --- a/bootstrap/bootstrap.d.ts +++ b/bootstrap/bootstrap.d.ts @@ -59,8 +59,8 @@ interface CollapseOptions { interface CarouselOptions { interval?: number; pause?: string; - wrap: boolean; - keybord: boolean; + wrap?: boolean; + keybord?: boolean; } interface TypeaheadOptions { From 55465434fd031109b131dd43a578eebb1d8f15d6 Mon Sep 17 00:00:00 2001 From: Basarat Syed Date: Mon, 24 Aug 2015 17:43:21 +1000 Subject: [PATCH 204/345] reactChidlren callbacks accept index ref https://github.com/facebook/react/blob/10c816604336d4b3ec4c2a4e0ac42061a37dd8ee/src/isomorphic/children/ReactChildren.js#L52 --- react/react-addons.d.ts | 4 ++-- react/react-global.d.ts | 4 ++-- react/react.d.ts | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/react/react-addons.d.ts b/react/react-addons.d.ts index d9915e502..822f370b8 100644 --- a/react/react-addons.d.ts +++ b/react/react-addons.d.ts @@ -748,8 +748,8 @@ declare module "react/addons" { // ---------------------------------------------------------------------- interface ReactChildren { - map(children: ReactNode, fn: (child: ReactChild) => T): { [key:string]: T }; - forEach(children: ReactNode, fn: (child: ReactChild) => any): void; + map(children: ReactNode, fn: (child: ReactChild, index: number) => T): { [key:string]: T }; + forEach(children: ReactNode, fn: (child: ReactChild, index: number) => any): void; count(children: ReactNode): number; only(children: ReactNode): ReactChild; } diff --git a/react/react-global.d.ts b/react/react-global.d.ts index f8b376355..d33d4268d 100644 --- a/react/react-global.d.ts +++ b/react/react-global.d.ts @@ -755,8 +755,8 @@ declare module React { // ---------------------------------------------------------------------- interface ReactChildren { - map(children: ReactNode, fn: (child: ReactChild) => T): { [key:string]: T }; - forEach(children: ReactNode, fn: (child: ReactChild) => any): void; + map(children: ReactNode, fn: (child: ReactChild, index: number) => T): { [key:string]: T }; + forEach(children: ReactNode, fn: (child: ReactChild, index: number) => any): void; count(children: ReactNode): number; only(children: ReactNode): ReactChild; } diff --git a/react/react.d.ts b/react/react.d.ts index 218c6c94a..f2697fd25 100644 --- a/react/react.d.ts +++ b/react/react.d.ts @@ -755,8 +755,8 @@ declare module __React { // ---------------------------------------------------------------------- interface ReactChildren { - map(children: ReactNode, fn: (child: ReactChild) => T): { [key:string]: T }; - forEach(children: ReactNode, fn: (child: ReactChild) => any): void; + map(children: ReactNode, fn: (child: ReactChild, index: number) => T): { [key:string]: T }; + forEach(children: ReactNode, fn: (child: ReactChild, index: number) => any): void; count(children: ReactNode): number; only(children: ReactNode): ReactChild; } From 1dbfd8a1641614248d3415dd319537d35f8cc9f0 Mon Sep 17 00:00:00 2001 From: tkQubo Date: Mon, 24 Aug 2015 19:50:57 +0900 Subject: [PATCH 205/345] Add gulp-coffeeify --- gulp-coffeeify/gulp-coffeeify-tests.ts | 53 ++++++++++++++++++++++++++ gulp-coffeeify/gulp-coffeeify.d.ts | 42 ++++++++++++++++++++ 2 files changed, 95 insertions(+) create mode 100644 gulp-coffeeify/gulp-coffeeify-tests.ts create mode 100644 gulp-coffeeify/gulp-coffeeify.d.ts diff --git a/gulp-coffeeify/gulp-coffeeify-tests.ts b/gulp-coffeeify/gulp-coffeeify-tests.ts new file mode 100644 index 000000000..662428563 --- /dev/null +++ b/gulp-coffeeify/gulp-coffeeify-tests.ts @@ -0,0 +1,53 @@ +/// +/// + +import gulp = require('gulp'); +import coffeeify = require('gulp-coffeeify'); + +// Basic usage +gulp.task('scripts', function() { + gulp.src('src/coffee/**/*.coffee') + .pipe(coffeeify()) + .pipe(gulp.dest('./build/js')); +}); + +gulp.task('scripts', function() { + gulp.src('src/coffee/**/*.coffee') + .pipe(coffeeify({ + options: { + debug: true, // source map + paths: [__dirname + '/node_modules', __dirname + '/src/coffee'] + } + })) + .pipe(gulp.dest('./build/js')); +}); + +gulp.task('scripts', function() { + gulp.src('src/coffee/**/*.coffee') + .pipe(coffeeify({ + aliases: [ + { + cwd: 'src/coffee/app', + base: 'app' + } + ] + })) + .pipe(gulp.dest('./build/js')); +}); + +var xform = function(data: string){ + return 'module.exports = "' + data + '"'; +}; +gulp.task('scripts', function() { + gulp.src('src/coffee/**/*.coffee') + .pipe(coffeeify({ + transforms: [ + { + ext: '.extension', + transform: xform + } + ] + })) + .pipe(gulp.dest('./build/js')); +}); + diff --git a/gulp-coffeeify/gulp-coffeeify.d.ts b/gulp-coffeeify/gulp-coffeeify.d.ts new file mode 100644 index 000000000..e47f863ac --- /dev/null +++ b/gulp-coffeeify/gulp-coffeeify.d.ts @@ -0,0 +1,42 @@ +// Type definitions for gulp-coffeeify +// Project: gulp-coffeeify +// Definitions by: Qubo +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "gulp-coffeeify" { + namespace coffeeify { + interface Coffeeify { + (option?: Option): NodeJS.ReadWriteStream; + } + + interface Option { + options?: { + debug?: boolean; + paths?: string[]; + }, + /** + * [DEPRECATED]: You should use a 'paths' options of browserify. + */ + aliases?: Aliases; + /** + * [DEPRECATED] + */ + transforms?: Transforms; + } + + interface Aliases { + cwd?: string; + base?: string; + } + + interface Transforms { + ext?: string; + transform?(data: string): string; + } + } + + var coffeeify: coffeeify.Coffeeify; + + export = coffeeify; +} + From 94fda366f42b0dccf2703579ffff0e2b5e4a065a Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Mon, 24 Aug 2015 19:51:24 +0900 Subject: [PATCH 206/345] Assertions should return Thenable --- .../chai-as-promised-tests-with-bluebird.ts | 7 + .../chai-as-promised-tests-with-q.ts | 7 + chai-as-promised/chai-as-promised-tests.ts | 58 +++- chai-as-promised/chai-as-promised.d.ts | 283 +++++++++++++++++- 4 files changed, 326 insertions(+), 29 deletions(-) create mode 100644 chai-as-promised/chai-as-promised-tests-with-bluebird.ts create mode 100644 chai-as-promised/chai-as-promised-tests-with-q.ts diff --git a/chai-as-promised/chai-as-promised-tests-with-bluebird.ts b/chai-as-promised/chai-as-promised-tests-with-bluebird.ts new file mode 100644 index 000000000..e27205c41 --- /dev/null +++ b/chai-as-promised/chai-as-promised-tests-with-bluebird.ts @@ -0,0 +1,7 @@ +/// +/// + +// Compatibility check for Promise/A+ valid libraries +var thenableNum: Chai.Thenable; +import Bluebird = require('bluebird'); +thenableNum = Bluebird.resolve(1); diff --git a/chai-as-promised/chai-as-promised-tests-with-q.ts b/chai-as-promised/chai-as-promised-tests-with-q.ts new file mode 100644 index 000000000..91fe676cd --- /dev/null +++ b/chai-as-promised/chai-as-promised-tests-with-q.ts @@ -0,0 +1,7 @@ +/// +/// + +// Compatibility check for Promise/A+ valid libraries +var thenableNum: Chai.Thenable; +import Q = require('q'); +thenableNum = Q.resolve(1); diff --git a/chai-as-promised/chai-as-promised-tests.ts b/chai-as-promised/chai-as-promised-tests.ts index 95a433517..dd528e9f6 100644 --- a/chai-as-promised/chai-as-promised-tests.ts +++ b/chai-as-promised/chai-as-promised-tests.ts @@ -1,23 +1,53 @@ /// +/// import chai = require('chai'); import chaiAsPromised = require('chai-as-promised'); +import Q = require('q'); chai.use(chaiAsPromised); // ReSharper disable WrongExpressionStatement -var promise: any; -chai.expect(promise).to.eventually.equal(3); -chai.expect(promise).to.become(3); -chai.expect(promise).to.be.fulfilled; -chai.expect(promise).to.be.rejected; -chai.expect(promise).to.be.rejectedWith(Error); -chai.expect(promise).to.notify(() => console.log('done')); +// BDD API (expect) +var thenableNum: Chai.Thenable; +thenableNum = chai.expect(thenableNum).to.eventually.equal(3); +thenableNum = chai.expect(thenableNum).to.eventually.have.property('foo'); +thenableNum = chai.expect(thenableNum).to.become(3); +thenableNum = chai.expect(thenableNum).to.be.fulfilled; +thenableNum = chai.expect(thenableNum).to.be.rejected; +thenableNum = chai.expect(thenableNum).to.be.rejectedWith(Error); +thenableNum = chai.expect(thenableNum).to.notify(() => console.log('done')); -chai.assert.eventually.equal(promise, 4, 'Message'); -chai.assert.isFulfilled(promise, "optional message"); -chai.assert.becomes(promise, "foo", "optional message"); -chai.assert.doesNotBecome(promise, "foo", "optional message"); -chai.assert.isRejected(promise, "optional message"); -chai.assert.isRejected(promise, Error, "optional message"); -chai.assert.isRejected(promise, /error message matcher/, "optional message"); +// BDD API (should) +thenableNum = thenableNum.should.be.fulfilled; +thenableNum = thenableNum.should.eventually.deep.equal(3); +thenableNum = thenableNum.should.become(3); +thenableNum = thenableNum.should.be.rejected; +thenableNum = thenableNum.should.be.rejectedWith(Error); +thenableNum = thenableNum.should.eventually.equal(3).notify(() => console.log('done')); +thenableNum = thenableNum.should.be.fulfilled.and.notify(() => console.log('done')); + +// Complex examples on https://github.com/domenic/chai-as-promised#working-with-non-promisefriendly-test-runners +thenableNum.should.be.fulfilled.then(function () { + thenableNum.should.equal("after"); +}).should.notify(() => console.log('done')); + +Q.all([ + thenableNum.should.become("happy"), + thenableNum.should.eventually.have.property("fun times"), + thenableNum.should.be.rejectedWith(TypeError, "only joyful types are allowed") +]).should.notify(() => console.log('done')); + +// Assert API +var thenableVoid: Chai.Thenable; +thenableVoid = chai.assert.eventually.equal(thenableNum, 4, 'Message'); +thenableVoid = chai.assert.isFulfilled(thenableNum, "optional message"); +thenableVoid = chai.assert.becomes(thenableNum, "foo", "optional message"); +thenableVoid = chai.assert.doesNotBecome(thenableNum, "foo", "optional message"); +thenableVoid = chai.assert.isRejected(thenableNum, "optional message"); +thenableVoid = chai.assert.isRejected(thenableNum, Error, "optional message"); +thenableVoid = chai.assert.isRejected(thenableNum, /error message matcher/, "optional message"); + +// Check that original chai assertions are not broken +var undef: void; +undef = chai.assert.equal(10, 4, 'Message'); diff --git a/chai-as-promised/chai-as-promised.d.ts b/chai-as-promised/chai-as-promised.d.ts index 106bbf41e..5b68b0b5d 100644 --- a/chai-as-promised/chai-as-promised.d.ts +++ b/chai-as-promised/chai-as-promised.d.ts @@ -12,25 +12,278 @@ declare module 'chai-as-promised' { declare module Chai { - interface Assertion { - become(expected: any): Assertion; - fulfilled: Assertion; - rejected: Assertion; - rejectedWith(expected: any): Assertion; - notify(fn: Function): Assertion; + // chai-as-promised can take Promise/A+ valid promises. + interface Thenable { + then(onFulfilled?: (value: R) => U | Thenable, onRejected?: (error: any) => U | Thenable): Thenable; + then(onFulfilled?: (value: R) => U | Thenable, onRejected?: (error: any) => void): Thenable; } - interface LanguageChains { - eventually: Assertion; + // For BDD API + interface Assertion extends LanguageChains, NumericComparison, TypeComparison { + eventually: PromisedAssertion; + become(expected: any): PromisedAssertion; + fulfilled: PromisedAssertion; + rejected: PromisedAssertion; + rejectedWith(expected: any, message?: string): PromisedAssertion; + notify(fn: Function): PromisedAssertion; } + // Eventually does not have .then(), but PromisedAssertion have. + interface Eventually extends PromisedLanguageChains, PromisedNumericComparison, PromisedTypeComparison { + // From chai-as-promised + become(expected: Thenable): PromisedAssertion; + fulfilled: PromisedAssertion; + rejected: PromisedAssertion; + rejectedWith(expected: any): PromisedAssertion; + notify(fn: Function): PromisedAssertion; + + // From chai + not: PromisedAssertion; + deep: PromisedDeep; + a: PromisedTypeComparison; + an: PromisedTypeComparison; + include: PromisedInclude; + contain: PromisedInclude; + ok: PromisedAssertion; + true: PromisedAssertion; + false: PromisedAssertion; + null: PromisedAssertion; + undefined: PromisedAssertion; + exist: PromisedAssertion; + empty: PromisedAssertion; + arguments: PromisedAssertion; + Arguments: PromisedAssertion; + equal: PromisedEqual; + equals: PromisedEqual; + eq: PromisedEqual; + eql: PromisedEqual; + eqls: PromisedEqual; + property: PromisedProperty; + ownProperty: PromisedOwnProperty; + haveOwnProperty: PromisedOwnProperty; + length: PromisedLength; + lengthOf: PromisedLength; + match(regexp: RegExp|string, message?: string): PromisedAssertion; + string(string: string, message?: string): PromisedAssertion; + keys: PromisedKeys; + key(string: string): PromisedAssertion; + throw: PromisedThrow; + throws: PromisedThrow; + Throw: PromisedThrow; + respondTo(method: string, message?: string): PromisedAssertion; + itself: PromisedAssertion; + satisfy(matcher: Function, message?: string): PromisedAssertion; + closeTo(expected: number, delta: number, message?: string): PromisedAssertion; + members: PromisedMembers; + } + + interface PromisedAssertion extends Eventually, Thenable { + } + + interface PromisedLanguageChains { + eventually: Eventually; + + // From chai + to: PromisedAssertion; + be: PromisedAssertion; + been: PromisedAssertion; + is: PromisedAssertion; + that: PromisedAssertion; + which: PromisedAssertion; + and: PromisedAssertion; + has: PromisedAssertion; + have: PromisedAssertion; + with: PromisedAssertion; + at: PromisedAssertion; + of: PromisedAssertion; + same: PromisedAssertion; + } + + interface PromisedNumericComparison { + above: PromisedNumberComparer; + gt: PromisedNumberComparer; + greaterThan: PromisedNumberComparer; + least: PromisedNumberComparer; + gte: PromisedNumberComparer; + below: PromisedNumberComparer; + lt: PromisedNumberComparer; + lessThan: PromisedNumberComparer; + most: PromisedNumberComparer; + lte: PromisedNumberComparer; + within(start: number, finish: number, message?: string): PromisedAssertion; + } + + interface PromisedNumberComparer { + (value: number, message?: string): PromisedAssertion; + } + + interface PromisedTypeComparison { + (type: string, message?: string): PromisedAssertion; + instanceof: PromisedInstanceOf; + instanceOf: PromisedInstanceOf; + } + + interface PromisedInstanceOf { + (constructor: Object, message?: string): PromisedAssertion; + } + + interface PromisedDeep { + equal: PromisedEqual; + include: PromisedInclude; + property: PromisedProperty; + } + + interface PromisedEqual { + (value: any, message?: string): PromisedAssertion; + } + + interface PromisedProperty { + (name: string, value?: any, message?: string): PromisedAssertion; + } + + interface PromisedOwnProperty { + (name: string, message?: string): PromisedAssertion; + } + + interface PromisedLength extends PromisedLanguageChains, PromisedNumericComparison { + (length: number, message?: string): PromisedAssertion; + } + + interface PromisedInclude { + (value: Object, message?: string): PromisedAssertion; + (value: string, message?: string): PromisedAssertion; + (value: number, message?: string): PromisedAssertion; + keys: PromisedKeys; + members: PromisedMembers; + } + + interface PromisedKeys { + (...keys: string[]): PromisedAssertion; + (keys: any[]): PromisedAssertion; + } + + interface PromisedThrow { + (): PromisedAssertion; + (expected: string, message?: string): PromisedAssertion; + (expected: RegExp, message?: string): PromisedAssertion; + (constructor: Error, expected?: string, message?: string): PromisedAssertion; + (constructor: Error, expected?: RegExp, message?: string): PromisedAssertion; + (constructor: Function, expected?: string, message?: string): PromisedAssertion; + (constructor: Function, expected?: RegExp, message?: string): PromisedAssertion; + } + + interface PromisedMembers { + (set: any[], message?: string): PromisedAssertion; + } + + // For Assert API interface Assert { - eventually: Assert; - isFulfilled(promise: any, message?: string): void; - becomes(promise: any, expected: any, message?: string): void; - doesNotBecome(promise: any, expected: any, message?: string): void; - isRejected(promise: any, message?: string): void; - isRejected(promise: any, expected: any, message?: string): void; - isRejected(promise: any, match: RegExp, message?: string): void; + eventually: PromisedAssert; + isFulfilled(promise: Thenable, message?: string): Thenable; + becomes(promise: Thenable, expected: any, message?: string): Thenable; + doesNotBecome(promise: Thenable, expected: any, message?: string): Thenable; + isRejected(promise: Thenable, message?: string): Thenable; + isRejected(promise: Thenable, expected: any, message?: string): Thenable; + isRejected(promise: Thenable, match: RegExp, message?: string): Thenable; + notify(fn: Function): Thenable; + } + + export interface PromisedAssert { + fail(actual?: any, expected?: any, msg?: string, operator?: string): Thenable; + + ok(val: any, msg?: string): Thenable; + notOk(val: any, msg?: string): Thenable; + + equal(act: any, exp: any, msg?: string): Thenable; + notEqual(act: any, exp: any, msg?: string): Thenable; + + strictEqual(act: any, exp: any, msg?: string): Thenable; + notStrictEqual(act: any, exp: any, msg?: string): Thenable; + + deepEqual(act: any, exp: any, msg?: string): Thenable; + notDeepEqual(act: any, exp: any, msg?: string): Thenable; + + isTrue(val: any, msg?: string): Thenable; + isFalse(val: any, msg?: string): Thenable; + + isNull(val: any, msg?: string): Thenable; + isNotNull(val: any, msg?: string): Thenable; + + isUndefined(val: any, msg?: string): Thenable; + isDefined(val: any, msg?: string): Thenable; + + isFunction(val: any, msg?: string): Thenable; + isNotFunction(val: any, msg?: string): Thenable; + + isObject(val: any, msg?: string): Thenable; + isNotObject(val: any, msg?: string): Thenable; + + isArray(val: any, msg?: string): Thenable; + isNotArray(val: any, msg?: string): Thenable; + + isString(val: any, msg?: string): Thenable; + isNotString(val: any, msg?: string): Thenable; + + isNumber(val: any, msg?: string): Thenable; + isNotNumber(val: any, msg?: string): Thenable; + + isBoolean(val: any, msg?: string): Thenable; + isNotBoolean(val: any, msg?: string): Thenable; + + typeOf(val: any, type: string, msg?: string): Thenable; + notTypeOf(val: any, type: string, msg?: string): Thenable; + + instanceOf(val: any, type: Function, msg?: string): Thenable; + notInstanceOf(val: any, type: Function, msg?: string): Thenable; + + include(exp: string, inc: any, msg?: string): Thenable; + include(exp: any[], inc: any, msg?: string): Thenable; + + notInclude(exp: string, inc: any, msg?: string): Thenable; + notInclude(exp: any[], inc: any, msg?: string): Thenable; + + match(exp: any, re: RegExp, msg?: string): Thenable; + notMatch(exp: any, re: RegExp, msg?: string): Thenable; + + property(obj: Object, prop: string, msg?: string): Thenable; + notProperty(obj: Object, prop: string, msg?: string): Thenable; + deepProperty(obj: Object, prop: string, msg?: string): Thenable; + notDeepProperty(obj: Object, prop: string, msg?: string): Thenable; + + propertyVal(obj: Object, prop: string, val: any, msg?: string): Thenable; + propertyNotVal(obj: Object, prop: string, val: any, msg?: string): Thenable; + + deepPropertyVal(obj: Object, prop: string, val: any, msg?: string): Thenable; + deepPropertyNotVal(obj: Object, prop: string, val: any, msg?: string): Thenable; + + lengthOf(exp: any, len: number, msg?: string): Thenable; + //alias frenzy + throw(fn: Function, msg?: string): Thenable; + throw(fn: Function, regExp: RegExp): Thenable; + throw(fn: Function, errType: Function, msg?: string): Thenable; + throw(fn: Function, errType: Function, regExp: RegExp): Thenable; + + throws(fn: Function, msg?: string): Thenable; + throws(fn: Function, regExp: RegExp): Thenable; + throws(fn: Function, errType: Function, msg?: string): Thenable; + throws(fn: Function, errType: Function, regExp: RegExp): Thenable; + + Throw(fn: Function, msg?: string): Thenable; + Throw(fn: Function, regExp: RegExp): Thenable; + Throw(fn: Function, errType: Function, msg?: string): Thenable; + Throw(fn: Function, errType: Function, regExp: RegExp): Thenable; + + doesNotThrow(fn: Function, msg?: string): Thenable; + doesNotThrow(fn: Function, regExp: RegExp): Thenable; + doesNotThrow(fn: Function, errType: Function, msg?: string): Thenable; + doesNotThrow(fn: Function, errType: Function, regExp: RegExp): Thenable; + + operator(val: any, operator: string, val2: any, msg?: string): Thenable; + closeTo(act: number, exp: number, delta: number, msg?: string): Thenable; + + sameMembers(set1: any[], set2: any[], msg?: string): Thenable; + includeMembers(set1: any[], set2: any[], msg?: string): Thenable; + + ifError(val: any, msg?: string): Thenable; } } From 1781feb65cdf1fdf505aef85a00beccbe32f119d Mon Sep 17 00:00:00 2001 From: tkQubo Date: Mon, 24 Aug 2015 19:56:16 +0900 Subject: [PATCH 207/345] Fix project url --- gulp-coffeeify/gulp-coffeeify.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gulp-coffeeify/gulp-coffeeify.d.ts b/gulp-coffeeify/gulp-coffeeify.d.ts index e47f863ac..6973b38cc 100644 --- a/gulp-coffeeify/gulp-coffeeify.d.ts +++ b/gulp-coffeeify/gulp-coffeeify.d.ts @@ -1,5 +1,5 @@ // Type definitions for gulp-coffeeify -// Project: gulp-coffeeify +// Project: https://github.com/nariyu/gulp-coffeeify // Definitions by: Qubo // Definitions: https://github.com/borisyankov/DefinitelyTyped From 49c153d83b8f70d4dbf77fa3beab6b9dcf4891fa Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Mon, 24 Aug 2015 19:57:24 +0900 Subject: [PATCH 208/345] Add Kuniwak to credits --- chai-as-promised/chai-as-promised.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chai-as-promised/chai-as-promised.d.ts b/chai-as-promised/chai-as-promised.d.ts index 5b68b0b5d..e6644b03c 100644 --- a/chai-as-promised/chai-as-promised.d.ts +++ b/chai-as-promised/chai-as-promised.d.ts @@ -1,6 +1,6 @@ // Type definitions for chai-as-promised // Project: https://github.com/domenic/chai-as-promised/ -// Definitions by: jt000 +// Definitions by: jt000 , Yuki Kokubun // Definitions: https://github.com/borisyankov/DefinitelyTyped /// From 8abef0fcb5676b38159adb6f93af4385092998c4 Mon Sep 17 00:00:00 2001 From: tkQubo Date: Mon, 24 Aug 2015 21:57:54 +0900 Subject: [PATCH 209/345] Add vinyl-buffer --- vinyl-buffer/vinyl-buffer-tests.ts | 14 ++++++++++++++ vinyl-buffer/vinyl-buffer.d.ts | 17 +++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 vinyl-buffer/vinyl-buffer-tests.ts create mode 100644 vinyl-buffer/vinyl-buffer.d.ts diff --git a/vinyl-buffer/vinyl-buffer-tests.ts b/vinyl-buffer/vinyl-buffer-tests.ts new file mode 100644 index 000000000..6a36d0f52 --- /dev/null +++ b/vinyl-buffer/vinyl-buffer-tests.ts @@ -0,0 +1,14 @@ +/// +/// +/// + +import buffer = require('vinyl-buffer'); +import gulp = require('gulp') +import browserify = require('browserify'); + +gulp.task('build', function() { + return browserify('./index.js') + .bundle() + .pipe(buffer()) + .pipe(gulp.dest('dist/')); +}); diff --git a/vinyl-buffer/vinyl-buffer.d.ts b/vinyl-buffer/vinyl-buffer.d.ts new file mode 100644 index 000000000..dd868eb80 --- /dev/null +++ b/vinyl-buffer/vinyl-buffer.d.ts @@ -0,0 +1,17 @@ +// Type definitions for vinyl-buffer +// Project: https://github.com/hughsk/vinyl-buffer +// Definitions by: Qubo +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "vinyl-buffer" { + namespace buffer { + interface Buffer { + (): NodeJS.ReadWriteStream; + } + } + + var buffer: buffer.Buffer; + + export = buffer; +} + From 44fdc4c19b75a5b6018ad4553898154136719fbe Mon Sep 17 00:00:00 2001 From: tkQubo Date: Mon, 24 Aug 2015 22:14:13 +0900 Subject: [PATCH 210/345] Add vinyl-paths --- vinyl-paths/vinyl-paths-tests.ts | 26 ++++++++++++++++++++++++++ vinyl-paths/vinyl-paths.d.ts | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 vinyl-paths/vinyl-paths-tests.ts create mode 100644 vinyl-paths/vinyl-paths.d.ts diff --git a/vinyl-paths/vinyl-paths-tests.ts b/vinyl-paths/vinyl-paths-tests.ts new file mode 100644 index 000000000..e369dcb64 --- /dev/null +++ b/vinyl-paths/vinyl-paths-tests.ts @@ -0,0 +1,26 @@ +/// +/// +/// + +import gulp = require('gulp'); +import del = require('del'); +import paths = require('vinyl-paths'); + +gulp.task('delete', function () { + return gulp.src('app/*') + .pipe(paths(del)); +}); + +// or if you need to use the paths after the pipeline +gulp.task('delete2', function (cb: Function) { + var vp = paths(); + + gulp.src('app/*') + .pipe(vp) + .pipe(gulp.dest('dist')) + .on('end', function () { + del(vp.paths, cb); + }); +}); + + diff --git a/vinyl-paths/vinyl-paths.d.ts b/vinyl-paths/vinyl-paths.d.ts new file mode 100644 index 000000000..681601eb9 --- /dev/null +++ b/vinyl-paths/vinyl-paths.d.ts @@ -0,0 +1,32 @@ +// Type definitions for vinyl-paths +// Project: https://github.com/sindresorhus/vinyl-paths +// Definitions by: Qubo +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "vinyl-paths" { + + namespace paths { + interface Paths extends NodeJS.ReadWriteStream { + paths: string[]; + } + + interface PathsStatic { + /** + * Use the file paths from a gulp pipeline in vanilla node module + * @param callback The optionally supplied callback will get a file path for every file and is expected + * to call the callback when done. An array of the file paths so far is available as a paths property + * on the stream. + */ + (callback?: Callback): Paths; + } + + interface Callback { + //TODO: Function is gulp.ITaskCallback, which is currently invisible + (path: string, callback: Function): any; + } + } + + var paths: paths.PathsStatic; + export = paths; +} + From 1a4b2f0ff98d7b1071474c4ab16f2626d9a62d31 Mon Sep 17 00:00:00 2001 From: tkQubo Date: Mon, 24 Aug 2015 22:18:47 +0900 Subject: [PATCH 211/345] Add reference to node --- vinyl-buffer/vinyl-buffer.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/vinyl-buffer/vinyl-buffer.d.ts b/vinyl-buffer/vinyl-buffer.d.ts index dd868eb80..b6edbb1aa 100644 --- a/vinyl-buffer/vinyl-buffer.d.ts +++ b/vinyl-buffer/vinyl-buffer.d.ts @@ -3,6 +3,8 @@ // Definitions by: Qubo // Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + declare module "vinyl-buffer" { namespace buffer { interface Buffer { From 25b3502efc4f4750346d2d9a03667398966154b9 Mon Sep 17 00:00:00 2001 From: tkQubo Date: Mon, 24 Aug 2015 22:19:29 +0900 Subject: [PATCH 212/345] Add reference to node --- vinyl-paths/vinyl-paths.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/vinyl-paths/vinyl-paths.d.ts b/vinyl-paths/vinyl-paths.d.ts index 681601eb9..fabc2c667 100644 --- a/vinyl-paths/vinyl-paths.d.ts +++ b/vinyl-paths/vinyl-paths.d.ts @@ -3,6 +3,8 @@ // Definitions by: Qubo // Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + declare module "vinyl-paths" { namespace paths { From 9b8299ce8b34edaea16329b4e391a77c77f91071 Mon Sep 17 00:00:00 2001 From: tkQubo Date: Mon, 24 Aug 2015 22:20:09 +0900 Subject: [PATCH 213/345] Add reference to node --- gulp-coffeeify/gulp-coffeeify.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/gulp-coffeeify/gulp-coffeeify.d.ts b/gulp-coffeeify/gulp-coffeeify.d.ts index 6973b38cc..b847b8c03 100644 --- a/gulp-coffeeify/gulp-coffeeify.d.ts +++ b/gulp-coffeeify/gulp-coffeeify.d.ts @@ -3,6 +3,8 @@ // Definitions by: Qubo // Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + declare module "gulp-coffeeify" { namespace coffeeify { interface Coffeeify { From e12cbe7d2c3ea4079af2f33aca7a07d73a33e381 Mon Sep 17 00:00:00 2001 From: slozier Date: Mon, 24 Aug 2015 13:59:06 -0400 Subject: [PATCH 214/345] Update type of DialogOptions.buttons Add event argument to DialogOptions.buttons callback. --- 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 5cd04f22d..d5e60cd0d 100644 --- a/jqueryui/jqueryui.d.ts +++ b/jqueryui/jqueryui.d.ts @@ -341,7 +341,7 @@ declare module JQueryUI { interface DialogOptions extends DialogEvents { autoOpen?: boolean; - buttons?: { [buttonText: string]: () => void } | ButtonOptions[]; + buttons?: { [buttonText: string]: (event?: Event) => void } | ButtonOptions[]; closeOnEscape?: boolean; closeText?: string; dialogClass?: string; From a22c78d619f18548081e69ce68b950dc6265a74a Mon Sep 17 00:00:00 2001 From: Alexander Horn Date: Mon, 24 Aug 2015 21:00:14 +0200 Subject: [PATCH 215/345] mysql: Added .format() overload Added the .format() overload thats accepts an object for the values parameter --- mysql/mysql-tests.ts | 4 ++++ mysql/mysql.d.ts | 3 +++ 2 files changed, 7 insertions(+) diff --git a/mysql/mysql-tests.ts b/mysql/mysql-tests.ts index f671a6372..97df14dbf 100644 --- a/mysql/mysql-tests.ts +++ b/mysql/mysql-tests.ts @@ -109,6 +109,10 @@ var sql = "SELECT * FROM ?? WHERE ?? = ?"; var inserts = ['users', 'id', userId]; sql = mysql.format(sql, inserts); +var sql = "INSERT INTO posts SET ?"; +var post = { id: 1, title: 'Hello MySQL' }; +sql = mysql.format(sql, post); + connection.config.queryFormat = function (query, values) { if (!values) return query; return query.replace(/\:(\w+)/g, function (txt: string, key: string) { diff --git a/mysql/mysql.d.ts b/mysql/mysql.d.ts index 9b6ed7998..715c799a2 100644 --- a/mysql/mysql.d.ts +++ b/mysql/mysql.d.ts @@ -15,6 +15,7 @@ declare module "mysql" { function escape(value: any): string; function format(sql: string): string; function format(sql: string, values: Array): string; + function format(sql: string, values: any): string; interface IMySql { createConnection(connectionUri: string): IConnection; @@ -24,6 +25,7 @@ declare module "mysql" { escape(value: any): string; format(sql: string): string; format(sql: string, values: Array): string; + format(sql: string, values: any): string; } interface IConnectionStatic { @@ -69,6 +71,7 @@ declare module "mysql" { format(sql: string): string; format(sql: string, values: Array): string; + format(sql: string, values: any): string; on(ev: string, callback: (...args: any[]) => void): IConnection; on(ev: 'error', callback: (err: IError) => void): IConnection; From 948a63a0adb839d35be91dc505ba0b4e004b247a Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Mon, 24 Aug 2015 12:23:29 -0700 Subject: [PATCH 216/345] Made the 'pips' property optional in 'nouislider'. --- nouislider/nouislider.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nouislider/nouislider.d.ts b/nouislider/nouislider.d.ts index 9b6a84902..e63215981 100644 --- a/nouislider/nouislider.d.ts +++ b/nouislider/nouislider.d.ts @@ -77,7 +77,7 @@ declare module noUiSlider { /** * Allows you to generate points along the slider. */ - pips: PipsOptions; + pips?: PipsOptions; } interface PipsOptions { From a662c2649a7de0195e776a04065fd0bc57f1fa16 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Mon, 24 Aug 2015 12:23:57 -0700 Subject: [PATCH 217/345] Use 'let' instead of 'var' in definitions for 'parse'. --- parse/parse.d.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/parse/parse.d.ts b/parse/parse.d.ts index f5f7ad4a0..eae08b1c4 100644 --- a/parse/parse.d.ts +++ b/parse/parse.d.ts @@ -867,9 +867,7 @@ declare namespace Parse { * * import Buffer = require("buffer").Buffer; */ - let HTTPOptions: { - new (): HTTPOptions; - }; + var HTTPOptions: new () => HTTPOptions; interface HTTPOptions extends FunctionResponse { /** * The body of the request. From 1f964fab44772ef1c4c61fc2c2246a6775627aa5 Mon Sep 17 00:00:00 2001 From: Ben Tesser Date: Tue, 11 Aug 2015 04:36:14 -0400 Subject: [PATCH 218/345] Ui-grid: Update Version and Plugin Support Extensive plugin support added (Plugin specific API, ColumnDef, GridOptions, GridRow, Constants). Added docs for all existing interfaces Fixed a few incorrect interfaces, updated interfaces to reflect latest version. Did some cleanup... Moved all plugins into their own modules --- ui-grid/ui-grid.d.ts | 3184 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 3047 insertions(+), 137 deletions(-) diff --git a/ui-grid/ui-grid.d.ts b/ui-grid/ui-grid.d.ts index 9dbb6dac9..a6460dbd4 100644 --- a/ui-grid/ui-grid.d.ts +++ b/ui-grid/ui-grid.d.ts @@ -6,13 +6,18 @@ // These are very definitely preliminary. Please feel free to improve. // Changelog: +// 8/11/2015 ui-grid v3.0.3 +// Extensive plugin support added (Plugin specific API, ColumnDef, GridOptions, GridRow, Constants). +// Added docs for all existing interfaces. +// Fixed a few incorrect interfaces, updated interfaces to reflect latest version. +// Did some cleanup... Moved all plugins into their own modules // 7/8/2015 ui-grid v3.0.0-rc.22-482dc67 // Added primary interfaces for row, column, api, grid, columnDef, and gridOptions. Needs more tests! - +/// /// declare module uiGrid { - export interface UIGridConstants { + export interface IUiGridConstants { LOG_DEBUG_MESSAGES: boolean; LOG_WARN_MESSAGES: boolean; LOG_ERROR_MESSAGES: boolean; @@ -116,67 +121,394 @@ declare module uiGrid { } } export interface IGridInstance { - appScope?: ng.IScope; - columnFooterHeight?: number; - footerHeight?: number; - isScrollingHorizontally?: boolean; - isScrollingVertically?: boolean; - scrollDirection?: number; - addRowHeaderColumn(column: IGridColumn): void; + /** + * adds a row header column to the grid + * @param {IColumnDef} colDef The column definition + */ + addRowHeaderColumn(colDef: IColumnDef): void; + /** + * uses the first row of data to assign colDef.type for any types not defined. + */ assignTypes(): void; + /** + * Populates columnDefs from the provided data + * @param {IRowBuilder} rowBuilder function to be called + */ buildColumnDefsFromData(rowBuilder: IRowBuilder): void; + /** + * creates GridColumn objects from the columnDefinition. + * Calls each registered columnBuilder to further process the column + * @param {IBuildColumnsOptions} options An object containing options to use when building columns + * * orderByColumnDefs: defaults to false. When true, buildColumns will order existing columns + * according to the order within the column definitions + * @returns {ng.IPromise} A promise to load any needed column resources + */ buildColumns(options: IBuildColumnsOptions): ng.IPromise; + /** + * calls each styleComputation function + */ buildStyles(): void; + /** + * Calls the callbacks based on the type of data change that has occurred. + * Always calls the ALL callbacks, calls the ROW, EDIT, COLUMN and OPTIONS callbacks + * if the event type is matching, or if the type is ALL. + * @param {number} type the type of event that occurred - one of the uiGridConstants.dataChange values + * (ALL, ROW, EDIT, COLUMN, OPTIONS + */ callDataChangeCallbacks(type: number): void; - clearAllFilters(refreshRows: boolean, clearConditions: boolean, clearFlags: boolean): void; + /** + * Clears all filters and optionally refreshes the visible rows. + * @param {boolean} [refreshRows=true] Refresh the rows? + * @param {boolean} [clearConditions=true] Clear conditions? + * @param {boolean} [clearFlags=true] Clear flags? + * @returns {ng.IPromise} If refreshRows is true, returns a promise of the rows refreshing + */ + clearAllFilters(refreshRows: boolean, clearConditions: boolean, + clearFlags: boolean): ng.IPromise; + /** + * refreshes the grid when a column refresh is notified, which triggers handling of the visible flag. + * This is called on uiGridConstants.dataChange.COLUMN, and is registered as a dataChangeCallback in grid.js + * @param {string} name column name + */ columnRefreshCallback(name: string): void; + /** + * creates the left render container if it doesn't already exist + */ createLeftContainer(): void; + /** + * creates the right render container if it doesn't already exist + */ createRightContainer(): void; + /** + * sets isScrollingHorizontally to true and sets it to false in a debounced function + */ flagScrollingHorizontally(): void; + /** + * sets isScrollingVertically to true and sets it to false in a debounced function + */ flagScrollingVertically(): void; + /** + * Gets the displayed value of a cell after applying any the cellFilter + * @param {IGridRow} row Row to access + * @param {IGridColumn} col Column to access + * @returns {string} Cell display value + */ getCellDisplayValue(row: IGridRow, col: IGridColumn): string; + /** + * Gets the displayed value of a cell + * @param {IGridRow} row Row to access + * @param {IGridColumn} col Column to access + * @returns {any} Cell value + */ getCellValue(row: IGridRow, col: IGridColumn): any; + /** + * returns a grid colDef for the column name + * @param {string} name Column name + * @returns {IColumnDef} The column definition + */ getColDef(name: string): IColumnDef; + /** + * returns a grid column by name + * @param {string} name Column name + * @returns {IGridColumn} The column + */ getColumn(name: string): IGridColumn; + /** + * Return the columns that the grid is currently being sorted by + * @returns {Array} the columns that the grid is currently being sorted by + */ getColumnSorting(): Array; - getGridQualifiedColField(col: IGridColumn): any; + /** + * Returns the $parse-able accessor for a column within its $scope + * @param {IGridColumn} col Column object + * @returns {string} $parse-able accessor for a column within its $scope + */ + getGridQualifiedColField(col: IGridColumn): string; + /** + * returns all columns except for rowHeader columns + * @returns {Array} All data columns + */ getOnlyDataColumns(): Array; + /** + * returns the GridRow that contains the rowEntity + * @param {any} rowEntity the gridOptionms.data array element instance + * @param {Array} rows The rows to look in. if not provided then it looks in grid.rows + */ getRow(rowEntity: any, rows?: Array): IGridRow; - handleWindowResize(): void; + /** + * Triggered when the browser window resizes; automatically resizes the grid + * @param {ng.IAngularEvent} $event Resize event + */ + handleWindowResize($event: ng.IAngularEvent): void; + /** + * returns true if leftContainer exists + * @returns {boolean} container exists? + */ hasLeftContainer(): boolean; + /** + * returns true if rightContainer exists + * @returns {boolean} container exists? + */ hasRightContainer(): boolean; + /** + * returns true if leftContainer has columns + * @returns {boolean} container has columns + */ hasLeftContainerColumns(): boolean; + /** + * returns true if rightContainer has columns + * @returns {boolean} container has columns + */ hasRightContainerColumns(): boolean; + /** + * Is grid right to left + * @returns {boolean} true if grid is RTL + */ isRTL(): boolean; - isRowHeaderColumn(col: IGridColumn): boolean; - modifyRows(): void; + /** + * Checks if column is a row header + * @param {IGridColumn} column The column + * @returns {boolean} true if the column is a row header + */ + isRowHeaderColumn(column: IGridColumn): boolean; + /** + * creates or removes GridRow objects from the newRawData array. Calls each registered + * rowBuilder to further process the row + * + * This method aims to achieve three things: + * 1. the resulting rows array is in the same order as the newRawData, we'll call + * rowsProcessors immediately after to sort the data anyway + * 2. if we have row hashing available, we try to use the rowHash to find the row + * 3. no memory leaks - rows that are no longer in newRawData need to be garbage collected + * + * The basic logic flow makes use of the newRawData, oldRows and oldHash, and creates + * the newRows and newHash + * + * Rows are identified using the hashKey if configured. If not configured, then rows + * are identified using the gridOptions.rowEquality function + * @param {Array} newRawData The new grid data + * @return {ng.IPromise} Promise which resolves when the rows have been created or removed + */ + modifyRows(newRawData: Array): ng.IPromise; + /** + * Notify the grid that a data or config change has occurred, + * where that change isn't something the grid was otherwise noticing. This + * might be particularly relevant where you've changed values within the data + * and you'd like cell classes to be re-evaluated, or changed config within + * the columnDef and you'd like headerCellClasses to be re-evaluated. + * @param {string} type one of the uiGridConstants.dataChange values [ALL, ROW, EDIT, COLUMN], which tells + * us which refreshes to fire + */ notifyDataChange(type: string): void; + /** + * precompiles all cell templates + */ precompileCellTemplates(): void; + /** + * processes all RowBuilders for the gridRow + * @param {IGridRow} gridRow reference to gridRow + * @returns {IGridRow} the gridRow with all additional behavior added + */ processRowBuilders(gridRow: IGridRow): IGridRow; + /** + * calls the row processors, specifically + * intended to reset the sorting when an edit is called, + * registered as a dataChangeCallback on uiGridConstants.dataChange.EDIT + * @param {string} name column name + */ processRowsCallback(name: string): void; + /** + * queues a grid refresh, a way of debouncing all the refreshes we might otherwise issue + */ queueGridRefresh(): void; + /** + * queues a grid refreshCanvas, a way of debouncing all the refreshes we might otherwise issue + */ queueRefresh(): void; + /** + * Redraw the rows and columns based on our current scroll position + * @param {boolean} [rowsAdded] Optional to indicate rows are added and the scroll percentage must be + * recalculated + */ redrawCanvas(rowsAdded?: boolean): void; + /** + * Refresh the rendered grid on screen. + * The refresh method re-runs both the columnProcessors and the + * rowProcessors, as well as calling refreshCanvas to update all + * the grid sizing. In general you should prefer to use queueGridRefresh + * instead, which is basically a debounced version of refresh. + * + * If you only want to resize the grid, not regenerate all the rows + * and columns, you should consider directly calling refreshCanvas instead. + * @param {boolean} rowsAltered Optional flag for refreshing when the number of rows has changed + */ refresh(rowsAltered?: boolean): void; + /** + * Builds all styles and recalculates much of the grid sizing + * @param {boolean} buildStyles optional parameter. Use TBD + * @returns {ng.IPromise} promise that is resolved when the canvas + * has been refreshed + */ refreshCanvas(buildStyles?: boolean): ng.IPromise; + /** + * Refresh the rendered rows on screen? Note: not functional at present + * @returns {ng.IPromise} promise that is resolved when render completes? + */ refreshRows(): ng.IPromise; + /** + * When the build creates columns from column definitions, the columnbuilders will be called to add + * additional properties to the column. + * @param {IColumnBuilder} columnBuilder function to be called + */ registerColumnBuilder(columnBuilder: IColumnBuilder): void; + /** + * Register a "columns processor" function. When the columns are updated, + * the grid calls each registered "columns processor", which has a chance + * to alter the set of columns, as long as the count is not modified. + * @param {IColumnProcessor} columnProcessor column processor function, which + * is run in the context of the grid (i.e. this for the function will be the grid), and + * which must return an updated renderedColumnsToProcess which can be passed to the next processor + * in the chain + * @param {number} priority the priority of this processor. In general we try to do them in 100s to leave room + * for other people to inject columns processors at intermediate priorities. + * Lower priority columnsProcessors run earlier.priority + */ registerColumnsProcessor(columnProcessor: IColumnProcessor, priority: number): void; + /** + * When a data change occurs, the data change callbacks of the specified type + * will be called. The rules are: + * + * - when the data watch fires, that is considered a ROW change (the data watch only notices + * added or removed rows) + * - when the api is called to inform us of a change, the declared type of that change is used + * - when a cell edit completes, the EDIT callbacks are triggered + * - when the columnDef watch fires, the COLUMN callbacks are triggered + * - when the options watch fires, the OPTIONS callbacks are triggered + * + * For a given event: + * - ALL calls ROW, EDIT, COLUMN, OPTIONS and ALL callbacks + * - ROW calls ROW and ALL callbacks + * - EDIT calls EDIT and ALL callbacks + * - COLUMN calls COLUMN and ALL callbacks + * - OPTIONS calls OPTIONS and ALL callbacks + * + * @param {(grid: IGridInstance) => void} callback function to be called + * @param {Array} types the types of data change you want to be informed of. Values from + * the uiGridConstants.dataChange values ( ALL, EDIT, ROW, COLUMN, OPTIONS ). Optional and defaults to + * ALL + * @returns {Function} deregister function - a function that can be called to deregister this callback + */ registerDataChangeCallback(callback: (grid: IGridInstance) => void, types: Array): Function; + /** + * When the build creates rows from gridOptions.data, the rowBuilders will be called to add + * additional properties to the row. + * @param {IRowBuilder} rowBuilder Function to be called + */ registerRowBuilder(rowBuilder: IRowBuilder): void; + /** + * Register a "rows processor" function. When the rows are updated, + * the grid calls each registered "rows processor", which has a chance + * to alter the set of rows (sorting, etc) as long as the count is not + * modified. + * + * @param {IRowProcessor} rowProcessor rows processor function, which + * is run in the context of the grid (i.e. this for the function will be the grid), and must + * return the updated rows list, which is passed to the next processor in the chain + * @param {number} priority the priority of this processor. + * In general we try to do them in 100s to leave room for other people to inject rows processors at + * intermediate priorities. Lower priority rowsProcessors run earlier. At present all rows visible + * is running at 50, filter is running at 100, sort is at 200, grouping at 400, selectable rows at + * 500, pagination at 900 (pagination will generally want to be last) + */ registerRowsProcessor(rowProcessor: IRowProcessor, priority: number): void; + /** + * registered a styleComputation function + * + * If the function returns a value it will be appended into the grid's `