From 65d386f2de01f5399bc3010002058b3e04a32fea Mon Sep 17 00:00:00 2001 From: Roland Zwaga Date: Thu, 31 Jul 2014 09:23:37 +0200 Subject: [PATCH 001/614] Update CONTRIBUTORS.md --- CONTRIBUTORS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 4c2fbc8e1..b91802e87 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -9,6 +9,7 @@ All definitions files include a header with the author and editors, so at some p * [Add To Home Screen](http://cubiq.org/add-to-home-screen) (by [James Wilkins](http://www.codeplex.com/site/users/view/jamesnw)) * [AmCharts](http://www.amcharts.com/) (by [Covobonomo](https://github.com/covobonomo/)) * [AngularAgility](https://github.com/AngularAgility/AngularAgility) (by [Roland Zwaga](https://github.com/rolandzwaga) +* [AngularBootstrapLightbox](https://github.com/compact/angular-bootstrap-lightbox) (by [Roland Zwaga](https://github.com/rolandzwaga) * [AngularFire](https://www.firebase.com/docs/angular/reference.html) (by [Dénes Harmath](https://github.com/thSoft)) * [AngularJS](http://angularjs.org) (by [Diego Vilar](https://github.com/diegovilar)) ([wiki](https://github.com/borisyankov/DefinitelyTyped/wiki/AngularJS-Definitions-Usage-Notes)) * [angularLocalStorage](https://github.com/agrublev/angularLocalStorage) (by [Hiroki Horiuchi](https://github.com/horiuchi/)) 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 002/614] 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 003/614] 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 004/614] 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 005/614] 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 006/614] 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 007/614] 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 008/614] 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 009/614] 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 010/614] 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 011/614] 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 012/614] 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 013/614] 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 014/614] 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 015/614] 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 016/614] 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 017/614] 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 018/614] 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 019/614] 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 020/614] 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 021/614] 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 022/614] 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 023/614] 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 024/614] 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 025/614] 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 026/614] 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 027/614] 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 028/614] 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 029/614] 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 030/614] 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 031/614] 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 032/614] 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 033/614] 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 034/614] 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 035/614] 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 036/614] 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 037/614] 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 038/614] 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 039/614] 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 040/614] 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 c9e62555dfc9317344fa8ac39dfabb0f74f14d4b Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Wed, 5 Aug 2015 13:58:04 -0700 Subject: [PATCH 041/614] Add 'dataType' to 'jquery.fileupload'. --- jquery.fileupload/jquery.fileupload.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/jquery.fileupload/jquery.fileupload.d.ts b/jquery.fileupload/jquery.fileupload.d.ts index 3774cb6e1..9daea94ee 100644 --- a/jquery.fileupload/jquery.fileupload.d.ts +++ b/jquery.fileupload/jquery.fileupload.d.ts @@ -8,6 +8,11 @@ // Interface options for the plugin interface JQueryFileInputOptions { + /** + * The type of data that is expected back from the server. + */ + dataType?: string; + // The drop target element(s), by the default the complete document. // Set to null to disable drag & drop support: dropZone?: HTMLElement; From 0bd13d9dae8daf5c1502973b83541b0ee214f267 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Wed, 5 Aug 2015 14:04:53 -0700 Subject: [PATCH 042/614] Use JSDoc for 'jquery.fileupload'. --- jquery.fileupload/jquery.fileupload.d.ts | 213 ++++++++++++++--------- 1 file changed, 132 insertions(+), 81 deletions(-) diff --git a/jquery.fileupload/jquery.fileupload.d.ts b/jquery.fileupload/jquery.fileupload.d.ts index 9daea94ee..8c9e93737 100644 --- a/jquery.fileupload/jquery.fileupload.d.ts +++ b/jquery.fileupload/jquery.fileupload.d.ts @@ -13,137 +13,188 @@ interface JQueryFileInputOptions { */ dataType?: string; - // The drop target element(s), by the default the complete document. - // Set to null to disable drag & drop support: + /** + * The drop target element(s), by the default the complete document. + * Set to null to disable drag & drop support: + */ dropZone?: HTMLElement; - // The paste target element(s), by the default the complete document. - // Set to null to disable paste support: + /** + * The paste target element(s), by the default the complete document. + * Set to null to disable paste support: + */ pasteZone?: HTMLElement; - // The file input field(s), that are listened to for change events. - // If undefined, it is set to the file input fields inside - // of the widget element on plugin initialization. - // Set to null to disable the change listener. + /** + * The file input field(s), that are listened to for change events. + * If undefined, it is set to the file input fields inside + * of the widget element on plugin initialization. + * Set to null to disable the change listener. + */ fileInput?: HTMLElement; - // By default, the file input field is replaced with a clone after - // each input field change event. This is required for iframe transport - // queues and allows change events to be fired for the same file - // selection, but can be disabled by setting the following option to false: + /** + * By default, the file input field is replaced with a clone after + * each input field change event. This is required for iframe transport + * queues and allows change events to be fired for the same file + * selection, but can be disabled by setting the following option to false: + */ replaceFileInput?: boolean; - - // The parameter name for the file form data (the request argument name). - // If undefined or empty, the name property of the file input field is - // used, or "files[]" if the file input name property is also empty, - // can be a string or an array of strings: + /** + * The parameter name for the file form data (the request argument name). + * If undefined or empty, the name property of the file input field is + * used, or "files[]" if the file input name property is also empty, + * can be a string or an array of strings: + */ paramName?: any; - // By default, each file of a selection is uploaded using an individual - // request for XHR type uploads. Set to false to upload file - // selections in one request each: + /** + * By default, each file of a selection is uploaded using an individual + * request for XHR type uploads. Set to false to upload file + * selections in one request each: + */ singleFileUploads?: boolean; - // To limit the number of files uploaded with one XHR request, - // set the following option to an integer greater than 0: + /** + * To limit the number of files uploaded with one XHR request, + * set the following option to an integer greater than 0: + */ limitMultiFileUploads?: number; - // The following option limits the number of files uploaded with one - // XHR request to keep the request size under or equal to the defined - // limit in bytes: + /** + * The following option limits the number of files uploaded with one + * XHR request to keep the request size under or equal to the defined + * limit in bytes + */ limitMultiFileUploadSize?: number; - // Multipart file uploads add a number of bytes to each uploaded file, - // therefore the following option adds an overhead for each file used - // in the limitMultiFileUploadSize configuration: + /** + * Multipart file uploads add a number of bytes to each uploaded file, + * therefore the following option adds an overhead for each file used + * in the limitMultiFileUploadSize configuration: + */ limitMultiFileUploadSizeOverhead?: number; - // Set the following option to true to issue all file upload requests - // in a sequential order: + /** + * Set the following option to true to issue all file upload requests + * in a sequential order: + */ sequentialUploads?: boolean; - // To limit the number of concurrent uploads, - // set the following option to an integer greater than 0: + /** + * To limit the number of concurrent uploads, + * set the following option to an integer greater than 0: + */ limitConcurrentUploads?: number; - // Set the following option to true to force iframe transport uploads: + /** + * Set the following option to true to force iframe transport uploads: + */ forceIframeTransport?: boolean; - // Set the following option to the location of a redirect url on the - // origin server, for cross-domain iframe transport uploads: + /** + * Set the following option to the location of a redirect url on the + * origin server, for cross-domain iframe transport uploads: + */ redirect?: string; - // The parameter name for the redirect url, sent as part of the form - // data and set to 'redirect' if this option is empty: + /** + * The parameter name for the redirect url, sent as part of the form + * data and set to 'redirect' if this option is empty: + */ redirectParamName?: string; - // Set the following option to the location of a postMessage window, - // to enable postMessage transport uploads: + /** + * Set the following option to the location of a postMessage window, + * to enable postMessage transport uploads: + */ postMessage?: string; - // By default, XHR file uploads are sent as multipart/form-data. - // The iframe transport is always using multipart/form-data. - // Set to false to enable non-multipart XHR uploads: + /** + * By default, XHR file uploads are sent as multipart/form-data. + * The iframe transport is always using multipart/form-data. + * Set to false to enable non-multipart XHR uploads: + */ multipart?: boolean; - // To upload large files in smaller chunks, set the following option - // to a preferred maximum chunk size. If set to 0, null or undefined, - // or the browser does not support the required Blob API, files will - // be uploaded as a whole. + /** + * To upload large files in smaller chunks, set the following option + * to a preferred maximum chunk size. If set to 0, null or undefined, + * or the browser does not support the required Blob API, files will + * be uploaded as a whole. + */ maxChunkSize?: number; - // When a non-multipart upload or a chunked multipart upload has been - // aborted, this option can be used to resume the upload by setting - // it to the size of the already uploaded bytes. This option is most - // useful when modifying the options object inside of the "add" or - // "send" callbacks, as the options are cloned for each file upload. + /** + * When a non-multipart upload or a chunked multipart upload has been + * aborted, this option can be used to resume the upload by setting + * it to the size of the already uploaded bytes. This option is most + * useful when modifying the options object inside of the "add" or + * "send" callbacks, as the options are cloned for each file upload. + */ uploadedBytes?: number; - // By default, failed (abort or error) file uploads are removed from the - // global progress calculation. Set the following option to false to - // prevent recalculating the global progress data: + /** + * By default, failed (abort or error) file uploads are removed from the + * global progress calculation. Set the following option to false to + * prevent recalculating the global progress data: + */ recalculateProgress?: boolean; - // Interval in milliseconds to calculate and trigger progress events: + /** + * Interval in milliseconds to calculate and trigger progress events: + */ progressInterval?: number; - // Interval in milliseconds to calculate progress bitrate: + /** + * Interval in milliseconds to calculate progress bitrate: + */ bitrateInterval?: number; - // By default, uploads are started automatically when adding files: + /** + * By default, uploads are started automatically when adding files: + */ autoUpload?: boolean; - // Error and info messages: + /** + * Error and info messages: + */ messages?: any; - // Translation function, gets the message key to be translated - // and an object with context specific data as arguments: + /** + * Translation function, gets the message key to be translated + * and an object with context specific data as arguments: + */ i18n?: any; - // Additional form data to be sent along with the file uploads can be set - // using this option, which accepts an array of objects with name and - // value properties, a function returning such an array, a FormData - // object (for XHR file uploads), or a simple object. - // The form of the first fileInput is given as parameter to the function: + /** + * Additional form data to be sent along with the file uploads can be set + * using this option, which accepts an array of objects with name and + * value properties, a function returning such an array, a FormData + * object (for XHR file uploads), or a simple object. + * The form of the first fileInput is given as parameter to the function: + */ formData?: any; - // The add callback is invoked as soon as files are added to the fileupload - // widget (via file input selection, drag & drop, paste or add API call). - // If the singleFileUploads option is enabled, this callback will be - // called once for each file in the selection for XHR file uploads, else - // once for each file selection. - // - // The upload starts when the submit method is invoked on the data parameter. - // The data object contains a files property holding the added files - // and allows you to override plugin options as well as define ajax settings. - // - // Listeners for this callback can also be bound the following way: - // .bind('fileuploadadd', func); - // - // data.submit() returns a Promise object and allows to attach additional - // handlers using jQuery's Deferred callbacks: - // data.submit().done(func).fail(func).always(func); + /** + * The add callback is invoked as soon as files are added to the fileupload + * widget (via file input selection, drag & drop, paste or add API call). + * If the singleFileUploads option is enabled, this callback will be + * called once for each file in the selection for XHR file uploads, else + * once for each file selection. + * + * The upload starts when the submit method is invoked on the data parameter. + * The data object contains a files property holding the added files + * and allows you to override plugin options as well as define ajax settings. + * + * Listeners for this callback can also be bound the following way: + * .bind('fileuploadadd', func); + * + * data.submit() returns a Promise object and allows to attach additional + * handlers using jQuery's Deferred callbacks: + * data.submit().done(func).fail(func).always(func); + */ add?: any; // The plugin options are used as settings object for the ajax calls. From 290fa269a8fe64d32db63800d4311f28187f275b Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Wed, 5 Aug 2015 14:09:23 -0700 Subject: [PATCH 043/614] Add 'animationSpeed' to 'jquery.notifyBar'. --- jquery.notifyBar/jquery.notifyBar.d.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/jquery.notifyBar/jquery.notifyBar.d.ts b/jquery.notifyBar/jquery.notifyBar.d.ts index 22e012673..bbfb59bc3 100644 --- a/jquery.notifyBar/jquery.notifyBar.d.ts +++ b/jquery.notifyBar/jquery.notifyBar.d.ts @@ -18,6 +18,13 @@ declare module JQueryNotifyBar { */ delay?: number; + /** + * How long this bar will be slided up and down. + * + * Default: "normal" + */ + animationSpeed?: string | number; + /** * Custom jQuery object for notify bar. */ From 4b4fd6dd16af81f9c292d42df5694a68c1e934ba Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Wed, 5 Aug 2015 14:16:51 -0700 Subject: [PATCH 044/614] Test all properties of options in 'jquery.pjax'. --- jquery.pjax/jquery.pjax-tests.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/jquery.pjax/jquery.pjax-tests.ts b/jquery.pjax/jquery.pjax-tests.ts index 0df488130..257a265dd 100644 --- a/jquery.pjax/jquery.pjax-tests.ts +++ b/jquery.pjax/jquery.pjax-tests.ts @@ -47,11 +47,15 @@ function test_defauluts() { timeout: 650, push: true, replace: false, + maxCacheLength: 20, + version: $.noop, + scrollTo: 0, type: 'GET', dataType: 'html', - scrollTo: 0, - maxCacheLength: 20, - version: $.noop + container: "#pjax-container", + url: "https://jquery.com/", + target: "https://jquery.com/", + fragment: "#pjax-response", }; } From 6bf2f869e141121959b23e7168ea9ec93b0f2082 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Wed, 5 Aug 2015 14:26:47 -0700 Subject: [PATCH 045/614] Added missing properties in 'jquery.pjax'. --- jquery.pjax/jquery.pjax-tests.ts | 2 +- jquery.pjax/jquery.pjax.d.ts | 23 ++++++++++++++++++++++- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/jquery.pjax/jquery.pjax-tests.ts b/jquery.pjax/jquery.pjax-tests.ts index 257a265dd..6af27618e 100644 --- a/jquery.pjax/jquery.pjax-tests.ts +++ b/jquery.pjax/jquery.pjax-tests.ts @@ -54,7 +54,7 @@ function test_defauluts() { dataType: 'html', container: "#pjax-container", url: "https://jquery.com/", - target: "https://jquery.com/", + target: undefined, fragment: "#pjax-response", }; } diff --git a/jquery.pjax/jquery.pjax.d.ts b/jquery.pjax/jquery.pjax.d.ts index 1bd465b1e..bc7d39209 100644 --- a/jquery.pjax/jquery.pjax.d.ts +++ b/jquery.pjax/jquery.pjax.d.ts @@ -36,7 +36,28 @@ interface PjaxSettings extends JQueryAjaxSettings { /** * How many requests to cache. Defaults to 20. */ - maxCacheLength?: number; + maxCacheLength?: number; + + /** + * A string or function returning the current pjax version + */ + version?: string | (() => string); + + /** + * Vertical position to scroll to after navigation. + * To avoid changing scroll position, pass false. + */ + scrollTo?: number | boolean; + + /** + * Eventually the relatedTarget value for pjax events. + */ + target?: EventTarget; + + /** + * CSS selector for the fragment to extract from ajax response. + */ + fragment?: string; } interface JQuery { From da093877f475389bf0e4b62d29afbf17fbd597a4 Mon Sep 17 00:00:00 2001 From: Ivan Drinchev Date: Thu, 6 Aug 2015 20:06:25 +0200 Subject: [PATCH 046/614] 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 047/614] 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 55ebb8625a06e127197fa963e708be610f7fc9b2 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 6 Aug 2015 15:17:55 -0700 Subject: [PATCH 048/614] Fix overload order for 'jquery.colorpicker'. --- jquery.colorpicker/jquery.colorpicker.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/jquery.colorpicker/jquery.colorpicker.d.ts b/jquery.colorpicker/jquery.colorpicker.d.ts index 5c89e4ed0..32f68c1c1 100644 --- a/jquery.colorpicker/jquery.colorpicker.d.ts +++ b/jquery.colorpicker/jquery.colorpicker.d.ts @@ -154,11 +154,11 @@ interface JQueryStatic { } interface JQuery { - colorpicker(options?: JQueryColorpickerOptions): JQuery; - colorpicker(method: string): JQuery; - colorpicker(method: string, param: any): JQuery; colorpicker(method: "close"): JQuery; colorpicker(method: "destroy"): JQuery; colorpicker(method: "open"): JQuery; + colorpicker(method: string): JQuery; colorpicker(method: "setColor", color: any): JQuery; + colorpicker(method: string, param: any): JQuery; + colorpicker(options?: JQueryColorpickerOptions): JQuery; } From 71738c9b95ed67fa194e146f0bab04246d23cdaa Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 6 Aug 2015 15:18:52 -0700 Subject: [PATCH 049/614] Fix overload order for 'jquery.timepicker'. --- jquery.timepicker/jquery.timepicker.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/jquery.timepicker/jquery.timepicker.d.ts b/jquery.timepicker/jquery.timepicker.d.ts index 13a6d2e69..59d677706 100644 --- a/jquery.timepicker/jquery.timepicker.d.ts +++ b/jquery.timepicker/jquery.timepicker.d.ts @@ -63,12 +63,12 @@ interface TimePickerOptions { interface JQuery { timepicker(): JQuery; - timepicker(options: TimePickerOptions): JQuery; - timepicker(methodName: string): any; timepicker(methodName: 'getTime'): string; timepicker(methodName: 'getTimeAsDate'): Date; timepicker(methodName: 'getHour'): number; timepicker(methodName: 'getMinute'): number; + timepicker(methodName: string): any; timepicker(methodName: string, methodParameter: any): any; timepicker(optionLiteral: string, optionName: string): any; + timepicker(options: TimePickerOptions): JQuery; } From 23d1273719d3edf1233c52adc92c10307073fe25 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 6 Aug 2015 15:28:38 -0700 Subject: [PATCH 050/614] Use JSDoc comments. --- jquery.timepicker/jquery.timepicker.d.ts | 72 ++++++++++++------------ 1 file changed, 36 insertions(+), 36 deletions(-) diff --git a/jquery.timepicker/jquery.timepicker.d.ts b/jquery.timepicker/jquery.timepicker.d.ts index 59d677706..bc8678d72 100644 --- a/jquery.timepicker/jquery.timepicker.d.ts +++ b/jquery.timepicker/jquery.timepicker.d.ts @@ -7,57 +7,57 @@ /// interface TimePickerHour { - starts?: number; // first displayed hour - ends?: number; // last displayed hour + /** first displayed hour */ starts?: number; + /** last displayed hour */ ends?: number; } interface TimePickerMinutes { - starts?: number; // first displayed minute - ends?: number; // last displayed minute - interval?: number; // interval of displayed minutes + /** first displayed minute */ starts?: number; + /** last displayed minute */ ends?: number; + /** interval of displayed minutes */ interval?: number; } interface TimePickerOptions { - showOn?: string; // 'focus' for popup on focus, - // 'button' for trigger button, or 'both' for either (not yet implemented) - button?: string; // 'button' element that will trigger the timepicker - showAnim?: string; // Name of jQuery animation for popup - showOptions?: any; // Options for enhanced animations - appendText?: string; // Display text following the input box, e.g. showing the format + /** 'focus' for popup on focus, */ showOn?: string; + + /** * 'button' element that will trigger the timepicker. * * "button" for trigger button, or "both" for either (not yet implemented). */ button?: string; + + /** Name of jQuery animation for popup */ showAnim?: string; + /** Options for enhanced animations */ showOptions?: any; + /** Display text following the input box, e.g. showing the format */ appendText?: string; - beforeShow?: () => any; // Define a callback function executed before the timepicker is shown - onSelect?: (timeText: string, inst: any) => any; // Define a callback function when a hour / minutes is selected - onClose?: (timeText: string, inst: any) => any; // Define a callback function when the timepicker is closed + /** Define a callback function executed before the timepicker is shown */ beforeShow?: () => any; + /** Define a callback function when a hour / minutes is selected */ onSelect?: (timeText: string, inst: any) => any; + /** Define a callback function when the timepicker is closed */ onClose?: (timeText: string, inst: any) => any; + + /** The character to use to separate hours and minutes. */ timeSeparator?: string; + /** The character to use to separate the time from the time period. */ periodSeparator?: string; + /** Define whether or not to show AM/PM with selected time */ showPeriod?: boolean; + /** Show the AM/PM labels on the left of the time picker */ showPeriodLabels?: boolean; + /** Define whether or not to show a leading zero for hours < 10. [true/false] */ showLeadingZero?: boolean; + /** Define whether or not to show a leading zero for minutes < 10. */ showMinutesLeadingZero?: boolean; + /** Selector for an alternate field to store selected time into */ altField?: string; + /** * Used as default time when input field is empty or for inline timePicker * (set to 'now' for the current time, '' for no highlighted time) **/ defaultTime?: string; + /** * Position of the dialog relative to the input. * * See the position utility for more info : http://jqueryui.com/demos/position/ */ myPosition?: string; + /** * Position of the input element to match * * Note : if the position utility is not loaded, the timepicker will attach left top to left bottom * See the position utility for more info : http://jqueryui.com/demos/position/ */ atPosition?: string; - timeSeparator?: string; // The character to use to separate hours and minutes. - periodSeparator?: string; // The character to use to separate the time from the time period. - showPeriod?: boolean; // Define whether or not to show AM/PM with selected time - showPeriodLabels?: boolean; // Show the AM/PM labels on the left of the time picker - showLeadingZero?: boolean; // Define whether or not to show a leading zero for hours < 10. [true/false] - showMinutesLeadingZero?: boolean; // Define whether or not to show a leading zero for minutes < 10. - altField?: string; // Selector for an alternate field to store selected time into - defaultTime?: string; // Used as default time when input field is empty or for inline timePicker - // (set to 'now' for the current time, '' for no highlighted time) - myPosition?: string; // Position of the dialog relative to the input. - // see the position utility for more info : http://jqueryui.com/demos/position/ - atPosition?: string; // Position of the input element to match - // Note : if the position utility is not loaded, the timepicker will attach left top to left bottom //NEW: 2011-02-03 - onHourShow?: () => any; // callback for enabling / disabling on selectable hours ex : function(hour) { return true; } - onMinuteShow?: () => any; // callback for enabling / disabling on time selection ex : function(hour,minute) { return true; } + /** callback for enabling / disabling on selectable hours ex : function(hour) { return true; } */ onHourShow?: () => any; + /** callback for enabling / disabling on time selection ex : function(hour,minute) { return true; } */ onMinuteShow?: () => any; hours?: TimePickerHour; minutes?: TimePickerMinutes; - rows?: number; // number of rows for the input tables, minimum 2, makes more sense if you use multiple of 2 + + /** number of rows for the input tables, minimum 2, makes more sense if you use multiple of 2 */ rows?: number; // 2011-08-05 0.2.4 - showHours?: boolean; // display the hours section of the dialog - showMinutes?: boolean; // display the minute section of the dialog - optionalMinutes?: boolean; // optionally parse inputs of whole hours with minutes omitted + /** display the hours section of the dialog */ showHours?: boolean; + /** display the minute section of the dialog */ showMinutes?: boolean; + /** optionally parse inputs of whole hours with minutes omitted */ optionalMinutes?: boolean; // buttons - showCloseButton?: boolean; // shows an OK button to confirm the edit - showNowButton?: boolean; // Shows the 'now' button - showDeselectButton?: boolean; // Shows the deselect time button + /** shows an OK button to confirm the edit */ showCloseButton?: boolean; + /** Shows the 'now' button */ showNowButton?: boolean; + /** Shows the deselect time button */ showDeselectButton?: boolean; } From fc0f0afd0abbb61b4f26ffa81b49a6615a1feca2 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 6 Aug 2015 15:57:06 -0700 Subject: [PATCH 051/614] Added missing properties for 'jquery.timepicker'. --- jquery.timepicker/jquery.timepicker.d.ts | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/jquery.timepicker/jquery.timepicker.d.ts b/jquery.timepicker/jquery.timepicker.d.ts index bc8678d72..398813b9e 100644 --- a/jquery.timepicker/jquery.timepicker.d.ts +++ b/jquery.timepicker/jquery.timepicker.d.ts @@ -22,6 +22,17 @@ interface TimePickerOptions { /** * 'button' element that will trigger the timepicker. * * "button" for trigger button, or "both" for either (not yet implemented). */ button?: string; + // Localization + + /** Define the locale text for "Hours" */ + hourText?: string; + + /** Define the locale text for "Minute" */ + minuteText?: string; + + /** Define the locale text for periods. */ + amPmText?: [string, string]; + /** Name of jQuery animation for popup */ showAnim?: string; /** Options for enhanced animations */ showOptions?: any; /** Display text following the input box, e.g. showing the format */ appendText?: string; @@ -56,8 +67,19 @@ interface TimePickerOptions { // buttons /** shows an OK button to confirm the edit */ showCloseButton?: boolean; + + /** Text for the confirmation button (ok button).*/ + closeButtonText?: string; + /** Shows the 'now' button */ showNowButton?: boolean; + + /** Text for the 'now' button.*/ + nowButtonText?: string; + /** Shows the deselect time button */ showDeselectButton?: boolean; + + /** Text for the deselect button */ + deselectButtonText?: string; } From 9916c6f043cfd9e3274c0649f395d27c879abef3 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 6 Aug 2015 16:00:11 -0700 Subject: [PATCH 052/614] Fix overload order for 'jquery-sortable'. --- jquery-sortable/jquery-sortable.d.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/jquery-sortable/jquery-sortable.d.ts b/jquery-sortable/jquery-sortable.d.ts index 82f4e8aa0..b416dfb8e 100644 --- a/jquery-sortable/jquery-sortable.d.ts +++ b/jquery-sortable/jquery-sortable.d.ts @@ -91,14 +91,12 @@ declare module JQuerySortable { } } - interface JQuery { - sortable(options?: JQuerySortable.Options): JQuery; - sortable(methodName: 'enable'): JQuery; sortable(methodName: 'disable'): JQuery; sortable(methodName: 'refresh'): JQuery; sortable(methodName: 'destroy'): JQuery; sortable(methodName: 'serialize'): JQuery; sortable(methodName: string): JQuery; + sortable(options?: JQuerySortable.Options): JQuery; } From 5ed654f9b8154a9c0df7cbeae24c8c669997ad7e Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 6 Aug 2015 16:40:44 -0700 Subject: [PATCH 053/614] Added 'group' to options for 'jquery-sortable'. Should follow up with https://github.com/johnny/jquery-sortable/issues/187 --- jquery-sortable/jquery-sortable.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/jquery-sortable/jquery-sortable.d.ts b/jquery-sortable/jquery-sortable.d.ts index b416dfb8e..ce47a5900 100644 --- a/jquery-sortable/jquery-sortable.d.ts +++ b/jquery-sortable/jquery-sortable.d.ts @@ -88,6 +88,7 @@ declare module JQuerySortable { } interface Options extends GroupOptions, ContainerOptions { + group?: string; } } From e5a57c9bbb981db484fb3d4531fe04e994bd34dd Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 6 Aug 2015 16:51:57 -0700 Subject: [PATCH 054/614] sockerUrl -> socketUrl in 'jquery-jsonrpcclient'. --- jquery-jsonrpcclient/jquery-jsonrpcclient.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jquery-jsonrpcclient/jquery-jsonrpcclient.d.ts b/jquery-jsonrpcclient/jquery-jsonrpcclient.d.ts index de008dc09..c771f9a77 100644 --- a/jquery-jsonrpcclient/jquery-jsonrpcclient.d.ts +++ b/jquery-jsonrpcclient/jquery-jsonrpcclient.d.ts @@ -8,7 +8,7 @@ interface JsonRpcClientOptions extends JQueryAjaxSettings { ajaxUrl?: string; headers?: {[key:string]: any}; - sockerUrl?: string; + socketUrl?: string; onmessage?: () => void; onopen?: () => void; onclose?: () => void; From 74528bc33450950053a831afd604187cbe0c69c2 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 6 Aug 2015 16:55:37 -0700 Subject: [PATCH 055/614] Used correct types from websocket callbacks in 'jquery-jsonrpcclient'. --- jquery-jsonrpcclient/jquery-jsonrpcclient.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/jquery-jsonrpcclient/jquery-jsonrpcclient.d.ts b/jquery-jsonrpcclient/jquery-jsonrpcclient.d.ts index c771f9a77..94981217b 100644 --- a/jquery-jsonrpcclient/jquery-jsonrpcclient.d.ts +++ b/jquery-jsonrpcclient/jquery-jsonrpcclient.d.ts @@ -9,10 +9,10 @@ interface JsonRpcClientOptions extends JQueryAjaxSettings { ajaxUrl?: string; headers?: {[key:string]: any}; socketUrl?: string; - onmessage?: () => void; - onopen?: () => void; - onclose?: () => void; - onerror?: () => void; + onmessage?: (ev: MessageEvent) => void; + onopen?: (ev: Event) => void; + onclose?: (ev: CloseEvent) => void; + onerror?: (ev: Event) => void; getSockect?: (onmessageCb: () => void) => WebSocket; } From 4c2711f4cf264b6191d28aff0d715a005cf8713b Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 6 Aug 2015 17:20:02 -0700 Subject: [PATCH 056/614] Make 'ajaxUrl' non-optional in 'jquery-jsonrpcclient'. --- jquery-jsonrpcclient/jquery-jsonrpcclient.d.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/jquery-jsonrpcclient/jquery-jsonrpcclient.d.ts b/jquery-jsonrpcclient/jquery-jsonrpcclient.d.ts index 94981217b..fd620ba7f 100644 --- a/jquery-jsonrpcclient/jquery-jsonrpcclient.d.ts +++ b/jquery-jsonrpcclient/jquery-jsonrpcclient.d.ts @@ -6,7 +6,7 @@ /// interface JsonRpcClientOptions extends JQueryAjaxSettings { - ajaxUrl?: string; + ajaxUrl: string; headers?: {[key:string]: any}; socketUrl?: string; onmessage?: (ev: MessageEvent) => void; @@ -14,6 +14,12 @@ interface JsonRpcClientOptions extends JQueryAjaxSettings { onclose?: (ev: CloseEvent) => void; onerror?: (ev: Event) => void; getSockect?: (onmessageCb: () => void) => WebSocket; + + /** + * Sets timeout for calls in milliseconds. + * Works with WebSocket as well as AJAX. + */ + timeout?: number; } interface JsonRpcClient { From b1578458f4e8a134c4bab56305124a9169f42521 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 6 Aug 2015 17:27:30 -0700 Subject: [PATCH 057/614] Correct option type in 'jqrangeslider'. --- jqrangeslider/jqrangeslider.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jqrangeslider/jqrangeslider.d.ts b/jqrangeslider/jqrangeslider.d.ts index b41df43c0..58934e776 100644 --- a/jqrangeslider/jqrangeslider.d.ts +++ b/jqrangeslider/jqrangeslider.d.ts @@ -70,5 +70,5 @@ interface JQuery { dateRangeSlider(method: string): any; dateRangeSlider(method: string, value: Date): JQuery; dateRangeSlider(method: string, min: Date, max: Date): JQuery - dateRangeSlider(options?: JQRangeSliderOptions): JQuery; + dateRangeSlider(options?: JQDateRangeSliderOptions): JQuery; } From c6fed019e861566e9b306528272fcbfa64249890 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 6 Aug 2015 17:32:00 -0700 Subject: [PATCH 058/614] Correct test for 'ReferenceOptions' object in 'joi'. --- joi/joi-tests.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/joi/joi-tests.ts b/joi/joi-tests.ts index 26048a9dc..fbdb12779 100644 --- a/joi/joi-tests.ts +++ b/joi/joi-tests.ts @@ -78,9 +78,8 @@ whenOpts = {is: schema, otherwise: schema}; var refOpts: Joi.ReferenceOptions = null; -refOpts = {alias: bool}; -refOpts = {multiple: bool}; -refOpts = {override: bool}; +refOpts = {separator: str}; +refOpts = {contextPrefix: str}; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- From dd12455c4a3171db5dab22780d522dc2f138c6c4 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Fri, 7 Aug 2015 14:57:38 -0700 Subject: [PATCH 059/614] backgound -> background in 'highcharts'. --- highcharts/highstock.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/highcharts/highstock.d.ts b/highcharts/highstock.d.ts index 162d15655..5f59e3694 100644 --- a/highcharts/highstock.d.ts +++ b/highcharts/highstock.d.ts @@ -14,7 +14,7 @@ interface HighstockNavigatorOptions { baseSeries?: string | number; enabled?: boolean; handles?: { - backgoundColor?: string; + backgroundColor?: string; borderColor?: string; }; height?: number; From 6c2a9bd4a28f7fe0c03d38ed9af5cc64b88eb431 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Fri, 7 Aug 2015 15:03:16 -0700 Subject: [PATCH 060/614] Use correct object in test for 'highcharts'. --- highcharts/highcharts-tests.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/highcharts/highcharts-tests.ts b/highcharts/highcharts-tests.ts index 9918df953..f163f2a30 100644 --- a/highcharts/highcharts-tests.ts +++ b/highcharts/highcharts-tests.ts @@ -112,9 +112,7 @@ var chart2 = new Highcharts.Chart({ }); chart1.exportChart(null, { - chart: { - backgroundColor: '#FFFFFF' - } + backgroundColor: '#FFFFFF' }); From 3e2ea701cdb0208fc2fd423f5875a72c9777e406 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Fri, 7 Aug 2015 17:09:26 -0700 Subject: [PATCH 061/614] Fix test for 'hammerjs'. --- hammerjs/hammerjs-1.1.3-tests.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/hammerjs/hammerjs-1.1.3-tests.ts b/hammerjs/hammerjs-1.1.3-tests.ts index 42c5ccea3..5515175af 100644 --- a/hammerjs/hammerjs-1.1.3-tests.ts +++ b/hammerjs/hammerjs-1.1.3-tests.ts @@ -43,7 +43,7 @@ $("#element") }); $("#container").hammer({ - prevent_default: false, - drag_block_vertical: false + preventDefault: false, + dragBlockVertical: false }).on("hold tap doubletap transformstart transform transformend dragstart drag dragend release swipe", function (ev) { }); \ No newline at end of file From 5d6c3bdb5d936b257f22961890141a999e19daef Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Fri, 7 Aug 2015 17:35:54 -0700 Subject: [PATCH 062/614] includeContext -> includeContent and fix overload signature ordering in 'gulp-sourcemaps'. --- gulp-sourcemaps/gulp-sourcemaps.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gulp-sourcemaps/gulp-sourcemaps.d.ts b/gulp-sourcemaps/gulp-sourcemaps.d.ts index 220085367..56cb957e1 100644 --- a/gulp-sourcemaps/gulp-sourcemaps.d.ts +++ b/gulp-sourcemaps/gulp-sourcemaps.d.ts @@ -17,12 +17,12 @@ declare module "gulp-sourcemaps" { interface WriteOptions { addComment?: boolean; - includeContext?: boolean; + includeContent?: boolean; sourceRoot?: string | WriteMapper; sourceMappingURLPrefix?: string | WriteMapper; } export function init(opts?: InitOptions): NodeJS.ReadWriteStream; - export function write(opts?: WriteOptions): NodeJS.ReadWriteStream; export function write(path?: string, opts?: WriteOptions): NodeJS.ReadWriteStream; + export function write(opts?: WriteOptions): NodeJS.ReadWriteStream; } \ No newline at end of file From 0bd8371116a8cf3b9c38ffeee9d6a5ff150973f2 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Fri, 7 Aug 2015 17:50:26 -0700 Subject: [PATCH 063/614] 'viewDisplay' is not documented in 'fullcalendar'. --- fullCalendar/fullCalendar-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fullCalendar/fullCalendar-tests.ts b/fullCalendar/fullCalendar-tests.ts index e7c01a27e..6890cbe42 100644 --- a/fullCalendar/fullCalendar-tests.ts +++ b/fullCalendar/fullCalendar-tests.ts @@ -67,7 +67,7 @@ $('#calendar').fullCalendar({ $('#calendar').fullCalendar('option', 'aspectRatio', 1.8); $('#calendar').fullCalendar({ - viewDisplay: function (view) { + viewRender: function(view) { alert('The new title of the view is ' + view.title); } }); From e7f03cf4e36003b307ccd489689f07701a74b648 Mon Sep 17 00:00:00 2001 From: Shmulik Flint Date: Sun, 9 Aug 2015 17:23:38 +0300 Subject: [PATCH 064/614] Add lodash _.partition Add t.ds definition for lodash _.partition method --- lodash/lodash.d.ts | 118 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 118 insertions(+) diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 7c4111746..0820b5c33 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -4093,6 +4093,124 @@ declare module _ { property: string): LoDashArrayWrapper; } + //_.partition + interface LoDashStatic { + /** + * Creates an array of elements split into two groups, the first of which contains elements predicate returns truthy for, + * while the second of which contains elements predicate returns falsey for. + * The predicate is bound to thisArg and invoked with three arguments: (value, index|key, collection). + * + * If a property name is provided for predicate the created _.property style callback + * returns the property value of the given element. + * + * If a value is also provided for thisArg the created _.matchesProperty style callback + * returns true for elements that have a matching property value, else false. + * + * If an object is provided for predicate the created _.matches style callback returns + * true for elements that have the properties of the given object, else false. + * + * @param collection The collection to iterate over. + * @param callback The function called per iteration. + * @param thisArg The this binding of predicate. + * @return Returns the array of grouped elements. + **/ + partition( + collection: Array, + callback: ListIterator, + thisArg?: any): T[][]; + + /** + * @see _.partition + **/ + partition( + collection: List, + callback: ListIterator, + thisArg?: any): T; + + /** + * @see _.partition + **/ + partition( + collection: Dictionary, + callback: DictionaryIterator, + thisArg?: any): T; + + /** + * @see _.partition + * @param _.matches style callback + **/ + partition( + collection: Array, + whereValue: W): T; + + /** + * @see _.partition + * @param _.matches style callback + **/ + partition( + collection: List, + whereValue: W): T; + + /** + * @see _.partition + * @param _.matches style callback + **/ + partition( + collection: Dictionary, + whereValue: W): T; + + /** + * @see _.partition + * @param _.property style callback + **/ + partition( + collection: Array, + pluckValue: string): T; + + /** + * @see _.partition + * @param _.property style callback + **/ + partition( + collection: List, + pluckValue: string): T; + + /** + * @param _.property style callback + **/ + partition( + collection: Dictionary, + pluckValue: string): T; + } + + interface LoDashArrayWrapper { + /** + * @see _.partition + */ + partition( + callback: ListIterator, + thisArg?: any): LoDashArrayWrapper; + /** + * @see _.partition + * @param _.matches style callback + */ + partition( + whereValue: W): LoDashArrayWrapper; + /** + * @see _.partition + * @param _.matchesProperty style callback + */ + partition( + path: string, + srcValue: any): LoDashArrayWrapper; + /** + * @see _.partition + * @param _.property style callback + */ + partition( + pluckValue: string): LoDashArrayWrapper; + } + //_.reduce interface LoDashStatic { /** From 3ece183e164a6ba0a071f4b5df5a22b046ee7ed1 Mon Sep 17 00:00:00 2001 From: yortus Date: Mon, 10 Aug 2015 18:37:41 +0800 Subject: [PATCH 065/614] remove KnexStatic, which is no longer used --- knex/knex.d.ts | 8 -------- 1 file changed, 8 deletions(-) diff --git a/knex/knex.d.ts b/knex/knex.d.ts index 5300cd3c4..c94d02f47 100644 --- a/knex/knex.d.ts +++ b/knex/knex.d.ts @@ -15,14 +15,6 @@ declare module "knex" { type Value = string|number|boolean|Date; type ColumnName = string|Raw|QueryBuilder; - module KnexStatic { - interface ConfigStatic { } - } - - interface KnexStatic { - (config: Config): Knex; - } - interface Knex extends QueryInterface { } interface Knex { From ac75761608d8ecdd59eed3269a76bfcd18955e9f Mon Sep 17 00:00:00 2001 From: yortus Date: Mon, 10 Aug 2015 18:44:38 +0800 Subject: [PATCH 066/614] export all interfaces by wrapping them in exported Knex namespace --- knex/knex.d.ts | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/knex/knex.d.ts b/knex/knex.d.ts index c94d02f47..1fb326c26 100644 --- a/knex/knex.d.ts +++ b/knex/knex.d.ts @@ -13,28 +13,29 @@ declare module "knex" { type Callback = Function; type Client = Function; type Value = string|number|boolean|Date; - type ColumnName = string|Raw|QueryBuilder; + type ColumnName = string|Knex.Raw|Knex.QueryBuilder; - interface Knex extends QueryInterface { } - - interface Knex { - (tableName?: string): QueryBuilder; + interface Knex extends Knex.QueryInterface { + (tableName?: string): Knex.QueryBuilder; VERSION: string; __knex__: string; - raw: RawBuilder; - transaction: (transactionScope: ((trx: Transaction) => void)) => Promise; + raw: Knex.RawBuilder; + transaction: (transactionScope: ((trx: Knex.Transaction) => void)) => Promise; destroy(callback: Function): void; destroy(): Promise; + schema: Knex.SchemaBuilder; + client: any; migrate: any; seed: any; fn: any; } - function Knex( config : Config ) : Knex; + function Knex( config : Knex.Config ) : Knex; + namespace Knex { // // QueryInterface // @@ -296,10 +297,6 @@ declare module "knex" { // Schema builder // - interface Knex { - schema: SchemaBuilder; - } - interface SchemaBuilder { createTable(tableName: string, callback: (tableBuilder: CreateTableBuilder) => any): Promise; renameTable(oldTableName: string, newTableName: string): Promise; @@ -448,6 +445,7 @@ declare module "knex" { extension?: string; tableName?: string; } + } export = Knex; } From bd876d257df35571a4e9cb601b4567653a01efdd Mon Sep 17 00:00:00 2001 From: yortus Date: Mon, 10 Aug 2015 18:46:53 +0800 Subject: [PATCH 067/614] fix indentation only (NO other changes) --- knex/knex.d.ts | 818 ++++++++++++++++++++++++------------------------- 1 file changed, 409 insertions(+), 409 deletions(-) diff --git a/knex/knex.d.ts b/knex/knex.d.ts index 1fb326c26..90514e7cb 100644 --- a/knex/knex.d.ts +++ b/knex/knex.d.ts @@ -36,415 +36,415 @@ declare module "knex" { function Knex( config : Knex.Config ) : Knex; namespace Knex { - // - // QueryInterface - // - - interface QueryInterface { - select: Select; - as: As; - columns: Select; - column: Select; - from: Table; - into: Table; - table: Table; - distinct: Distinct; - - // Joins - join: Join; - joinRaw: JoinRaw; - innerJoin: Join; - leftJoin: Join; - leftOuterJoin: Join; - rightJoin: Join; - rightOuterJoin: Join; - outerJoin: Join; - fullOuterJoin: Join; - crossJoin: Join; - - // Wheres - where: Where; - andWhere: Where; - orWhere: Where; - whereRaw: WhereRaw; - whereWrapped: WhereWrapped; - havingWrapped: WhereWrapped; - orWhereRaw: WhereRaw; - whereExists: WhereExists; - orWhereExists: WhereExists; - whereNotExists: WhereExists; - orWhereNotExists: WhereExists; - whereIn: WhereIn; - orWhereIn: WhereIn; - whereNotIn: WhereIn; - orWhereNotIn: WhereIn; - whereNull: WhereNull; - orWhereNull: WhereNull; - whereNotNull: WhereNull; - orWhereNotNull: WhereNull; - whereBetween: WhereBetween; - whereNotBetween: WhereBetween; - orWhereBetween: WhereBetween; - orWhereNotBetween: WhereBetween; - - // Group by - groupBy: GroupBy; - groupByRaw: RawQueryBuilder; - - // Order by - orderBy: OrderBy; - orderByRaw: RawQueryBuilder; - - // Union - union: Union; - unionAll(callback: Function): QueryBuilder; - - // Having - having: Having; - havingRaw: RawQueryBuilder; - orHaving: Having; - orHavingRaw: RawQueryBuilder; - - // Paging - offset(offset: number): QueryBuilder; - limit(limit: number): QueryBuilder; - - // Aggregation - count(columnName?: string): QueryBuilder; - min(columnName: string): QueryBuilder; - max(columnName: string): QueryBuilder; - sum(columnName: string): QueryBuilder; - avg(columnName: string): QueryBuilder; - increment(columnName: string, amount?: number): QueryBuilder; - decrement(columnName: string, amount?: number): QueryBuilder; - - // Others - first(...columns: string[]): QueryBuilder; - - debug(enabled?: boolean): QueryBuilder; - pluck(column: string): QueryBuilder; - - insert(data: any, returning?: string | string[]): QueryBuilder; - update(data: any, returning?: string | string[]): QueryBuilder; - update(columnName: string, value: Value, returning?: string | string[]): QueryBuilder; - returning(column: string): QueryBuilder; - - del(returning?: string | string[]): QueryBuilder; - delete(returning?: string | string[]): QueryBuilder; - truncate(): QueryBuilder; - - transacting(trx: Transaction): QueryBuilder; - connection(connection: any): QueryBuilder; - } - - interface As { - (columnName: string): QueryBuilder; - } - - interface Select extends ColumnNameQueryBuilder { - } - - interface Table { - (tableName: string): QueryBuilder; - (callback: Function): QueryBuilder; - } - - interface Distinct extends ColumnNameQueryBuilder { - } - - interface Join { - (raw: Raw): QueryBuilder; - (tableName: string, callback: Function): QueryBuilder; - (tableName: string, column1: string, column2: string): QueryBuilder; - (tableName: string, column1: string, raw: Raw): QueryBuilder; - (tableName: string, column1: string, operator: string, column2: string): QueryBuilder; - } - - interface JoinRaw { - (tableName: string, binding?: Value): QueryBuilder; - } - - interface Where extends WhereRaw, WhereWrapped, WhereNull { - (object: Object): QueryBuilder; - (columnName: string, value: Value): QueryBuilder; - (columnName: string, operator: string, value: Value): QueryBuilder; - (columnName: string, operator: string, query: QueryBuilder): QueryBuilder; - } - - interface WhereRaw extends RawQueryBuilder { - (condition: boolean): QueryBuilder; - } - - interface WhereWrapped { - (callback: Function): QueryBuilder; - } - - interface WhereNull { - (columnName: string): QueryBuilder; - } - - interface WhereIn { - (columnName: string, values: Value[]): QueryBuilder; - (columnName: string, callback: Function): QueryBuilder; - (columnName: string, query: QueryBuilder): QueryBuilder; - } - - interface WhereBetween { - (columnName: string, range: [Value, Value]): QueryBuilder; - } - - interface WhereExists { - (callback: Function): QueryBuilder; - (query: QueryBuilder): QueryBuilder; - } - - interface WhereNull { - (columnName: string): QueryBuilder; - } - - interface WhereIn { - (columnName: string, values: Value[]): QueryBuilder; - } - - interface GroupBy extends RawQueryBuilder, ColumnNameQueryBuilder { - } - - interface OrderBy { - (columnName: string, direction?: string): QueryBuilder; - } - - interface Union { - (callback: Function, wrap?: boolean): QueryBuilder; - (callbacks: Function[], wrap?: boolean): QueryBuilder; - (...callbacks: Function[]): QueryBuilder; - // (...callbacks: Function[], wrap?: boolean): QueryInterface; - } - - interface Having extends RawQueryBuilder, WhereWrapped { - (tableName: string, column1: string, operator: string, column2: string): QueryBuilder; - } - - // commons - - interface ColumnNameQueryBuilder { - (...columnNames: ColumnName[]): QueryBuilder; - (columnNames: ColumnName[]): QueryBuilder; - } - - interface RawQueryBuilder { - (sql: string, ...bindings: Value[]): QueryBuilder; - (sql: string, bindings: Value[]): QueryBuilder; - (raw: Raw): QueryBuilder; - } - - // Raw - - interface Raw extends events.EventEmitter, ChainableInterface { - wrap(before: string, after: string): Raw; - } - - interface RawBuilder { - (value: Value): Raw; - (sql: string, ...bindings: Value[]): Raw; - (sql: string, bindings: Value[]): Raw; - } - - // - // QueryBuilder - // - - interface QueryBuilder extends QueryInterface, ChainableInterface { - or: QueryBuilder; - and: QueryBuilder; - - //TODO: Promise? - columnInfo(column?: string): Promise; - - forUpdate(): QueryBuilder; - forShare(): QueryBuilder; - - toSQL(): Sql; - - on(event: string, callback: Function): QueryBuilder; - } - - interface Sql { - method: string; - options: any; - bindings: Value[]; - sql: string; - } - - // - // Chainable interface - // - - interface ChainableInterface extends Promise { - toQuery(): string; - options(options: any): QueryBuilder; - stream(options?: any, callback?: (builder: QueryBuilder) => any): QueryBuilder; - stream(callback?: (builder: QueryBuilder) => any): QueryBuilder; - pipe(writable: any): QueryBuilder; - exec(callback: Function): QueryBuilder; - } - - interface Transaction extends QueryBuilder { - commit: any; - rollback: any; - } - - // - // Schema builder - // - - interface SchemaBuilder { - createTable(tableName: string, callback: (tableBuilder: CreateTableBuilder) => any): Promise; - renameTable(oldTableName: string, newTableName: string): Promise; - dropTable(tableName: string): Promise; - hasTable(tableName: string): Promise; - hasColumn(tableName: string, columnName: string): Promise; - table(tableName: string, callback: (tableBuilder: AlterTableBuilder) => any): Promise; - dropTableIfExists(tableName: string): Promise; - raw(statement: string): SchemaBuilder; - } - - interface TableBuilder { - increments(columnName?: string): ColumnBuilder; - dropColumn(columnName: string): TableBuilder; - dropColumns(...columnNames: string[]): TableBuilder; - renameColumn(from: string, to: string): ColumnBuilder; - integer(columnName: string): ColumnBuilder; - bigInteger(columnName: string): ColumnBuilder; - text(columnName: string, textType?: string): ColumnBuilder; - string(columnName: string, length?: number): ColumnBuilder; - float(columnName: string, precision?: number, scale?: number): ColumnBuilder; - decimal(columnName: string, precision?: number, scale?: number): ColumnBuilder; - boolean(columnName: string): ColumnBuilder; - date(columnName: string): ColumnBuilder; - dateTime(columnName: string): ColumnBuilder; - time(columnName: string): ColumnBuilder; - timestamp(columnName: string): ColumnBuilder; - timestamps(): ColumnBuilder; - binary(columnName: string): ColumnBuilder; - enum(columnName: string): ColumnBuilder; - enu(columnName: string): ColumnBuilder; - json(columnName: string): ColumnBuilder; - uuid(columnName: string): ColumnBuilder; - comment(val: string): TableBuilder; - specificType(columnName: string, type: string): ColumnBuilder; - primary(columnNames: string[]) : TableBuilder; - index(columnNames: string[], indexName?: string, indexType?: string) : TableBuilder; - unique(columnNames: string[], indexName?: string) : TableBuilder; - } - - interface CreateTableBuilder extends TableBuilder { - } - - interface MySqlTableBuilder extends CreateTableBuilder { - engine(val: string): CreateTableBuilder; - charset(val: string): CreateTableBuilder; - collate(val: string): CreateTableBuilder; - } - - interface AlterTableBuilder extends TableBuilder { - } - - interface MySqlAlterTableBuilder extends AlterTableBuilder { - } - - interface ColumnBuilder { - index(indexName?: string): ColumnBuilder; - primary(): ColumnBuilder; - unique(): ColumnBuilder; - references(columnName: string): ReferencingColumnBuilder; - onDelete(command: string): ColumnBuilder; - onUpdate(command: string): ColumnBuilder; - defaultTo(value: Value): ColumnBuilder; - unsigned(): ColumnBuilder; - notNullable(): ColumnBuilder; - nullable(): ColumnBuilder; - comment(value: string): ColumnBuilder; - } - - interface PostgreSqlColumnBuilder extends ColumnBuilder { - index(indexName?: string, indexType?: string): ColumnBuilder; - } - - interface ReferencingColumnBuilder { - inTable(tableName: string): ColumnBuilder; - } - - interface AlterColumnBuilder extends ColumnBuilder { - } - - interface MySqlAlterColumnBuilder extends AlterColumnBuilder { - first(): AlterColumnBuilder; - after(columnName: string): AlterColumnBuilder; - } - - // - // Configurations - // - - interface ColumnInfo { - defaultValue: Value; - type: string; - maxLength: number; - nullable: boolean; - } - - interface Config { - client?: string; - dialect?: string; - connection: string|ConnectionConfig| - Sqlite3ConnectionConfig|SocketConnectionConfig; - pool?: PoolConfig; - migrations?: MigrationConfig; - } - - interface ConnectionConfig { - host: string; - user: string; - password: string; - database: string; - debug?: boolean; - } - - /** Used with SQLite3 adapter */ - interface Sqlite3ConnectionConfig { - filename: string; - debug?: boolean; - } - - interface SocketConnectionConfig { - socketPath: string; - user: string; - password: string; - database: string; - debug?: boolean; - } - - interface PoolConfig { - name?: string; - create?: Function; - destroy?: Function; - min?: number; - max?: number; - refreshIdle?: boolean; - idleTimeoutMillis?: number; - reapIntervalMillis?: number; - returnToHead?: boolean; - priorityRange?: number; - validate?: Function; - log?: boolean; - } - - interface MigrationConfig { - database?: string; - directory?: string; - extension?: string; - tableName?: string; - } + // + // QueryInterface + // + + interface QueryInterface { + select: Select; + as: As; + columns: Select; + column: Select; + from: Table; + into: Table; + table: Table; + distinct: Distinct; + + // Joins + join: Join; + joinRaw: JoinRaw; + innerJoin: Join; + leftJoin: Join; + leftOuterJoin: Join; + rightJoin: Join; + rightOuterJoin: Join; + outerJoin: Join; + fullOuterJoin: Join; + crossJoin: Join; + + // Wheres + where: Where; + andWhere: Where; + orWhere: Where; + whereRaw: WhereRaw; + whereWrapped: WhereWrapped; + havingWrapped: WhereWrapped; + orWhereRaw: WhereRaw; + whereExists: WhereExists; + orWhereExists: WhereExists; + whereNotExists: WhereExists; + orWhereNotExists: WhereExists; + whereIn: WhereIn; + orWhereIn: WhereIn; + whereNotIn: WhereIn; + orWhereNotIn: WhereIn; + whereNull: WhereNull; + orWhereNull: WhereNull; + whereNotNull: WhereNull; + orWhereNotNull: WhereNull; + whereBetween: WhereBetween; + whereNotBetween: WhereBetween; + orWhereBetween: WhereBetween; + orWhereNotBetween: WhereBetween; + + // Group by + groupBy: GroupBy; + groupByRaw: RawQueryBuilder; + + // Order by + orderBy: OrderBy; + orderByRaw: RawQueryBuilder; + + // Union + union: Union; + unionAll(callback: Function): QueryBuilder; + + // Having + having: Having; + havingRaw: RawQueryBuilder; + orHaving: Having; + orHavingRaw: RawQueryBuilder; + + // Paging + offset(offset: number): QueryBuilder; + limit(limit: number): QueryBuilder; + + // Aggregation + count(columnName?: string): QueryBuilder; + min(columnName: string): QueryBuilder; + max(columnName: string): QueryBuilder; + sum(columnName: string): QueryBuilder; + avg(columnName: string): QueryBuilder; + increment(columnName: string, amount?: number): QueryBuilder; + decrement(columnName: string, amount?: number): QueryBuilder; + + // Others + first(...columns: string[]): QueryBuilder; + + debug(enabled?: boolean): QueryBuilder; + pluck(column: string): QueryBuilder; + + insert(data: any, returning?: string | string[]): QueryBuilder; + update(data: any, returning?: string | string[]): QueryBuilder; + update(columnName: string, value: Value, returning?: string | string[]): QueryBuilder; + returning(column: string): QueryBuilder; + + del(returning?: string | string[]): QueryBuilder; + delete(returning?: string | string[]): QueryBuilder; + truncate(): QueryBuilder; + + transacting(trx: Transaction): QueryBuilder; + connection(connection: any): QueryBuilder; + } + + interface As { + (columnName: string): QueryBuilder; + } + + interface Select extends ColumnNameQueryBuilder { + } + + interface Table { + (tableName: string): QueryBuilder; + (callback: Function): QueryBuilder; + } + + interface Distinct extends ColumnNameQueryBuilder { + } + + interface Join { + (raw: Raw): QueryBuilder; + (tableName: string, callback: Function): QueryBuilder; + (tableName: string, column1: string, column2: string): QueryBuilder; + (tableName: string, column1: string, raw: Raw): QueryBuilder; + (tableName: string, column1: string, operator: string, column2: string): QueryBuilder; + } + + interface JoinRaw { + (tableName: string, binding?: Value): QueryBuilder; + } + + interface Where extends WhereRaw, WhereWrapped, WhereNull { + (object: Object): QueryBuilder; + (columnName: string, value: Value): QueryBuilder; + (columnName: string, operator: string, value: Value): QueryBuilder; + (columnName: string, operator: string, query: QueryBuilder): QueryBuilder; + } + + interface WhereRaw extends RawQueryBuilder { + (condition: boolean): QueryBuilder; + } + + interface WhereWrapped { + (callback: Function): QueryBuilder; + } + + interface WhereNull { + (columnName: string): QueryBuilder; + } + + interface WhereIn { + (columnName: string, values: Value[]): QueryBuilder; + (columnName: string, callback: Function): QueryBuilder; + (columnName: string, query: QueryBuilder): QueryBuilder; + } + + interface WhereBetween { + (columnName: string, range: [Value, Value]): QueryBuilder; + } + + interface WhereExists { + (callback: Function): QueryBuilder; + (query: QueryBuilder): QueryBuilder; + } + + interface WhereNull { + (columnName: string): QueryBuilder; + } + + interface WhereIn { + (columnName: string, values: Value[]): QueryBuilder; + } + + interface GroupBy extends RawQueryBuilder, ColumnNameQueryBuilder { + } + + interface OrderBy { + (columnName: string, direction?: string): QueryBuilder; + } + + interface Union { + (callback: Function, wrap?: boolean): QueryBuilder; + (callbacks: Function[], wrap?: boolean): QueryBuilder; + (...callbacks: Function[]): QueryBuilder; + // (...callbacks: Function[], wrap?: boolean): QueryInterface; + } + + interface Having extends RawQueryBuilder, WhereWrapped { + (tableName: string, column1: string, operator: string, column2: string): QueryBuilder; + } + + // commons + + interface ColumnNameQueryBuilder { + (...columnNames: ColumnName[]): QueryBuilder; + (columnNames: ColumnName[]): QueryBuilder; + } + + interface RawQueryBuilder { + (sql: string, ...bindings: Value[]): QueryBuilder; + (sql: string, bindings: Value[]): QueryBuilder; + (raw: Raw): QueryBuilder; + } + + // Raw + + interface Raw extends events.EventEmitter, ChainableInterface { + wrap(before: string, after: string): Raw; + } + + interface RawBuilder { + (value: Value): Raw; + (sql: string, ...bindings: Value[]): Raw; + (sql: string, bindings: Value[]): Raw; + } + + // + // QueryBuilder + // + + interface QueryBuilder extends QueryInterface, ChainableInterface { + or: QueryBuilder; + and: QueryBuilder; + + //TODO: Promise? + columnInfo(column?: string): Promise; + + forUpdate(): QueryBuilder; + forShare(): QueryBuilder; + + toSQL(): Sql; + + on(event: string, callback: Function): QueryBuilder; + } + + interface Sql { + method: string; + options: any; + bindings: Value[]; + sql: string; + } + + // + // Chainable interface + // + + interface ChainableInterface extends Promise { + toQuery(): string; + options(options: any): QueryBuilder; + stream(options?: any, callback?: (builder: QueryBuilder) => any): QueryBuilder; + stream(callback?: (builder: QueryBuilder) => any): QueryBuilder; + pipe(writable: any): QueryBuilder; + exec(callback: Function): QueryBuilder; + } + + interface Transaction extends QueryBuilder { + commit: any; + rollback: any; + } + + // + // Schema builder + // + + interface SchemaBuilder { + createTable(tableName: string, callback: (tableBuilder: CreateTableBuilder) => any): Promise; + renameTable(oldTableName: string, newTableName: string): Promise; + dropTable(tableName: string): Promise; + hasTable(tableName: string): Promise; + hasColumn(tableName: string, columnName: string): Promise; + table(tableName: string, callback: (tableBuilder: AlterTableBuilder) => any): Promise; + dropTableIfExists(tableName: string): Promise; + raw(statement: string): SchemaBuilder; + } + + interface TableBuilder { + increments(columnName?: string): ColumnBuilder; + dropColumn(columnName: string): TableBuilder; + dropColumns(...columnNames: string[]): TableBuilder; + renameColumn(from: string, to: string): ColumnBuilder; + integer(columnName: string): ColumnBuilder; + bigInteger(columnName: string): ColumnBuilder; + text(columnName: string, textType?: string): ColumnBuilder; + string(columnName: string, length?: number): ColumnBuilder; + float(columnName: string, precision?: number, scale?: number): ColumnBuilder; + decimal(columnName: string, precision?: number, scale?: number): ColumnBuilder; + boolean(columnName: string): ColumnBuilder; + date(columnName: string): ColumnBuilder; + dateTime(columnName: string): ColumnBuilder; + time(columnName: string): ColumnBuilder; + timestamp(columnName: string): ColumnBuilder; + timestamps(): ColumnBuilder; + binary(columnName: string): ColumnBuilder; + enum(columnName: string): ColumnBuilder; + enu(columnName: string): ColumnBuilder; + json(columnName: string): ColumnBuilder; + uuid(columnName: string): ColumnBuilder; + comment(val: string): TableBuilder; + specificType(columnName: string, type: string): ColumnBuilder; + primary(columnNames: string[]) : TableBuilder; + index(columnNames: string[], indexName?: string, indexType?: string) : TableBuilder; + unique(columnNames: string[], indexName?: string) : TableBuilder; + } + + interface CreateTableBuilder extends TableBuilder { + } + + interface MySqlTableBuilder extends CreateTableBuilder { + engine(val: string): CreateTableBuilder; + charset(val: string): CreateTableBuilder; + collate(val: string): CreateTableBuilder; + } + + interface AlterTableBuilder extends TableBuilder { + } + + interface MySqlAlterTableBuilder extends AlterTableBuilder { + } + + interface ColumnBuilder { + index(indexName?: string): ColumnBuilder; + primary(): ColumnBuilder; + unique(): ColumnBuilder; + references(columnName: string): ReferencingColumnBuilder; + onDelete(command: string): ColumnBuilder; + onUpdate(command: string): ColumnBuilder; + defaultTo(value: Value): ColumnBuilder; + unsigned(): ColumnBuilder; + notNullable(): ColumnBuilder; + nullable(): ColumnBuilder; + comment(value: string): ColumnBuilder; + } + + interface PostgreSqlColumnBuilder extends ColumnBuilder { + index(indexName?: string, indexType?: string): ColumnBuilder; + } + + interface ReferencingColumnBuilder { + inTable(tableName: string): ColumnBuilder; + } + + interface AlterColumnBuilder extends ColumnBuilder { + } + + interface MySqlAlterColumnBuilder extends AlterColumnBuilder { + first(): AlterColumnBuilder; + after(columnName: string): AlterColumnBuilder; + } + + // + // Configurations + // + + interface ColumnInfo { + defaultValue: Value; + type: string; + maxLength: number; + nullable: boolean; + } + + interface Config { + client?: string; + dialect?: string; + connection: string|ConnectionConfig| + Sqlite3ConnectionConfig|SocketConnectionConfig; + pool?: PoolConfig; + migrations?: MigrationConfig; + } + + interface ConnectionConfig { + host: string; + user: string; + password: string; + database: string; + debug?: boolean; + } + + /** Used with SQLite3 adapter */ + interface Sqlite3ConnectionConfig { + filename: string; + debug?: boolean; + } + + interface SocketConnectionConfig { + socketPath: string; + user: string; + password: string; + database: string; + debug?: boolean; + } + + interface PoolConfig { + name?: string; + create?: Function; + destroy?: Function; + min?: number; + max?: number; + refreshIdle?: boolean; + idleTimeoutMillis?: number; + reapIntervalMillis?: number; + returnToHead?: boolean; + priorityRange?: number; + validate?: Function; + log?: boolean; + } + + interface MigrationConfig { + database?: string; + directory?: string; + extension?: string; + tableName?: string; + } } export = Knex; From 1bdaa7d80f2df2588afbcf5ae9f5c8f069af1784 Mon Sep 17 00:00:00 2001 From: yortus Date: Mon, 10 Aug 2015 19:02:16 +0800 Subject: [PATCH 068/614] spacing (no code changes) Added this commit purely to trigger first CI build as per contribution guidelines. --- knex/knex.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/knex/knex.d.ts b/knex/knex.d.ts index 90514e7cb..82dda6bf2 100644 --- a/knex/knex.d.ts +++ b/knex/knex.d.ts @@ -33,7 +33,7 @@ declare module "knex" { fn: any; } - function Knex( config : Knex.Config ) : Knex; + function Knex(config: Knex.Config) : Knex; namespace Knex { // From 52854d5f1c46796481428d3ab7be722b6c47c869 Mon Sep 17 00:00:00 2001 From: Greg Smith Date: Mon, 10 Aug 2015 13:17:20 -0500 Subject: [PATCH 069/614] 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 a7e09ad3d735a45e41e9b0f557ce779d8d99b3fa Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Mon, 10 Aug 2015 16:49:00 -0700 Subject: [PATCH 070/614] Add 'dataMap' to 'amplifyjs'. --- amplifyjs/amplifyjs.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/amplifyjs/amplifyjs.d.ts b/amplifyjs/amplifyjs.d.ts index 30e827294..961d815c6 100644 --- a/amplifyjs/amplifyjs.d.ts +++ b/amplifyjs/amplifyjs.d.ts @@ -29,6 +29,7 @@ interface amplifyDecoders { interface amplifyAjaxSettings extends JQueryAjaxSettings { cache?: any; + dataMap?: {} | ((data: any) => {}); decoder?: any /* string or amplifyDecoder */; } From e8c0ad7b0b1f70f401b4dc0064713206aa83f0a8 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Mon, 10 Aug 2015 16:51:53 -0700 Subject: [PATCH 071/614] IMetadata shouldn't extend Object in 'stripe'. --- stripe/stripe-node.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/stripe/stripe-node.d.ts b/stripe/stripe-node.d.ts index cb5932086..d41fdc13e 100644 --- a/stripe/stripe-node.d.ts +++ b/stripe/stripe-node.d.ts @@ -2802,7 +2802,7 @@ declare module StripeNode { * A set of key/value pairs that you can attach to a reversal. It can be useful for storing * additional information about the reversal in a structured format. */ - interface IMetadata extends Object { } + interface IMetadata { } interface IShippingInformation { /** From 9601565ddf89ef6895d4cb414e622f3ddb196665 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Mon, 10 Aug 2015 16:56:39 -0700 Subject: [PATCH 072/614] instance -> instanceName in tests for 'tedious'. --- tedious/tedious-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tedious/tedious-tests.ts b/tedious/tedious-tests.ts index 32c243614..f7346a174 100644 --- a/tedious/tedious-tests.ts +++ b/tedious/tedious-tests.ts @@ -11,7 +11,7 @@ var config: tedious.ConnectionConfig = { server: "127.0.0.1", options: { database: "somedb", - instance: "someinstance" + instanceName: "someinstance", } } From dbfb98a84c40956e7326764c04b850cd61d318c5 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Mon, 10 Aug 2015 17:07:22 -0700 Subject: [PATCH 073/614] Added missing properties to constructor options bag in 'vinyl'. --- vinyl/vinyl.d.ts | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/vinyl/vinyl.d.ts b/vinyl/vinyl.d.ts index 81aa781f9..4dd8016a5 100644 --- a/vinyl/vinyl.d.ts +++ b/vinyl/vinyl.d.ts @@ -27,9 +27,18 @@ declare module 'vinyl' { */ path?: string; /** - * Type: Buffer|Stream|null (Default: null) + * Path history. Has no effect if options.path is passed. */ - contents?: any; + history?: string[]; + /** + * The result of an fs.stat call. See fs.Stats for more information. + */ + stat?: fs.Stats; + /** + * File contents. + * Type: Buffer, Stream, or null + */ + contents?: Buffer | NodeJS.ReadWriteStream; }); /** @@ -48,7 +57,7 @@ declare module 'vinyl' { /** * Type: Buffer|Stream|null (Default: null) */ - public contents: any; + public contents: Buffer | NodeJS.ReadableStream; /** * Returns path.relative for the file base and file path. * Example: From d12fbb3b8159e326ece4fae84d40aae4f979fb58 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Mon, 10 Aug 2015 17:20:42 -0700 Subject: [PATCH 074/614] Added 'scales' to 'Mark' in 'vega'. --- vega/vega.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/vega/vega.d.ts b/vega/vega.d.ts index ebe89da02..3a959fe1c 100644 --- a/vega/vega.d.ts +++ b/vega/vega.d.ts @@ -369,6 +369,7 @@ declare module Vega { properties?: PropertySets; key?: string; delay?: ValueRef; + scales?: Scale[]; } export module Mark { From b0c077fdd39f2b901677a5d58155f516f66f88d1 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Mon, 10 Aug 2015 18:15:51 -0700 Subject: [PATCH 075/614] 'Selector' shouldn't extend 'Object' in 'meteor'. --- meteor/meteor.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/meteor/meteor.d.ts b/meteor/meteor.d.ts index ed0c97b29..2028cc266 100644 --- a/meteor/meteor.d.ts +++ b/meteor/meteor.d.ts @@ -134,7 +134,7 @@ declare module Meteor { } declare module Mongo { - interface Selector extends Object {} + interface Selector {} interface Modifier {} interface SortSpecifier {} interface FieldSpecifier { From 78ee8f994726b3f63a6c986efa5e0b0d7b4a9044 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Mon, 10 Aug 2015 18:30:32 -0700 Subject: [PATCH 076/614] Added 'views' to 'backbone.layoutmanager'. --- backbone.layoutmanager/backbone.layoutmanager.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/backbone.layoutmanager/backbone.layoutmanager.d.ts b/backbone.layoutmanager/backbone.layoutmanager.d.ts index 6c830d0ba..5ce548157 100644 --- a/backbone.layoutmanager/backbone.layoutmanager.d.ts +++ b/backbone.layoutmanager/backbone.layoutmanager.d.ts @@ -11,6 +11,7 @@ declare module Backbone { interface LayoutOptions extends ViewOptions { template?: string; + views?: { [viewName: string]: View }; } interface LayoutManagerOptions { From 985e4ccf0421a8a01dfe42631bba218ae546a3a0 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Mon, 10 Aug 2015 18:39:10 -0700 Subject: [PATCH 077/614] Actually use the options object in 'backgrid'. --- backgrid/backgrid.d.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/backgrid/backgrid.d.ts b/backgrid/backgrid.d.ts index 3a75e6142..d0ddc3e51 100644 --- a/backgrid/backgrid.d.ts +++ b/backgrid/backgrid.d.ts @@ -10,10 +10,10 @@ declare module Backgrid { interface GridOptions { columns: Column[]; collection: Backbone.Collection; - header: Header; - body: Body; - row: Row; - footer: Footer; + header?: Header; + body?: Body; + row?: Row; + footer?: Footer; } class Header extends Backbone.View { @@ -109,6 +109,8 @@ declare module Backgrid { header: any; tagName: string; + constructor(options: GridOptions); + initialize(options: any); getSelectedModels(): Backbone.Model[]; insertColumn(...options: any[]): Grid; From 14590ab303399ad1f07f3981183d72970ba78379 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Tue, 11 Aug 2015 12:32:46 -0700 Subject: [PATCH 078/614] 'overlay' is not a documented member of the dialog options in jQuery UI, so remove it in tests for 'chrome'. --- chrome/chrome-tests.ts | 4 ---- 1 file changed, 4 deletions(-) diff --git a/chrome/chrome-tests.ts b/chrome/chrome-tests.ts index cbbe93791..f4e208d89 100644 --- a/chrome/chrome-tests.ts +++ b/chrome/chrome-tests.ts @@ -60,10 +60,6 @@ function bookmarksExample() { resizable: false, height: 140, modal: true, - overlay: { - backgroundColor: '#000', - opacity: 0.5 - }, buttons: { 'Yes, Delete It!': function () { chrome.bookmarks.remove(String(bookmarkNode.id)); From d35c03133170ce5126f5f9322a1599430233b2e3 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Tue, 11 Aug 2015 12:40:44 -0700 Subject: [PATCH 079/614] Use union types where appropriately hinted in 'ckeditor'. --- ckeditor/ckeditor.d.ts | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/ckeditor/ckeditor.d.ts b/ckeditor/ckeditor.d.ts index 315f9bdf1..3bb90c760 100644 --- a/ckeditor/ckeditor.d.ts +++ b/ckeditor/ckeditor.d.ts @@ -628,7 +628,7 @@ declare module CKEDITOR { data: Function; defaults: Object; dialog: String; - downcast: any; // should be string | Function + downcast: string | Function; downcasts: Object; draggable: boolean; editables: Object; @@ -643,16 +643,16 @@ declare module CKEDITOR { styleToAllowedContentRules: Function; styleableElements: string; template: string; - upcast: any; // should be string | Function + upcast: string | Function; upcasts: Object; addClass(className: string): void; applyStyle(style: any): void; // any should be CKEDITOR.style capture(): void; checkStyleActive(style: any): boolean; // any should be CKEDITOR.style - define(name: string, meta: {errorProof?: boolean}): void; + define(name: string, meta: { errorProof?: boolean }): void; destroy(offline?: boolean): void; - destroyEditable(editableName:string, offline?: boolean): void; + destroyEditable(editableName: string, offline?: boolean): void; edit(): boolean; fire(eventName: string, data?: Object, editor?: editor): any; // should be boolean | Object fireOnce(eventName: string, data?: Object, editor?: editor): any; // should be boolean | Object @@ -670,7 +670,7 @@ declare module CKEDITOR { removeClass(className: string): void; removeListener(evnetName: string, listenerFunction: Function): void; removeStyle(style: any): void; // any should be CKEDITOR.style - setData(keyOrData: any, value?: Object): IWidget; // any should be string | Object + setData(keyOrData: string | {}, value?: Object): IWidget; setFocused(selected: boolean): IWidget; setSelected(selected: boolean): IWidget; toFeature(): any; // should be CKEDITOR.feature @@ -685,7 +685,7 @@ declare module CKEDITOR { data?: Function; defaults?: Object; dialog?: String; - downcast?: any; // should be string | Function + downcast?: string | Function; downcasts?: Object; draggable?: boolean; edit?: Function; @@ -701,7 +701,7 @@ declare module CKEDITOR { styleToAllowedContentRules?: Function; styleableElements?: string; template?: string; - upcast?: any; // should be string | Function + upcast?: string | Function; upcasts?: Object; toFeature?(): any; // should be CKEDITOR.feature } @@ -732,8 +732,8 @@ declare module CKEDITOR { interface IPluginDefinition { hidpi?: boolean; - lang?: any; // should be string | string[] - requires?: any; // should be string | string[]a + lang?: string | string[]; + requires?: string | string[]; afterInit?(editor: editor): any; beforeInit?(editor: editor): any; init?(editor: editor): any; From 8f8e362fc000a93615f3074a65b1e1797acb9854 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Tue, 11 Aug 2015 12:43:20 -0700 Subject: [PATCH 080/614] 'icons' is not a documented member for plugin definition objects in 'ckeditor'. --- ckeditor/ckeditor-tests.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/ckeditor/ckeditor-tests.ts b/ckeditor/ckeditor-tests.ts index aa052b8ee..f7deb6706 100644 --- a/ckeditor/ckeditor-tests.ts +++ b/ckeditor/ckeditor-tests.ts @@ -282,7 +282,6 @@ function test_adding_dialog_by_definition() { function test_adding_plugin() { CKEDITOR.plugins.add( 'abbr', { - icons: 'abbr', init: function( editor: CKEDITOR.editor ) { // empty logic } From a52c3885f8d6fa47a67aa2c1680ca0a1e2c40a4b Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Tue, 11 Aug 2015 14:22:43 -0700 Subject: [PATCH 081/614] Use 'lib.CipherParamsData' for create*cryptor in 'cryptojs'. --- cryptojs/cryptojs.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/cryptojs/cryptojs.d.ts b/cryptojs/cryptojs.d.ts index d9c77dbe9..a764ebada 100644 --- a/cryptojs/cryptojs.d.ts +++ b/cryptojs/cryptojs.d.ts @@ -127,12 +127,12 @@ declare module CryptoJS{ //BlockCipher has interface same as IStreamCipher interface BlockCipher extends IStreamCipher{} - interface IBlockCipherCfg{ + interface IBlockCipherCfg { mode?: mode.IBlockCipherModeImpl //default CBC padding?: pad.IPaddingImpl //default Pkcs7 } - interface CipherParamsData{ + interface CipherParamsData { ciphertext?: lib.WordArray key?: lib.WordArray iv?: lib.WordArray @@ -277,8 +277,8 @@ declare module CryptoJS{ encryptBlock(M: number[], offset: number): void decryptBlock(M: number[], offset: number): void - createEncryptor(key: lib.WordArray, cfg?: lib.IBlockCipherCfg): IBlockCipherImpl - createDecryptor(key: lib.WordArray, cfg?: lib.IBlockCipherCfg): IBlockCipherImpl + createEncryptor(key: lib.WordArray, cfg?: lib.CipherParamsData): IBlockCipherImpl + createDecryptor(key: lib.WordArray, cfg?: lib.CipherParamsData): IBlockCipherImpl create(xformMode?: number, key?: lib.WordArray, cfg?: lib.IBlockCipherCfg): IBlockCipherImpl } From e9a00d26d8cdea4de0e219a5e680c06ed1c123ac Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Tue, 11 Aug 2015 14:52:35 -0700 Subject: [PATCH 082/614] Add missing 'weight' property to labelAnchorLinks type in 'd3'. --- d3/d3-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/d3/d3-tests.ts b/d3/d3-tests.ts index d087c7876..105e8f29c 100644 --- a/d3/d3-tests.ts +++ b/d3/d3-tests.ts @@ -922,7 +922,7 @@ module forcedBasedLabelPlacemant { var nodes: Node[] = []; var labelAnchors: LabelAnchor[] = []; - var labelAnchorLinks: { source: number; target: number }[] = []; + var labelAnchorLinks: { source: number; target: number; weight: number }[] = []; var links: typeof labelAnchorLinks = []; for (var i = 0; i < 30; i++) { From 97f3794db2b2f624fa1001d7620b75cadb1fd9b1 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Tue, 11 Aug 2015 15:09:44 -0700 Subject: [PATCH 083/614] Add 'paramNames' to 'Object' in 'donna'. --- donna/donna.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/donna/donna.d.ts b/donna/donna.d.ts index fed09fa98..c953764d1 100644 --- a/donna/donna.d.ts +++ b/donna/donna.d.ts @@ -25,6 +25,7 @@ declare module DonnaTypes { type: string; name: string; bindingType: string; + paramNames?: string[]; classProperties?: any[]; prototypeProperties?: number[][]; doc?: string; From fc46cd7ac026e9c96d70f63b091ee72d43bf4aa0 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Tue, 11 Aug 2015 15:11:53 -0700 Subject: [PATCH 084/614] Add 'classes' property to options bag in 'drop'. --- drop/drop.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/drop/drop.d.ts b/drop/drop.d.ts index 85cfd0766..a48cb8fb3 100644 --- a/drop/drop.d.ts +++ b/drop/drop.d.ts @@ -22,6 +22,7 @@ declare module drop { content?: Element | string | ((drop?: Drop) => string) | ((drop?: Drop) => Element); position?: string; openOn?: string; + classes?: string; constrainToWindow?: boolean; constrainToScrollParent?: boolean; remove?: boolean; From c892b43ca46c0e12f656e468301ff1f73a8c2c10 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Tue, 11 Aug 2015 15:44:37 -0700 Subject: [PATCH 085/614] Add index signature to 'CoreObjectArguments' in 'ember'. --- ember/ember.d.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/ember/ember.d.ts b/ember/ember.d.ts index 00ea077dd..6a28a80fe 100644 --- a/ember/ember.d.ts +++ b/ember/ember.d.ts @@ -349,6 +349,8 @@ interface CoreObjectArguments { Override to implement teardown. **/ willDestroy?: Function; + + [propName: string]: any; } interface EnumerableConfigurationOptions { @@ -998,7 +1000,7 @@ declare module Ember { @static @param {Object} [args] - Object containing values to use within the new class **/ - static extend(args ?: CoreObjectArguments): T; + static extend(args?: CoreObjectArguments): T; /** Creates a new subclass. @method extend From b1d60d580d51b030d7300cc4fc87414523ccaff9 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Tue, 11 Aug 2015 16:16:20 -0700 Subject: [PATCH 086/614] Add missing properties to 'IDOMElementOptions' in 'famous'. --- famous/famous.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/famous/famous.d.ts b/famous/famous.d.ts index 8b05774d8..a02ac86f0 100644 --- a/famous/famous.d.ts +++ b/famous/famous.d.ts @@ -125,7 +125,13 @@ declare module "famous/dom-renderables" { } export interface IDOMElementOptions { + tagName?: string; + classes?: string[]; + attributes?: { [attributeName: string]: string }; + properties?: { [attributeName: string]: string }; + id?: string; content?: string; + cutout?: boolean; } } From 722357fe998fbaca34dad4c0030a3ccd6438bd07 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Tue, 11 Aug 2015 16:37:53 -0700 Subject: [PATCH 087/614] Account for callbacks in 'fancybox'. --- fancybox/fancybox-tests.ts | 2 +- fancybox/fancybox.d.ts | 22 +++++++++++----------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/fancybox/fancybox-tests.ts b/fancybox/fancybox-tests.ts index dce30bf43..d84a06815 100644 --- a/fancybox/fancybox-tests.ts +++ b/fancybox/fancybox-tests.ts @@ -116,7 +116,7 @@ $(".fancybox").fancybox({ } }); $(".fancybox").fancybox({ - beforeLoad: function () { + beforeLoad: () => { this.title = 'Image ' + (this.index + 1) + ' of ' + this.group.length + (this.title ? ' - ' + this.title : ''); } }); diff --git a/fancybox/fancybox.d.ts b/fancybox/fancybox.d.ts index 03a20bebf..7182f7cad 100644 --- a/fancybox/fancybox.d.ts +++ b/fancybox/fancybox.d.ts @@ -6,7 +6,7 @@ /// -interface FancyboxOptions { +interface FancyboxOptions extends FancyboxCallback { padding?: any; // number or [] margin?: any; // number or [] width?: any; // number or [] @@ -96,16 +96,16 @@ interface FancyboxMethods { } interface FancyboxCallback { - onCancel; - beforeLoad; - afterLoad; - beforeShow; - afterShow; - beforeClose; - afterClose; - onUpdate; - onPlayStart; - onPlayEnd; + onCancel?: Function; + beforeLoad?: Function; + afterLoad?: Function; + beforeShow?: Function; + afterShow?: Function; + beforeClose?: Function; + afterClose?: Function; + onUpdate?: Function; + onPlayStart?: Function; + onPlayEnd?: Function; } interface FancyboxThumbnailHelperOptions { From a7fb3bdf5cec0992215e6fa54f874934ba2f9f84 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Tue, 11 Aug 2015 17:00:59 -0700 Subject: [PATCH 088/614] Add 'inputClass' to 'jquery.uniform'. --- jquery.uniform/jquery.uniform.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/jquery.uniform/jquery.uniform.d.ts b/jquery.uniform/jquery.uniform.d.ts index 4b3ff0d0d..ac622e42c 100644 --- a/jquery.uniform/jquery.uniform.d.ts +++ b/jquery.uniform/jquery.uniform.d.ts @@ -22,6 +22,7 @@ interface UniformOptions { hoverClass?: string; idPrefix?: string; inputAddTypeAsClass?: boolean; + inputClass?: string; radioClass?: string; resetDefaultHtml?: string; resetSelector?: any; From 996944493fedb2b8d7ec7b7ec506a19964845c6c Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Tue, 11 Aug 2015 17:02:18 -0700 Subject: [PATCH 089/614] Add index signature to options parameter of 'uniform'. --- jquery.uniform/jquery.uniform.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jquery.uniform/jquery.uniform.d.ts b/jquery.uniform/jquery.uniform.d.ts index ac622e42c..e91a41c93 100644 --- a/jquery.uniform/jquery.uniform.d.ts +++ b/jquery.uniform/jquery.uniform.d.ts @@ -35,7 +35,7 @@ interface UniformOptions { wrapperClass?: string; } interface Uniform { - (options?: UniformOptions): JQuery; + (options?: UniformOptions & {[option: string]: any;}): JQuery; update(elemOrSelector?: any): void; restore(elemOrSelector?: any): void; elements: JQuery[]; From 26e110353dd64d6198dd482daa849753e0f3fc6a Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Tue, 11 Aug 2015 17:10:26 -0700 Subject: [PATCH 090/614] Make options interfaces extend events interfaces in 'jqueryui'. --- jqueryui/jqueryui.d.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/jqueryui/jqueryui.d.ts b/jqueryui/jqueryui.d.ts index 10a4e7159..24f64ef34 100644 --- a/jqueryui/jqueryui.d.ts +++ b/jqueryui/jqueryui.d.ts @@ -398,7 +398,7 @@ declare module JQueryUI { (event: Event, ui: DraggableEventUIParams): void; } - interface DraggableOptions { + interface DraggableOptions extends DraggableEvents { disabled?: boolean; addClasses?: boolean; appendTo?: any; @@ -453,7 +453,7 @@ declare module JQueryUI { (event: Event, ui: DroppableEventUIParam): void; } - interface DroppableOptions { + interface DroppableOptions extends DroppableEvents { disabled?: boolean; accept?: any; activeClass?: string; @@ -472,7 +472,7 @@ declare module JQueryUI { drop?: DroppableEvent; } - interface Droppable extends Widget, DroppableOptions, DroppableEvents { + interface Droppable extends Widget, DroppableOptions { } // Menu ////////////////////////////////////////////////// @@ -577,7 +577,7 @@ declare module JQueryUI { // Selectable ////////////////////////////////////////////////// - interface SelectableOptions { + interface SelectableOptions extends SelectableEvents { autoRefresh?: boolean; cancel?: string; delay?: number; @@ -596,7 +596,7 @@ declare module JQueryUI { unselecting? (event: Event, ui: { unselecting: Element; }): void; } - interface Selectable extends Widget, SelectableOptions, SelectableEvents { + interface Selectable extends Widget, SelectableOptions { } // Slider ////////////////////////////////////////////////// From 612ad67a79b2bdc330255d1a1739ac50e9acc805 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Tue, 11 Aug 2015 17:14:02 -0700 Subject: [PATCH 091/614] Add 'helper' for 'Sortable' in 'jqueryui'. --- jqueryui/jqueryui.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/jqueryui/jqueryui.d.ts b/jqueryui/jqueryui.d.ts index 24f64ef34..9d8d17097 100644 --- a/jqueryui/jqueryui.d.ts +++ b/jqueryui/jqueryui.d.ts @@ -652,6 +652,7 @@ declare module JQueryUI { forceHelperSize?: boolean; forcePlaceholderSize?: boolean; grid?: number[]; + helper?: string | ((event: Event, element: Sortable) => Element); handle?: any; // Selector or Element items?: any; // Selector opacity?: number; From 98f5ec12f00101da94209f93d4dbc5801c16748e Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Tue, 11 Aug 2015 17:22:40 -0700 Subject: [PATCH 092/614] Added 'sortable' overload for 'serialize' method in 'jqueryui'. --- jqueryui/jqueryui.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/jqueryui/jqueryui.d.ts b/jqueryui/jqueryui.d.ts index 9d8d17097..f0c8ac09f 100644 --- a/jqueryui/jqueryui.d.ts +++ b/jqueryui/jqueryui.d.ts @@ -1660,6 +1660,7 @@ interface JQuery { sortable(methodName: string): JQuery; sortable(options: JQueryUI.SortableOptions): JQuery; sortable(optionLiteral: string, optionName: string): any; + sortable(methodName: 'serialize', options: { key?: string; attribute?: string; expression?: RegExp }); sortable(optionLiteral: string, options: JQueryUI.SortableOptions): any; sortable(optionLiteral: string, optionName: string, optionValue: any): JQuery; From 9d15a87ca0a067db2d10d6cae8cf4ec9407aa1cb Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Tue, 11 Aug 2015 17:24:45 -0700 Subject: [PATCH 093/614] Make options for resizable extend events in 'jqueryui'. --- jqueryui/jqueryui.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/jqueryui/jqueryui.d.ts b/jqueryui/jqueryui.d.ts index f0c8ac09f..c4b9fc17c 100644 --- a/jqueryui/jqueryui.d.ts +++ b/jqueryui/jqueryui.d.ts @@ -529,7 +529,7 @@ declare module JQueryUI { // Resizable ////////////////////////////////////////////////// - interface ResizableOptions { + interface ResizableOptions extends ResizableEvents { alsoResize?: any; // Selector, JQuery or Element animate?: boolean; animateDuration?: any; // number or string @@ -571,7 +571,7 @@ declare module JQueryUI { stop?: ResizableEvent; } - interface Resizable extends Widget, ResizableOptions, ResizableEvents { + interface Resizable extends Widget, ResizableOptions { } From 8d1b81107ccc40ad8dad9e5ce76ca67542fc5256 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Tue, 11 Aug 2015 17:26:06 -0700 Subject: [PATCH 094/614] Make autocomplete options extend events in 'jqueryui'. --- jqueryui/jqueryui.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/jqueryui/jqueryui.d.ts b/jqueryui/jqueryui.d.ts index c4b9fc17c..6315b3547 100644 --- a/jqueryui/jqueryui.d.ts +++ b/jqueryui/jqueryui.d.ts @@ -43,7 +43,7 @@ declare module JQueryUI { // Autocomplete ////////////////////////////////////////////////// - interface AutocompleteOptions { + interface AutocompleteOptions extends AutocompleteEvents { appendTo?: any; //Selector; autoFocus?: boolean; delay?: number; @@ -72,7 +72,7 @@ declare module JQueryUI { select?: AutocompleteEvent; } - interface Autocomplete extends Widget, AutocompleteOptions, AutocompleteEvents { + interface Autocomplete extends Widget, AutocompleteOptions { escapeRegex: (value: string) => string; } From bd1e699afe92a4485253578265bc896caf9e8e78 Mon Sep 17 00:00:00 2001 From: John Rutherford Date: Wed, 12 Aug 2015 12:33:27 -0400 Subject: [PATCH 095/614] Update jquery.payment.d.ts --- jquery.payment/jquery.payment.d.ts | 123 +++++++++++++++++++++++++---- 1 file changed, 107 insertions(+), 16 deletions(-) diff --git a/jquery.payment/jquery.payment.d.ts b/jquery.payment/jquery.payment.d.ts index a4adc2e77..82e76fb17 100644 --- a/jquery.payment/jquery.payment.d.ts +++ b/jquery.payment/jquery.payment.d.ts @@ -1,26 +1,117 @@ // Type definitions for jQuery.payment // Project: https://github.com/stripe/jquery.payment // Definitions by: Eric J. Smith +// John Rutherford // Definitions: https://github.com/borisyankov/DefinitelyTyped +declare module JQueryPayment { + + interface Payment { + /** + * Validates a card number: + * * Validates numbers + * * Validates Luhn algorithm + * * Validates length + * + * @param cardNumber The card number to validate. + */ + validateCardNumber(cardNumber: string): boolean; + + /** + * Validates a card expiry: + * * Validates numbers + * * Validates in the future + * * Supports year shorthand + * + * @param year The year to validate. + * @param month The months to validate. + */ + validateCardExpiry(year: string, month: string): boolean; + + /** + * Validates a card expiry: + * * Validates numbers + * * Validates in the future + * * Supports year shorthand + * + * @param expiry An object with the year and month to validate. + */ + validateCardExpiry(expiry: ExpiryInfo): boolean; + + /** + * Validates a card CVC: + * * Validates number + * * Validates length to 4 + * + * @param cvc The CVC value to validate. + * @param type Optional card type. + */ + validateCardCVC(cvc: string, type?: string): boolean; + + /** + * Returns a card type. The function will return null if the card type can't be determined. + * + * @param cardNumber The card number to parse. + */ + cardType(cardNumber: string): string; + + /** + * Parses a credit card expiry in the form of MM/YYYY, returning an object containing the month and + * year. Shorthand years, such as 13 are also supported (and converted into the longhand, e.g. 2013). + * + * @param monthYear The value to parse. + */ + cardExpiryVal(monthYear: string): ExpiryInfo; + + /** + * Array of objects that describe valid card types. + */ + cards: CardInfo[]; + } + + interface ExpiryInfo { + month: number; + year: number; + } + + interface CardInfo { + /** + * Card type + */ + type: string; + + /* + * Regex used to identify the card type. For the best experience, this should be + * the shortest pattern that can guarantee the card is of a particular type. + */ + pattern: RegExp; + + /** + * Array of valid card number lengths. + */ + length: number[]; + + /** + * Array of valid card CVC lengths. + */ + cvcLength: number[]; + + /** + * Boolean indicating whether a valid card number should satisfy the Luhn check. + */ + luhn: boolean; + + /** + * Regex used to format the card number. Each match is joined with a space. + */ + format: RegExp; + } +} + interface JQuery { - payment(validatorName: string); + payment(command: string): JQuery; } interface JQueryStatic { - payment: JQueryPayment; + payment: JQueryPayment.Payment; } - -interface JQueryPayment { - validateCardNumber(cardNumber: string) : boolean; - validateCardExpiry(year: string, month: string) : boolean; - validateCardExpiry(expiry: any) : boolean; - validateCardCVC(cvc: string, type: string) : boolean; - cardType(cardNumber: string): string; - cardExpiryVal(monthYear: string): JQueryPaymentExpiryInfo; -} - -interface JQueryPaymentExpiryInfo { - month: number; - year: number; -} \ No newline at end of file From 2ffed1fde1f93a62480e2191e2f320e61b7cd63a Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Wed, 12 Aug 2015 12:21:13 -0700 Subject: [PATCH 096/614] Made dialog options extend events type, test should have had button callbacks within 'buttons' in 'jqueryui'. --- jqueryui/jqueryui-tests.ts | 13 +++++++------ jqueryui/jqueryui.d.ts | 6 +++--- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/jqueryui/jqueryui-tests.ts b/jqueryui/jqueryui-tests.ts index ef02b40d6..d7c85d228 100644 --- a/jqueryui/jqueryui-tests.ts +++ b/jqueryui/jqueryui-tests.ts @@ -1425,12 +1425,13 @@ function test_dialog() { height: 300, width: 350, modal: true, - buttons: {}, - Cancel: function () { - $(this).dialog("close"); - }, - close: function () { - var $el = $(this).dialog("destroy"); + buttons: { + Cancel: function () { + $(this).dialog("close"); + }, + close: function () { + var $el = $(this).dialog("destroy"); + } } }); $("#dialog-message").dialog({ diff --git a/jqueryui/jqueryui.d.ts b/jqueryui/jqueryui.d.ts index 6315b3547..e13754feb 100644 --- a/jqueryui/jqueryui.d.ts +++ b/jqueryui/jqueryui.d.ts @@ -336,9 +336,9 @@ declare module JQueryUI { // Dialog ////////////////////////////////////////////////// - interface DialogOptions { + interface DialogOptions extends DialogEvents { autoOpen?: boolean; - buttons?: any; // object or [] + buttons?: { [buttonText: string]: () => void } | ButtonOptions[]; closeOnEscape?: boolean; closeText?: string; dialogClass?: string; @@ -382,7 +382,7 @@ declare module JQueryUI { resizeStop?: DialogEvent; } - interface Dialog extends Widget, DialogOptions, DialogEvents { + interface Dialog extends Widget, DialogOptions { } From bb830c2a2dc34b2d3a6a11b0d3ffaa821290bf75 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Wed, 12 Aug 2015 12:32:49 -0700 Subject: [PATCH 097/614] Fix 'show' and 'hide' properties in dialog, fix union type, in 'jqueryui'. --- jqueryui/jqueryui.d.ts | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/jqueryui/jqueryui.d.ts b/jqueryui/jqueryui.d.ts index e13754feb..3724ce673 100644 --- a/jqueryui/jqueryui.d.ts +++ b/jqueryui/jqueryui.d.ts @@ -344,7 +344,8 @@ declare module JQueryUI { dialogClass?: string; disabled?: boolean; draggable?: boolean; - height?: any; // number or string + height?: number | string; + hide?: boolean | number | string | DialogShowHideOptions; maxHeight?: number; maxWidth?: number; minHeight?: number; @@ -352,7 +353,7 @@ declare module JQueryUI { modal?: boolean; position?: any; // object, string or [] resizable?: boolean; - show?: any; // number, string or object + show?: boolean | number | string | DialogShowHideOptions; stack?: boolean; title?: string; width?: any; // number or string @@ -361,6 +362,13 @@ declare module JQueryUI { close?: DialogEvent; } + interface DialogShowHideOptions { + effect: string; + delay?: number; + duration?: number; + easing?: string; + } + interface DialogUIParams { } @@ -799,7 +807,7 @@ declare module JQueryUI { interface EffectOptions { effect: string; easing?: string; - duration: any; + duration?: number; complete: Function; } From 539af528b354cfea93e28bb14470140ec65cb1a0 Mon Sep 17 00:00:00 2001 From: Felipe Barriga Richards Date: Wed, 12 Aug 2015 16:35:09 -0300 Subject: [PATCH 098/614] bunyan: adding missing types. --- bunyan/bunyan.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/bunyan/bunyan.d.ts b/bunyan/bunyan.d.ts index fd4e9d89a..1f73705c3 100644 --- a/bunyan/bunyan.d.ts +++ b/bunyan/bunyan.d.ts @@ -18,6 +18,7 @@ declare module "bunyan" { child(obj:Object, simple?:boolean):Logger; reopenFileStreams():void; + level():string|number; level(value: number | string):void; levels(name: number | string, value: number | string):void; @@ -50,7 +51,7 @@ declare module "bunyan" { interface LoggerOptions { name: string; streams?: Stream[]; - level?: string; + level?: string | number; stream?: WritableStream; serializers?: Serializers; src?: boolean; From 5e48f1bdb2c038e036d4fdbca745588b7580363b Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Wed, 12 Aug 2015 15:28:34 -0700 Subject: [PATCH 099/614] Made options extend events, added 'change' and 'create' in for spinner events, in 'jqueryui'. --- jqueryui/jqueryui.d.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/jqueryui/jqueryui.d.ts b/jqueryui/jqueryui.d.ts index 3724ce673..839ce84da 100644 --- a/jqueryui/jqueryui.d.ts +++ b/jqueryui/jqueryui.d.ts @@ -609,7 +609,7 @@ declare module JQueryUI { // Slider ////////////////////////////////////////////////// - interface SliderOptions { + interface SliderOptions extends SliderEvents { animate?: any; // boolean, string or number disabled?: boolean; max?: number; @@ -639,7 +639,7 @@ declare module JQueryUI { stop?: SliderEvent; } - interface Slider extends Widget, SliderOptions, SliderEvents { + interface Slider extends Widget, SliderOptions { } @@ -708,7 +708,7 @@ declare module JQueryUI { // Spinner ////////////////////////////////////////////////// - interface SpinnerOptions { + interface SpinnerOptions extends SpinnerEvents { culture?: string; disabled?: boolean; icons?: any; @@ -728,12 +728,14 @@ declare module JQueryUI { } interface SpinnerEvents { + change?: SpinnerEvent; + create?: SpinnerEvent; spin?: SpinnerEvent; start?: SpinnerEvent; stop?: SpinnerEvent; } - interface Spinner extends Widget, SpinnerOptions, SpinnerEvents { + interface Spinner extends Widget, SpinnerOptions { } From cb265e50c5d79195fc46b45cd8dc708b5f88ad9a Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Wed, 12 Aug 2015 15:29:54 -0700 Subject: [PATCH 100/614] extend options with events in 'jqueryui'. --- jqueryui/jqueryui.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/jqueryui/jqueryui.d.ts b/jqueryui/jqueryui.d.ts index 839ce84da..80cda8976 100644 --- a/jqueryui/jqueryui.d.ts +++ b/jqueryui/jqueryui.d.ts @@ -741,7 +741,7 @@ declare module JQueryUI { // Tabs ////////////////////////////////////////////////// - interface TabsOptions { + interface TabsOptions extends TabsEvents { active?: any; // boolean or number collapsible?: boolean; disabled?: any; // boolean or [] @@ -771,7 +771,7 @@ declare module JQueryUI { load?: TabsEvent; } - interface Tabs extends Widget, TabsOptions, TabsEvents { + interface Tabs extends Widget, TabsOptions { } From a9d5865d7936fd514823fcda9e4a859472e43d07 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Wed, 12 Aug 2015 15:39:37 -0700 Subject: [PATCH 101/614] 'offset' isn't a property for 'position' in 'jqueryui'. --- jqueryui/jqueryui-tests.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/jqueryui/jqueryui-tests.ts b/jqueryui/jqueryui-tests.ts index d7c85d228..39f28d7b5 100644 --- a/jqueryui/jqueryui-tests.ts +++ b/jqueryui/jqueryui-tests.ts @@ -1765,7 +1765,6 @@ function test_effects() { of: $("#parent"), my: $("#my_horizontal").val() + " " + $("#my_vertical").val(), at: $("#at_horizontal").val() + " " + $("#at_vertical").val(), - offset: $("#offset").val(), collision: $("#collision_horizontal").val() + " " + $("#collision_vertical").val() }); $("#toggle").toggle({ effect: "scale", direction: "horizontal" }); From 29e90320fb852db78cdaea6a3c7b6bccacb3d0ca Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Wed, 12 Aug 2015 15:52:00 -0700 Subject: [PATCH 102/614] 'start' should be a function in tests for 'jqueryui'. --- jqueryui/jqueryui-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jqueryui/jqueryui-tests.ts b/jqueryui/jqueryui-tests.ts index 39f28d7b5..9c154e4b1 100644 --- a/jqueryui/jqueryui-tests.ts +++ b/jqueryui/jqueryui-tests.ts @@ -1582,7 +1582,7 @@ function test_spinner() { min: 5, max: 2500, step: 25, - start: 1000, + start: function () { return; }, numberFormat: "C" }); $("#spinner").spinner({ From a19db768d1dcb8c8dbd2308f609cc0b68404af67 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Wed, 12 Aug 2015 15:52:46 -0700 Subject: [PATCH 103/614] Things should be functions in tests for 'jqueryui'. --- jqueryui/jqueryui-tests.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/jqueryui/jqueryui-tests.ts b/jqueryui/jqueryui-tests.ts index 9c154e4b1..98b45ca28 100644 --- a/jqueryui/jqueryui-tests.ts +++ b/jqueryui/jqueryui-tests.ts @@ -1596,8 +1596,8 @@ function test_spinner() { }); $("#lat, #lng").spinner({ step: .001, - change: 123, - stop: 321 + change() { }, + stop() { }, }); $("#spinner").spinner({ spin: function (event, ui) { From fe366f8f9193cbd7ef42494f440576b140717df0 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Wed, 12 Aug 2015 15:57:42 -0700 Subject: [PATCH 104/614] Fixed width (with) in 'js-beautify'. --- js-beautify/js-beautify.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js-beautify/js-beautify.d.ts b/js-beautify/js-beautify.d.ts index e52614ad8..fc581ea90 100644 --- a/js-beautify/js-beautify.d.ts +++ b/js-beautify/js-beautify.d.ts @@ -9,7 +9,7 @@ declare var js_beautify: { indent_char?: string; eol?: string; indent_level?: number; - indent_width_tabs?: boolean; + indent_with_tabs?: boolean; preserve_newlines?: boolean; max_preserve_newlines?: number; jslint_happy: boolean; From d9a282f5288049fe3148dc8d0cfbb6a947a67b96 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Wed, 12 Aug 2015 16:59:09 -0700 Subject: [PATCH 105/614] Fix excess object literal errors in 'leaflet'. --- leaflet/leaflet-tests.ts | 3 +-- leaflet/leaflet.d.ts | 31 ++++++++++++++++++++++++++----- 2 files changed, 27 insertions(+), 7 deletions(-) diff --git a/leaflet/leaflet-tests.ts b/leaflet/leaflet-tests.ts index 4c8fd4d73..6bec7e217 100755 --- a/leaflet/leaflet-tests.ts +++ b/leaflet/leaflet-tests.ts @@ -186,7 +186,7 @@ map.once('contextmenu', (e: L.LeafletMouseEvent) => { var marker = L.marker(L.latLng(42, 51), { icon: L.icon({ - iconURl: 'roger.png', + iconUrl: 'roger.png', iconRetinaUrl: 'roger-retina.png', iconSize: L.point(40, 40), iconAnchor: L.point(20, 0), @@ -264,7 +264,6 @@ popup.setLatLng(L.latLng(12, 54)).setContent('this is nice popup').openOn(map); popup.update(); var tileLayer = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png?{foo}', { - foo: 'bar', minZoom: 0, maxZoom: 18, maxNativeZoom: 17, diff --git a/leaflet/leaflet.d.ts b/leaflet/leaflet.d.ts index 92aed79b7..56d702485 100755 --- a/leaflet/leaflet.d.ts +++ b/leaflet/leaflet.d.ts @@ -264,6 +264,11 @@ declare module L { declare module L { export interface ClassExtendOptions { + /** + * Your class's constructor function, meaning that it gets called when you do 'new MyClass(...)'. + */ + initialize?: Function; + /** * options is a special property that unlike other objects that you pass * to extend will be merged with the parent one instead of overriding it @@ -286,6 +291,8 @@ declare module L { * constants. */ static?: any; + + [prop: string]: any; } export interface ClassStatic { @@ -3592,6 +3599,11 @@ declare module L { */ autoPan?: boolean; + /** + * Set it to true if you want to prevent users from panning the popup off of the screen while it is open. + */ + keepInView?: boolean; + /** * Controls the presense of a close button in the popup. * @@ -3645,6 +3657,11 @@ declare module L { * option). */ closeOnClick?: boolean; + + /** + * A custom class name to assign to the popup. + */ + className?: string; } } @@ -4064,6 +4081,11 @@ declare module L { * Default value: false. */ reuseTiles?: boolean; + + /** + * When this option is set, the TileLayer only loads tiles that are in the given geographical bounds. + */ + bounds?: LatLngBounds; } } @@ -4219,13 +4241,12 @@ declare module L { declare module L { export interface ZoomOptions { - /** - * The position of the control (one of the map corners). See control positions. - * - * Default value: 'topright'. + * If not specified, zoom animation will happen if the zoom origin is inside the current view. + * If true, the map will attempt animating zoom disregarding where zoom origin is. + * Setting false will make it always reset the view completely without animation. */ - position?: string; + animate?: boolean; } } From 6c9553af733cbcc56b42b92d07bd60c84762b16a Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Wed, 12 Aug 2015 17:10:07 -0700 Subject: [PATCH 106/614] Extend 'PathOptions' in 'leaflet-label'. --- leaflet-label/leaflet-label.d.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/leaflet-label/leaflet-label.d.ts b/leaflet-label/leaflet-label.d.ts index 38bb43d7a..a77def73c 100644 --- a/leaflet-label/leaflet-label.d.ts +++ b/leaflet-label/leaflet-label.d.ts @@ -6,9 +6,13 @@ /// declare module L { - export interface IconOptions { - labelAnchor?: Point; - } + export interface IconOptions { + labelAnchor?: Point; + } + + export interface PathOptions { + labelAnchor?: Point; + } export interface CircleMarkerOptions { labelAnchor?: Point; From d874adfcb6391e3345cf2f30088a43138a2aee05 Mon Sep 17 00:00:00 2001 From: almstrand Date: Wed, 12 Aug 2015 17:20:07 -0700 Subject: [PATCH 107/614] 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 75b38004961afa3fd24a1f25b8c2b57ca963e9d1 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Wed, 12 Aug 2015 18:30:54 -0700 Subject: [PATCH 108/614] Account for core data types in 'log4js'. --- log4js/log4js.d.ts | 108 ++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 103 insertions(+), 5 deletions(-) diff --git a/log4js/log4js.d.ts b/log4js/log4js.d.ts index 28d821377..70059142c 100644 --- a/log4js/log4js.d.ts +++ b/log4js/log4js.d.ts @@ -63,8 +63,8 @@ declare module "log4js" { */ export function shutdown(cb: Function): void; - export function configure(config: IConfig, options?: any): void; export function configure(filename: string, options?: any): void; + export function configure(config: IConfig, options?: any): void; export function setGlobalLogLevel(level: string): void; export function setGlobalLogLevel(level: Level): void; @@ -126,14 +126,112 @@ declare module "log4js" { } export interface IConfig { - appenders: IAppenderConfig[]; + appenders: AppenderConfig[]; levels?: { [category: string]: string }; replaceConsole?: boolean; } - export interface IAppenderConfig { + + export interface AppenderConfigBase { type: string; - category?: string[]; - // etc... + category?: string; } + + export interface ConsoleAppenderConfig extends AppenderConfigBase {} + + export interface FileAppenderConfig extends AppenderConfigBase { + filename: string; + } + export interface DateFileAppenderConfig extends FileAppenderConfig { + /** + * The following strings are recognised in the pattern: + * - yyyy : the full year, use yy for just the last two digits + * - MM : the month + * - dd : the day of the month + * - hh : the hour of the day (24-hour clock) + * - mm : the minute of the hour + * - ss : seconds + * - SSS : milliseconds (although I'm not sure you'd want to roll your logs every millisecond) + * - O : timezone (capital letter o) + */ + pattern: string; + alwaysIncludePattern: boolean; + } + + export interface SmtpAppenderConfig extends AppenderConfigBase { + /** Comma separated list of email recipients */ + recipients: string; + + /** Sender of all emails (defaults to transport user) */ + sender: string; + + /** Subject of all email messages (defaults to first event's message)*/ + subject: string; + + /** + * The time in seconds between sending attempts (defaults to 0). + * All events are buffered and sent in one email during this time. + * If 0 then every event sends an email + */ + sendInterval: number; + + SMTP: { + host: string; + secure: boolean; + port: number; + auth: { + user: string; + pass: string; + } + } + } + + export interface HookIoAppenderConfig extends FileAppenderConfig { + maxLogSize: number; + backup: number; + pollInterval: number; + } + + export interface GelfAppenderConfig extends AppenderConfigBase { + host: string; + hostname: string; + port: string; + facility: string; + } + + export interface MultiprocessAppenderConfig extends AppenderConfigBase { + mode: string; + loggerPort: number; + loggerHost: string; + facility: string; + appender?: AppenderConfig; + } + + export interface LogglyAppenderConfig extends AppenderConfigBase { + /** Loggly customer token - https://www.loggly.com/docs/api-sending-data/ */ + token: string; + + /** Loggly customer subdomain (use 'abc' for abc.loggly.com) */ + subdomain: string; + + /** an array of strings to help segment your data & narrow down search results in Loggly */ + tags: string[]; + + /** Enable JSON logging by setting to 'true' */ + json: boolean; + } + + export interface ClusteredAppenderConfig extends AppenderConfigBase { + appenders?: AppenderConfig[]; + } + + type CoreAppenderConfig = ConsoleAppenderConfig + | FileAppenderConfig + | DateFileAppenderConfig + | SmtpAppenderConfig + | HookIoAppenderConfig + | GelfAppenderConfig + | MultiprocessAppenderConfig + + type AppenderConfig = CoreAppenderConfig | (AppenderConfigBase & { [prop: string]: any; }); } From a1f7cb56596239b3797996cad846fc57ad418edc Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Wed, 12 Aug 2015 19:00:15 -0700 Subject: [PATCH 109/614] Added 'secondLevelDomains' to 'mailcheck'. --- mailcheck/mailcheck.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/mailcheck/mailcheck.d.ts b/mailcheck/mailcheck.d.ts index c6f28d0db..64b5f93c4 100644 --- a/mailcheck/mailcheck.d.ts +++ b/mailcheck/mailcheck.d.ts @@ -47,6 +47,7 @@ declare module MailcheckModule { export interface IOptions { domains?: string[]; + secondLevelDomains?: string[]; topLevelDomains?: string[]; distanceFunction?: IDistanceFunction; suggested?: ISuggested | IJQuerySuggested; From 7192d685cbb16c76a1426b62ea912960a2b316c5 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Wed, 12 Aug 2015 19:02:06 -0700 Subject: [PATCH 110/614] Not-so-smart lsts in 'marked'. --- marked/marked-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/marked/marked-tests.ts b/marked/marked-tests.ts index ca8b96920..44be0f0e8 100644 --- a/marked/marked-tests.ts +++ b/marked/marked-tests.ts @@ -8,7 +8,7 @@ var options: MarkedOptions = { breaks: false, pedantic: false, sanitize: true, - smartLsts: true, + smartLists: true, silent: false, highlight: function (code: string, lang: string) { return ''; From f8d51d29b3a6f416a5fee44330844e3a153e9a23 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Wed, 12 Aug 2015 19:05:02 -0700 Subject: [PATCH 111/614] Reorder overloads in 'mCustomScrollbar'. --- mCustomScrollbar/mCustomScrollbar.d.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/mCustomScrollbar/mCustomScrollbar.d.ts b/mCustomScrollbar/mCustomScrollbar.d.ts index 7e0a529ef..871ed2d5f 100644 --- a/mCustomScrollbar/mCustomScrollbar.d.ts +++ b/mCustomScrollbar/mCustomScrollbar.d.ts @@ -129,12 +129,6 @@ declare module MCustomScrollbar { } interface JQuery { - /** - * Creates a new mCustomScrollbar with the specified or default options - * - * @param options Override default options - */ - mCustomScrollbar(options?: MCustomScrollbar.CustomScrollbarOptions): JQuery; /** * Calls specified methods on the scrollbar "update", "stop", "disable", "destroy" * @@ -149,4 +143,10 @@ interface JQuery { * @param options Override default options */ mCustomScrollbar(scrollTo: string, parameter: any, options?: MCustomScrollbar.ScrollToParameterOptions): JQuery; + /** + * Creates a new mCustomScrollbar with the specified or default options + * + * @param options Override default options + */ + mCustomScrollbar(options?: MCustomScrollbar.CustomScrollbarOptions): JQuery; } \ No newline at end of file From 24d6b7762744ea69047a69ba1372775739adf6a5 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Wed, 12 Aug 2015 18:30:54 -0700 Subject: [PATCH 112/614] Account for core data types in 'log4js'. --- log4js/log4js.d.ts | 110 ++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 105 insertions(+), 5 deletions(-) diff --git a/log4js/log4js.d.ts b/log4js/log4js.d.ts index 28d821377..9ad5d266e 100644 --- a/log4js/log4js.d.ts +++ b/log4js/log4js.d.ts @@ -63,8 +63,8 @@ declare module "log4js" { */ export function shutdown(cb: Function): void; - export function configure(config: IConfig, options?: any): void; export function configure(filename: string, options?: any): void; + export function configure(config: IConfig, options?: any): void; export function setGlobalLogLevel(level: string): void; export function setGlobalLogLevel(level: Level): void; @@ -126,14 +126,114 @@ declare module "log4js" { } export interface IConfig { - appenders: IAppenderConfig[]; + appenders: AppenderConfig[]; levels?: { [category: string]: string }; replaceConsole?: boolean; } - export interface IAppenderConfig { + + export interface AppenderConfigBase { type: string; - category?: string[]; - // etc... + category?: string; } + + export interface ConsoleAppenderConfig extends AppenderConfigBase {} + + export interface FileAppenderConfig extends AppenderConfigBase { + filename: string; + } + export interface DateFileAppenderConfig extends FileAppenderConfig { + /** + * The following strings are recognised in the pattern: + * - yyyy : the full year, use yy for just the last two digits + * - MM : the month + * - dd : the day of the month + * - hh : the hour of the day (24-hour clock) + * - mm : the minute of the hour + * - ss : seconds + * - SSS : milliseconds (although I'm not sure you'd want to roll your logs every millisecond) + * - O : timezone (capital letter o) + */ + pattern: string; + alwaysIncludePattern: boolean; + } + + export interface SmtpAppenderConfig extends AppenderConfigBase { + /** Comma separated list of email recipients */ + recipients: string; + + /** Sender of all emails (defaults to transport user) */ + sender: string; + + /** Subject of all email messages (defaults to first event's message)*/ + subject: string; + + /** + * The time in seconds between sending attempts (defaults to 0). + * All events are buffered and sent in one email during this time. + * If 0 then every event sends an email + */ + sendInterval: number; + + SMTP: { + host: string; + secure: boolean; + port: number; + auth: { + user: string; + pass: string; + } + } + } + + export interface HookIoAppenderConfig extends FileAppenderConfig { + maxLogSize: number; + backup: number; + pollInterval: number; + } + + export interface GelfAppenderConfig extends AppenderConfigBase { + host: string; + hostname: string; + port: string; + facility: string; + } + + export interface MultiprocessAppenderConfig extends AppenderConfigBase { + mode: string; + loggerPort: number; + loggerHost: string; + facility: string; + appender?: AppenderConfig; + } + + export interface LogglyAppenderConfig extends AppenderConfigBase { + /** Loggly customer token - https://www.loggly.com/docs/api-sending-data/ */ + token: string; + + /** Loggly customer subdomain (use 'abc' for abc.loggly.com) */ + subdomain: string; + + /** an array of strings to help segment your data & narrow down search results in Loggly */ + tags: string[]; + + /** Enable JSON logging by setting to 'true' */ + json: boolean; + } + + export interface ClusteredAppenderConfig extends AppenderConfigBase { + appenders?: AppenderConfig[]; + } + + type CoreAppenderConfig = ConsoleAppenderConfig + | FileAppenderConfig + | DateFileAppenderConfig + | SmtpAppenderConfig + | HookIoAppenderConfig + | GelfAppenderConfig + | MultiprocessAppenderConfig + | LogglyAppenderConfig + | ClusteredAppenderConfig + + type AppenderConfig = CoreAppenderConfig | (AppenderConfigBase & { [prop: string]: any; }); } From 585ce49c019f202dec2380c1f7b6f71577df9993 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 13 Aug 2015 00:06:01 -0700 Subject: [PATCH 113/614] Don't use union types in 'log4js'. --- log4js/log4js.d.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/log4js/log4js.d.ts b/log4js/log4js.d.ts index 9ad5d266e..3a1e9e3e7 100644 --- a/log4js/log4js.d.ts +++ b/log4js/log4js.d.ts @@ -234,6 +234,10 @@ declare module "log4js" { | LogglyAppenderConfig | ClusteredAppenderConfig - type AppenderConfig = CoreAppenderConfig | (AppenderConfigBase & { [prop: string]: any; }); + interface UserDefinedAppenderConfig extends AppenderConfigBase { + [prop: string]: any; + } + + type AppenderConfig = CoreAppenderConfig | UserDefinedAppenderConfig; } From cefee3eadc419f8a994e3c42ed6b80078b5c73b4 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 13 Aug 2015 11:11:18 -0700 Subject: [PATCH 114/614] Can't use intersection types or else 1.5 tests will fail in 'jquery.uniform'. --- jquery.uniform/jquery.uniform.d.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/jquery.uniform/jquery.uniform.d.ts b/jquery.uniform/jquery.uniform.d.ts index e91a41c93..402f3d7c4 100644 --- a/jquery.uniform/jquery.uniform.d.ts +++ b/jquery.uniform/jquery.uniform.d.ts @@ -34,8 +34,13 @@ interface UniformOptions { useID?: boolean; wrapperClass?: string; } + +interface UniformOptionsWithExtraParameters extends UniformOptions { + [optionName: string]: any; +} + interface Uniform { - (options?: UniformOptions & {[option: string]: any;}): JQuery; + (options?: UniformOptions): JQuery; update(elemOrSelector?: any): void; restore(elemOrSelector?: any): void; elements: JQuery[]; From a508d7d50c089416516933c8781041c693fc578f Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 13 Aug 2015 11:18:47 -0700 Subject: [PATCH 115/614] Add 'enable' and fix types of properties in 'mCustomScrollbar'. --- mCustomScrollbar/mCustomScrollbar.d.ts | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/mCustomScrollbar/mCustomScrollbar.d.ts b/mCustomScrollbar/mCustomScrollbar.d.ts index 871ed2d5f..f41aca00a 100644 --- a/mCustomScrollbar/mCustomScrollbar.d.ts +++ b/mCustomScrollbar/mCustomScrollbar.d.ts @@ -40,6 +40,10 @@ declare module MCustomScrollbar { */ autoHideScrollbar?: boolean; scrollButtons?: { + /** + * Enable or disable scroll buttons. + */ + enable?: boolean; /** * Scroll buttons scroll type, values: "continuous" (scroll continuously while pressing the button), "pixels" (scrolls by a fixed number of pixels on each click") */ @@ -47,11 +51,11 @@ declare module MCustomScrollbar { /** * Scroll buttons continuous scrolling speed, integer value or "auto" (script calculates and sets the speed according to content length) */ - scrollSpeed?: any; + scrollSpeed?: number | string; /** - * Scroll buttons pixels scrolling amount, value in pixels + * Scroll buttons pixels scrolling amount, value in pixels or "auto" */ - scrollAmount?: number; + scrollAmount?: number | string; } advanced?: { /** @@ -94,14 +98,24 @@ declare module MCustomScrollbar { */ onScroll?: () => void; /** - * User defined callback function, triggered when scroll end-limit is reached + * A function to call when scrolling is completed and content is scrolled all the way to the end (bottom/right) + */ + onTotalScroll?: () => void; + /** + * A function to call when scrolling is completed and content is scrolled back to the beginning (top/left) */ onTotalScrollBack?: () => void; /** - * Scroll end-limit offset, value in pixels + * Set an offset for which the onTotalScroll callback is triggered. + * Its value is in pixels. */ onTotalScrollOffset?: number; /** + * Set an offset for which the onTotalScrollBack callback is triggered. + * Its value is in pixels + */ + onTotalScrollBackOffset?: number; + /** * User defined callback function, triggered while scrolling */ whileScrolling?: () => void; From e4484309b049b5c7778ede56c35fba9b2a4b36fd Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 13 Aug 2015 12:05:30 -0700 Subject: [PATCH 116/614] Add 'mongos' property to interface in 'mongoose'. --- mongoose/mongoose.d.ts | 63 +++++++++++++++++++++++++++++++++++------- 1 file changed, 53 insertions(+), 10 deletions(-) diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index ce4be964f..e840d8e05 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -6,10 +6,10 @@ /// declare module "mongoose" { - function connect(uri: string, options?: ConnectionOption, callback?: (err: any) => void): Mongoose; + function connect(uri: string, options?: ConnectionOptions , callback?: (err: any) => void): Mongoose; function createConnection(): Connection; - function createConnection(uri: string, options?: ConnectionOption): Connection; - function createConnection(host: string, database_name: string, port?: number, options?: ConnectionOption): Connection; + function createConnection(uri: string, options?: ConnectionOptions): Connection; + function createConnection(host: string, database_name: string, port?: number, options?: ConnectionOptions): Connection; function disconnect(callback?: (err?: any) => void): Mongoose; function model(name: string, schema?: Schema, collection?: string, skipInit?: boolean): Model; @@ -25,10 +25,10 @@ declare module "mongoose" { var connection: Connection; export class Mongoose { - connect(uri: string, options?: ConnectionOption, callback?: (err: any) => void): Mongoose; + connect(uri: string, options?: ConnectOpenOptionsBase, callback?: (err: any) => void): Mongoose; createConnection(): Connection; createConnection(uri: string, options?: Object): Connection; - createConnection(host: string, database_name: string, port?: number, options?: ConnectionOption): Connection; + createConnection(host: string, database_name: string, port?: number, options?: ConnectOpenOptionsBase): Connection; disconnect(callback?: (err?: any) => void): Mongoose; get(key: string): any; model(name: string, schema?: Schema, collection?: string, skipInit?: boolean): Model; @@ -49,23 +49,66 @@ declare module "mongoose" { collection(name: string, options?: Object): Collection; model(name: string, schema?: Schema, collection?: string): Model; modelNames(): string[]; - open(host: string, database?: string, port?: number, options?: ConnectionOption, callback?: (err: any) => void): Connection; - openSet(uris: string, database?: string, options?: ConnectionSetOption, callback?: (err: any) => void): Connection; + open(host: string, database?: string, port?: number, options?: OpenSetConnectionOptions, callback?: (err: any) => void): Connection; + openSet(uris: string, database?: string, options?: OpenSetConnectionOptions, callback?: (err: any) => void): Connection; db: any; collections: {[index: string]: Collection}; readyState: number; } - export interface ConnectionOption { + + export interface ConnectOpenOptionsBase { db?: any; server?: any; replset?: any; + /** Username for authentication if not supplied in the URI. */ user?: string; + /** Password for authentication if not supplied in the URI. */ pass?: string; + /** Options for authentication */ auth?: any; } - export interface ConnectionSetOption extends ConnectionOption { - mongos?: boolean; + + export interface ConnectionOptions extends ConnectOpenOptionsBase { + /** Passed to the underlying driver's Mongos instance. */ + mongos?: MongosOptions; + } + + interface OpenSetConnectionOptions extends ConnectOpenOptionsBase { + /** If true, enables High Availability support for mongos */ + mongos?: boolean; + } + + interface MongosOptions { + /** Turn on high availability monitoring. (default: true) */ + ha?: boolean; + /** Time between each replicaset status check. (default: 5000) */ + haInterval?: number; + /** + * Number of connections in the connection pool for each + * server instance. (default: 5 (for legacy reasons)) */ + poolSize?: number; + /** + * Use ssl connection (needs to have a mongod server with + * ssl support). (default: false). + */ + ssl?: boolean; + /** + * Validate mongod server certificate against ca + * (needs to have a mongod server with ssl support, 2.4 or higher) + * (default: true) + */ + sslValidate?: boolean; + /** Turn on high availability monitoring. */ + sslCA?: (Buffer|string)[]; + sslKey?: Buffer|string; + sslPass?: Buffer|string; + socketOptions?: { + noDelay?: boolean; + keepAlive?: number; + connectionTimeoutMS?: number; + socketTimeoutMS?: number; + }; } export interface Collection { From f2f72772620e10138bbb380fc1edb73001db0bf7 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 13 Aug 2015 12:25:57 -0700 Subject: [PATCH 117/614] 'compressed' in 'needle' --- needle/needle-tests.ts | 2 +- needle/needle.d.ts | 19 +++++++++++++++---- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/needle/needle-tests.ts b/needle/needle-tests.ts index 24d9701b5..106d46a71 100644 --- a/needle/needle-tests.ts +++ b/needle/needle-tests.ts @@ -22,7 +22,7 @@ function ResponsePipeline() { var options = { compressed: true, - follow: true, + follow: 5, rejectUnauthorized: true }; diff --git a/needle/needle.d.ts b/needle/needle.d.ts index 741cf5fe3..e7a67387d 100644 --- a/needle/needle.d.ts +++ b/needle/needle.d.ts @@ -15,13 +15,21 @@ declare module Needle { interface RequestOptions { timeout?: number; - follow?: any; // number | string + follow?: number; + follow_max?: number; multipart?: boolean; proxy?: string; agent?: string; - headers?: any; + headers?: HttpHeaderOptions; auth?: string; // auto | digest | basic (default) json?: boolean; + + // These properties are overwritten by those in the 'headers' field + compressed?: boolean; + cookies?: { [name: string]: any; }; + // Overwritten if present in the URI + username?: string; + password?: string; } interface ResponseOptions { @@ -31,12 +39,15 @@ declare module Needle { } interface HttpHeaderOptions { + cookies?: { [name: string]: any; }; compressed?: boolean; - username?: string; - password?: string; accept?: string; connection?: string; user_agent?: string; + + // Overwritten if present in the URI + username?: string; + password?: string; } interface TLSOptions { From 4549840d3380b5183f7a934ea0e62914b151d08b Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 13 Aug 2015 15:02:38 -0700 Subject: [PATCH 118/614] Added data map in 'node-gcm'. --- node-gcm/node-gcm.d.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/node-gcm/node-gcm.d.ts b/node-gcm/node-gcm.d.ts index 3272acac4..cac54f31a 100644 --- a/node-gcm/node-gcm.d.ts +++ b/node-gcm/node-gcm.d.ts @@ -10,6 +10,9 @@ declare module "node-gcm" { delayWhileIdle?: boolean; timeToLive?: number; dryRun?: boolean; + data: { + [key: string]: string; + }; } export class Message { @@ -20,7 +23,7 @@ declare module "node-gcm" { dryRun: boolean; addData(key: string, value: string): void; - addData(data: any): void; + addData(data: { [key: string]: string }): void; } From 0dcd0aec0b31a86ea4d6490952176c22039a2dce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20Corbi=C3=A8re?= Date: Sat, 15 Aug 2015 11:17:00 +0200 Subject: [PATCH 119/614] Add type definitions for gulp-cached --- gulp-cached/gulp-cached-tests.ts | 21 +++++++++++++++++ gulp-cached/gulp-cached.d.ts | 39 ++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 gulp-cached/gulp-cached-tests.ts create mode 100644 gulp-cached/gulp-cached.d.ts diff --git a/gulp-cached/gulp-cached-tests.ts b/gulp-cached/gulp-cached-tests.ts new file mode 100644 index 000000000..42a669738 --- /dev/null +++ b/gulp-cached/gulp-cached-tests.ts @@ -0,0 +1,21 @@ +/// +/// + +import * as gulp from "gulp"; +import cached = require("gulp-cached"); + +// Usage +gulp.src("*.ts") + .pipe(cached("ts-cache")); + +gulp.src("*.ts") + .pipe(cached("ts-cache", {})); + +gulp.src("*.ts") + .pipe(cached("ts-cache", { optimizeMemory: true })); + +// Clearing the whole cache +cached.caches = {}; + +// Clearing a specific cache entry +delete cached.caches["ts-cache"]; diff --git a/gulp-cached/gulp-cached.d.ts b/gulp-cached/gulp-cached.d.ts new file mode 100644 index 000000000..eeb03997c --- /dev/null +++ b/gulp-cached/gulp-cached.d.ts @@ -0,0 +1,39 @@ +// Type definitions for gulp-cached +// Project: https://github.com/wearefractal/gulp-cached +// Definitions by: Thomas Corbière +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "gulp-cached" +{ + interface ICacheStore + { + [name: string]: {}; + } + + interface IOptions + { + /** + * Uses md5 instead of storing the whole file contents. + * @default false + */ + optimizeMemory?: boolean; + } + + interface IGulpCached + { + /** + * Creates a new cache hash or uses an existing one. + */ + (name: string, options?: IOptions): NodeJS.ReadWriteStream; + + /** + * Cache store. + */ + caches: ICacheStore; + } + + const cached: IGulpCached; + export = cached; +} From f9fe170911e2e16e370a0686a491ba1ce03bec00 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20Corbi=C3=A8re?= Date: Sat, 15 Aug 2015 12:49:47 +0200 Subject: [PATCH 120/614] Add type definitions for gulp-remember --- gulp-remember/gulp-remember-tests.ts | 25 ++++++++++++ gulp-remember/gulp-remember.d.ts | 59 ++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+) create mode 100644 gulp-remember/gulp-remember-tests.ts create mode 100644 gulp-remember/gulp-remember.d.ts diff --git a/gulp-remember/gulp-remember-tests.ts b/gulp-remember/gulp-remember-tests.ts new file mode 100644 index 000000000..804832c5d --- /dev/null +++ b/gulp-remember/gulp-remember-tests.ts @@ -0,0 +1,25 @@ +/// +/// + +import * as gulp from "gulp"; +import remember = require("gulp-remember"); + +// Usage +gulp.src("*.ts") + .pipe(remember()); + +gulp.src("*.ts") + .pipe(remember("ts-cache")); + +// Drops a file from a remember cache +remember.forget("main.ts"); +remember.forget("ts-cache", "main.ts"); + +// Drops all files from a remember cache +remember.forgetAll(); +remember.forgetAll("ts-cache"); + +// Get a raw remember cache +remember.cacheFor(); +remember.cacheFor("ts-cache"); +remember.cacheFor("ts-cache")["main.ts"]; diff --git a/gulp-remember/gulp-remember.d.ts b/gulp-remember/gulp-remember.d.ts new file mode 100644 index 000000000..f606646e2 --- /dev/null +++ b/gulp-remember/gulp-remember.d.ts @@ -0,0 +1,59 @@ +// Type definitions for gulp-remember +// Project: https://github.com/ahaurw01/gulp-remember +// Definitions by: Thomas Corbière +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "gulp-remember" +{ + interface ICache + { + [path: string]: NodeJS.ReadWriteStream; + } + + interface IGulpRemember + { + /** + * Return a through stream that will: + * 1. Remember all files that ever pass through it. + * 2. Add all remembered files back into the stream when not present. + * @param cacheName Name to give your cache + */ + (cacheName?: string): NodeJS.ReadWriteStream; + + /** + * Forget about a file. + * A warning is logged if either the named cache or file do not exist. + * @param path Path of the file to forget + */ + forget(path: string): void; + + /** + * Forget about a file. + * A warning is logged if either the named cache or file do not exist. + * @param cacheName Name of the cache from which to drop the file + * @param path Path of the file to forget + */ + forget(cacheName: string, path: string): void; + + /** + * Forget all files in one cache. + * A warning is logged if the cache does not exist. + * + * @param cacheName Name of the cache to wipe + */ + forgetAll(cacheName?: string): void; + + /** + * Return a raw cache by name. + * Useful for checking state. Manually adding or removing files is NOT recommended. + * + * @param cacheName Name of the cache to retrieve + */ + cacheFor(cacheName?: string): ICache; + } + + const remember: IGulpRemember; + export = remember; +} From 77a5e5a7c784fdbade38402cadaab1d73799a219 Mon Sep 17 00:00:00 2001 From: unknown Date: Sat, 15 Aug 2015 15:39:26 +0300 Subject: [PATCH 121/614] Updated iso8601-localizer type definitions to suit server-side usage --- iso8601-localizer/iso8601-localizer-tests.ts | 13 ++++++++++++- iso8601-localizer/iso8601-localizer.d.ts | 6 +++++- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/iso8601-localizer/iso8601-localizer-tests.ts b/iso8601-localizer/iso8601-localizer-tests.ts index d532d7af0..1368b8d78 100644 --- a/iso8601-localizer/iso8601-localizer-tests.ts +++ b/iso8601-localizer/iso8601-localizer-tests.ts @@ -1,7 +1,18 @@ + +/* +The API is the same for both client-side and server-side users. + +For server-side users include the module as external module: + +import ISO8601Localizer = require('iso8601-localizer'); + +For client-side users include the module as internal module as shown below: +*/ + /// new ISO8601Localizer('2015-06-02T14:13:12').localize(); new ISO8601Localizer('2015-06-02T14:13:12').to(-5).localize(); -new ISO8601Localizer('2015-06-02T14:13:12').to(-5).returnAs('object').localize(); +new ISO8601Localizer('2015-06-02T14:13:12').to(-5).returnAs('object').localize(); \ No newline at end of file diff --git a/iso8601-localizer/iso8601-localizer.d.ts b/iso8601-localizer/iso8601-localizer.d.ts index 7d7c52626..0bd33176e 100644 --- a/iso8601-localizer/iso8601-localizer.d.ts +++ b/iso8601-localizer/iso8601-localizer.d.ts @@ -1,4 +1,4 @@ -// Type definitions for ISO8601-Localizer v1.2.0 +// Type definitions for ISO8601-Localizer v1.2.1 // Project: https://github.com/avielfedida/ISO8601-Localizer // Definitions by: Aviel Fedida // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -15,3 +15,7 @@ declare class ISO8601Localizer implements localizer { returnAs(as: string): localizer; localize(): string; } + +declare module "iso8601-localizer" { + export = ISO8601Localizer; +} \ No newline at end of file From 11689e16782fc33eac7e3837c63c2400b35c50e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20Corbi=C3=A8re?= Date: Sat, 15 Aug 2015 16:34:43 +0200 Subject: [PATCH 122/614] Add type definitions for lazypipe --- lazypipe/lazypipe-tests.ts | 18 ++++++++++++++++++ lazypipe/lazypipe.d.ts | 31 +++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 lazypipe/lazypipe-tests.ts create mode 100644 lazypipe/lazypipe.d.ts diff --git a/lazypipe/lazypipe-tests.ts b/lazypipe/lazypipe-tests.ts new file mode 100644 index 000000000..cd3d3a7fb --- /dev/null +++ b/lazypipe/lazypipe-tests.ts @@ -0,0 +1,18 @@ +/// +/// +/// +/// + +import * as gulp from "gulp"; +import minifyHtml = require("gulp-minify-html"); +import size = require("gulp-size"); +import lazypipe = require("lazypipe"); + +const pipeline = lazypipe() + .pipe(size) + .pipe(minifyHtml, {}) + .pipe(size); + +gulp.src("*.html") + .pipe(pipeline()) + .pipe(gulp.dest("build")); diff --git a/lazypipe/lazypipe.d.ts b/lazypipe/lazypipe.d.ts new file mode 100644 index 000000000..c0fd43ac2 --- /dev/null +++ b/lazypipe/lazypipe.d.ts @@ -0,0 +1,31 @@ +// Type definitions for lazypipe +// Project: https://github.com/OverZealous/lazypipe +// Definitions by: Thomas Corbière +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "lazypipe" +{ + interface IPipelineBuilder + { + /** + * Returns a stream where all the internal steps are processed sequentially + * and the final result is passed on. + */ + (): NodeJS.ReadWriteStream; + + /** + * Creates a new lazy pipeline with all the previous steps, and the new step added to the end. + * @param fn A stream creation function to call when the pipeline is created later. + * @param args Any remaining arguments are saved and passed into fn when the pipeline is created. + */ + pipe(fn: Function, ...args: any[]): IPipelineBuilder; + } + + /** + * Initializes a lazypipe. + */ + function lazypipe(): IPipelineBuilder; + export = lazypipe; +} From 7babb2704cd547042d01d73c7c341074469d163b Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Sat, 15 Aug 2015 22:18:59 +0500 Subject: [PATCH 123/614] lodash: changed _.property() method --- lodash/lodash-tests.ts | 12 ++++++++++++ lodash/lodash.d.ts | 25 +++++++++++++++++++------ 2 files changed, 31 insertions(+), 6 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 9d87e2a37..546e338bf 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1490,6 +1490,18 @@ result = _.result(object, 'stuff'); var tempObject = {}; result = _.runInContext(tempObject); +// _.property +interface TestPropertyObject { + a: { + b: number; + } +} +var testPropertyObject: TestPropertyObject; +result = _.property('a.b')(testPropertyObject); +result = _.property(['a', 'b'])(testPropertyObject); +result = (_('a.b').property().value())(testPropertyObject); +result = (_(['a', 'b']).property().value())(testPropertyObject); + // _.propertyOf interface TestPropertyOfObject { a: { diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index b2603ee95..b5fa0d479 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -7397,12 +7397,25 @@ declare module _ { //_.property interface LoDashStatic { /** - * # S - * Creates a "_.pluck" style function, which returns the key value of a given object. - * @param key (string) - * @return the value of that key on the object - **/ - property(key: string): (obj: T) => RT; + * Creates a function that returns the property value at path on a given object. + * @param path The path of the property to get. + * @return Returns the new function. + */ + property(path: string|string[]): (obj: TObj) => TResult; + } + + interface LoDashStringWrapper { + /** + * @see _.property + */ + property(): LoDashObjectWrapper<(obj: TObj) => TResult>; + } + + interface LoDashArrayWrapper { + /** + * @see _.property + */ + property(): LoDashObjectWrapper<(obj: TObj) => TResult>; } //_.propertyOf From 88a353262bd90766820c8140d37d89cd0e733bbf Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Sat, 15 Aug 2015 22:52:10 +0500 Subject: [PATCH 124/614] lodash: changed _.range() method --- lodash/lodash-tests.ts | 15 ++++++----- lodash/lodash.d.ts | 58 ++++++++++++++++++++++++------------------ 2 files changed, 41 insertions(+), 32 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 9d87e2a37..c95515487 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -303,13 +303,6 @@ result = <_.LoDashObjectWrapper<_.Dictionary>>_([['moe', 30], ['larry', 40] result = _.pull([1, 2, 3, 1, 2, 3], 2, 3); result = _.pullAt([1, 2, 3, 1, 2, 3], 2, 3); -result = _.range(10); -result = _.range(1, 11); -result = _.range(0, 30, 5); -result = _.range(0, -10, -1); -result = _.range(1, 4, 0); -result = _.range(0); - result = _.remove([1, 2, 3, 4, 5, 6], function (num: number) { return num % 2 == 0; }); result = _.remove(foodsOrganic, 'organic'); result = _.remove(foodsType, { 'type': 'vegetable' }); @@ -1501,6 +1494,14 @@ result = <(path: string|string[]) => any>_.propertyOf({}); result = <(path: string|string[]) => any>_.propertyOf(testPropertyOfObject); result = <(path: string|string[]) => any>_({}).propertyOf().value(); +// _.range +result = _.range(10); +result = _.range(1, 11); +result = _.range(0, 30, 5); +result = _(10).range().value(); +result = _(1).range(11).value(); +result = _(0).range(30, 5).value(); + result = <_.TemplateExecutor>_.template('hello <%= name %>'); result = _.template('<%- value %>', { 'value': ''); dompurify.addHook('beforeSanitizeElements', (el, data, config) => { return el; }); + +//examples from the DOMPurify README +let dirty = '

    Totally safe

    Totally not safe

    '; + +// allow only +dompurify.sanitize(dirty, {ALLOWED_TAGS: ['b']}); + +// allow only and with style attributes (for whatever reason) +dompurify.sanitize(dirty, {ALLOWED_TAGS: ['b', 'q'], ALLOWED_ATTR: ['style']}); + +// leave all as it is but forbid