From 65d386f2de01f5399bc3010002058b3e04a32fea Mon Sep 17 00:00:00 2001 From: Roland Zwaga Date: Thu, 31 Jul 2014 09:23:37 +0200 Subject: [PATCH 001/794] 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/794] 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/794] 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/794] 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/794] 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/794] 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/794] 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/794] 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/794] 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/794] 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/794] 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/794] 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/794] 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/794] 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/794] 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/794] 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/794] 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/794] 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/794] 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/794] 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/794] 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/794] 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/794] 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/794] 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/794] 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/794] 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/794] 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/794] 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/794] 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/794] 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/794] 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/794] 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/794] 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/794] 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 76ea613b90f40db3afae3ff77c21298d13775257 Mon Sep 17 00:00:00 2001 From: Gabriel Garcia Date: Mon, 20 Jul 2015 18:49:06 -0400 Subject: [PATCH 035/794] localforage typings --- localForage/localForage.d.ts | 135 ++++++++++++++++++----------------- 1 file changed, 70 insertions(+), 65 deletions(-) diff --git a/localForage/localForage.d.ts b/localForage/localForage.d.ts index b5c40dd61..6deef5277 100644 --- a/localForage/localForage.d.ts +++ b/localForage/localForage.d.ts @@ -3,71 +3,76 @@ // Definitions by: yuichi david pichsenmeister // Definitions: https://github.com/borisyankov/DefinitelyTyped -declare module lf { - interface ILocalForage { - /** - * Removes every key from the database, returning it to a blank slate. - */ - clear(callback: IErrorCallback): void - /** - * Iterate over all value/key pairs in datastore. - */ - iterate(iterateCallback: IIterateCallback): void - /** - * Get the name of a key based on its ID. - */ - key(keyIndex: number, callback: IKeyCallback): void - /** - * Get the list of all keys in the datastore. - */ - keys(callback: IKeysCallback): void; - /** - * Gets the number of keys in the offline store (i.e. its “length”). - */ - length(callback: INumberCallback): void - /** - * Gets an item from the storage library and supplies the result to a callback. - * If the key does not exist, getItem() will return null. - */ - getItem(key: string, callback: ICallback): void - getItem(key: string): IPromise - /** - * Saves data to an offline store. - */ - setItem(key: string, value: T, callback: ICallback): void - setItem(key: string, value: T): IPromise - /** - * Removes the value of a key from the offline store. - */ - removeItem(key: string, callback: IErrorCallback): void - removeItem(key: string): IPromise - } +/// - interface ICallback { - (err: any, value: T): void - } +interface LocalForageOptions { + driver?: LocalForageDriver | LocalForageDriver[]; + + name?: string; + + size?: number; + + storeName?: string; + + version?: string; + + description?: string; +} - interface IIterateCallback { - (value: T, key: string, iterationNumber: number): void - } +interface LocalForageDriver { + _driver: string; + + _initStorage(options: LocalForageOptions): void; + + _support: boolean | Promise; + + clear(callback: (err: any) => void): void; + + getItem(key: string, callback: (err: any, value: any) => void): void; + + key(keyIndex: number, callback: (err: any, key: string) => void): void; + + keys(callback: (err: any, keys: string[]) => void): void; + + length(callback: (err: any, numberOfKeys: number) => void): void; + + removeItem(key: string, callback: (err: any) => void): void; + + setItem(key: string, value: any, callback: (err: any, value: any) => void): void; +} - interface IErrorCallback { - (err: any): void - } - - interface IKeyCallback { - (err: any, keyName: string): void - } - - interface IKeysCallback { - (err: any, keys: Array): void - } - - interface INumberCallback { - (err: any, numberOfKeys: number): void - } - - interface IPromise { - then(callback: ICallback): void - } -} \ No newline at end of file +interface LocalForage { + LOCALSTORAGE: LocalForageDriver; + WEBSQL: LocalForageDriver; + INDEXEDDB: LocalForageDriver; + + config(options: LocalForageOptions): void; + + setDriver(driver: LocalForageDriver): void; + setDriver(driver: LocalForageDriver[]): void; + + getItem(key: string): Promise; + getItem(key: string, callback: (err: any, value: T) => void): void; + + setItem(key: string, value: T): Promise; + setItem(key: string, value: T, callback: (err: any, value: T) => void): void; + + removeItem(key: string): Promise; + removeItem(key: string, callback: (err: any) => void): void; + + clear(): Promise; + clear(callback: (err: any) => void): void; + + length(): Promise; + length(callback: (err: any, numberOfKeys: number) => void): void; + + key(keyIndex: number): Promise; + key(keyIndex: number, callback: (err: any, key: string) => void): void; + + keys(): Promise; + keys(callback: (err: any, keys: string[]) => void): void; + + iterate(iteratee: (value: any, key: string, iterationNumber: number) => any): Promise; + iterate(iteratee: (value: any, key: string, iterationNumber: number) => any, + callback: (err: any, result: any) => void): void; +} From e7335515d8bd5a258087918530842595554b909c Mon Sep 17 00:00:00 2001 From: Gabriel Garcia Date: Fri, 24 Jul 2015 18:01:38 -0400 Subject: [PATCH 036/794] Update localForage tests --- localForage/localForage-tests.ts | 25 ++++++------------------- 1 file changed, 6 insertions(+), 19 deletions(-) diff --git a/localForage/localForage-tests.ts b/localForage/localForage-tests.ts index 15638c1cb..59e429a76 100644 --- a/localForage/localForage-tests.ts +++ b/localForage/localForage-tests.ts @@ -1,13 +1,6 @@ /// -declare var localForage: lf.ILocalForage; -declare var callback: lf.ICallback; -declare var iterateCallback: lf.IIterateCallback; -declare var errorCallback: lf.IErrorCallback; -declare var keyCallback: lf.IKeyCallback; -declare var keysCallback: lf.IKeysCallback; -declare var numberCallback: lf.INumberCallback; -declare var promise: lf.IPromise; +declare var localForage: LocalForage; () => { localForage.clear((err: any) => { @@ -25,7 +18,7 @@ declare var promise: lf.IPromise; var newNumber: number = num; }); - localForage.key(0,(err: any, value: string) => { + localForage.key(0, (err: any, value: string) => { var newError: any = err; var newValue: string = value; }); @@ -40,9 +33,8 @@ declare var promise: lf.IPromise; var newStr: string = str }); - localForage.getItem("key").then((err: any, str: string) => { - var newError: any = err; - var newStr: string = str + localForage.getItem("key").then((str: string) => { + var newStr: string = str; }); localForage.setItem("key", "value",(err: any, str: string) => { @@ -50,8 +42,7 @@ declare var promise: lf.IPromise; var newStr: string = str }); - localForage.setItem("key", "value").then((err: any, str: string) => { - var newError: any = err; + localForage.setItem("key", "value").then((str: string) => { var newStr: string = str; }); @@ -59,10 +50,6 @@ declare var promise: lf.IPromise; var newError: any = err; }); - localForage.removeItem("key").then((err: any, str: string) => { - var newError: any = err; - var newStr: string = str + localForage.removeItem("key").then(() => { }); - - promise.then(callback); } From 90d7feb531e0935de1eebbac1bb5bedf8ab5ccc1 Mon Sep 17 00:00:00 2001 From: Gabriel Garcia Date: Fri, 24 Jul 2015 18:18:58 -0400 Subject: [PATCH 037/794] Correct misunderstanding of documentation --- angular-localForage/angular-localForage.d.ts | 4 ++-- localForage/localForage.d.ts | 13 ++++++++----- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/angular-localForage/angular-localForage.d.ts b/angular-localForage/angular-localForage.d.ts index ee2aeeb6d..c7a8f7dae 100644 --- a/angular-localForage/angular-localForage.d.ts +++ b/angular-localForage/angular-localForage.d.ts @@ -22,8 +22,8 @@ declare module angular.localForage { } interface ILocalForageService { - setDriver(driver:string):angular.IPromise; - driver():lf.ILocalForage; + driver(): LocalForageDriver; + setDriver(name: string | string[]): angular.IPromise; setItem(key:string, value:any):angular.IPromise; setItem(keys:Array, values:Array):angular.IPromise; diff --git a/localForage/localForage.d.ts b/localForage/localForage.d.ts index 6deef5277..d169d01e3 100644 --- a/localForage/localForage.d.ts +++ b/localForage/localForage.d.ts @@ -42,14 +42,17 @@ interface LocalForageDriver { } interface LocalForage { - LOCALSTORAGE: LocalForageDriver; - WEBSQL: LocalForageDriver; - INDEXEDDB: LocalForageDriver; + LOCALSTORAGE: string; + WEBSQL: string; + INDEXEDDB: string; config(options: LocalForageOptions): void; - setDriver(driver: LocalForageDriver): void; - setDriver(driver: LocalForageDriver[]): void; + driver(): LocalForageDriver; + setDriver(driver: string | string[]): Promise; + setDriver(driver: string | string[], callback: () => void, errorCallback: (error: any) => void): void; + defineDriver(driver: LocalForageDriver): Promise; + defineDriver(driver: LocalForageDriver, callback: () => void, errorCallback: (error: any) => void): void; getItem(key: string): Promise; getItem(key: string, callback: (err: any, value: T) => void): void; From c1b2c0c40d6d0ee60677425996e758fb1274c468 Mon Sep 17 00:00:00 2001 From: Dan Lewi Harkestad Date: Tue, 4 Aug 2015 14:04:32 +0200 Subject: [PATCH 038/794] 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 039/794] 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 040/794] 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 041/794] 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 042/794] 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 043/794] 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 044/794] 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 045/794] 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 046/794] 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 047/794] 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 048/794] 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 049/794] 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 050/794] 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 051/794] 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 052/794] 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 053/794] 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 054/794] 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 055/794] 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 056/794] 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 057/794] 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 058/794] 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 059/794] 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 060/794] 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 061/794] 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 062/794] 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 063/794] 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 064/794] 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 065/794] 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 066/794] '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 52854d5f1c46796481428d3ab7be722b6c47c869 Mon Sep 17 00:00:00 2001 From: Greg Smith Date: Mon, 10 Aug 2015 13:17:20 -0500 Subject: [PATCH 067/794] 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 068/794] 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 069/794] 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 070/794] 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 071/794] 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 072/794] 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 073/794] '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 074/794] 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 075/794] 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 076/794] '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 077/794] 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 078/794] '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 079/794] 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 080/794] 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 081/794] 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 082/794] 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 083/794] 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 084/794] 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 085/794] 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 086/794] 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 087/794] 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 088/794] 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 089/794] 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 090/794] 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 091/794] 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 092/794] 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 2ffed1fde1f93a62480e2191e2f320e61b7cd63a Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Wed, 12 Aug 2015 12:21:13 -0700 Subject: [PATCH 093/794] 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 094/794] 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 5e48f1bdb2c038e036d4fdbca745588b7580363b Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Wed, 12 Aug 2015 15:28:34 -0700 Subject: [PATCH 095/794] 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 096/794] 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 097/794] '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 098/794] '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 099/794] 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 100/794] 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 101/794] 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 102/794] 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 103/794] 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 104/794] 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 105/794] 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 106/794] 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 107/794] 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 108/794] 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 109/794] 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 110/794] 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 111/794] 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 112/794] 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 113/794] '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 114/794] 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 5d0102d544c46020090d8cea9fb6ec82e7997650 Mon Sep 17 00:00:00 2001 From: Almouro Date: Sat, 15 Aug 2015 20:20:49 +0200 Subject: [PATCH 115/794] Add ability to create element without using load --- cheerio/cheerio-tests.ts | 2 ++ cheerio/cheerio.d.ts | 19 +++++++++++++------ 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/cheerio/cheerio-tests.ts b/cheerio/cheerio-tests.ts index af671cd00..c02b1ed26 100644 --- a/cheerio/cheerio-tests.ts +++ b/cheerio/cheerio-tests.ts @@ -2,6 +2,8 @@ import cheerio = require("cheerio"); +cheerio(''); + var $ = cheerio.load(""); var $el = $('selector'); var $multiEl = $('seletor', 'selector', 'selector'); diff --git a/cheerio/cheerio.d.ts b/cheerio/cheerio.d.ts index fc8e5a70f..bbd47810f 100644 --- a/cheerio/cheerio.d.ts +++ b/cheerio/cheerio.d.ts @@ -172,11 +172,7 @@ interface CheerioOptionsInterface { normalizeWhitespace?: boolean; } -interface CheerioStatic { - // Document References - // Cheerio https://github.com/cheeriojs/cheerio - // JQuery http://api.jquery.com - +interface CheerioSelector { (selector: string): Cheerio; (selector: string, context: string): Cheerio; (selector: string, context: CheerioElement): Cheerio; @@ -187,7 +183,12 @@ interface CheerioStatic { (selector: string, context: CheerioElement[], root: string): Cheerio; (selector: string, context: Cheerio, root: string): Cheerio; (selector: any): Cheerio; +} +interface CheerioStatic extends CheerioSelector { + // Document References + // Cheerio https://github.com/cheeriojs/cheerio + // JQuery http://api.jquery.com xml(): string; root(): Cheerio; contains(container: CheerioElement, contained: CheerioElement): boolean; @@ -213,6 +214,12 @@ interface CheerioElement { root: CheerioElement; } +interface CheerioAPI extends CheerioSelector { + load(html: string, options?: CheerioOptionsInterface): CheerioStatic; +} + +declare var cheerio:CheerioAPI; + declare module "cheerio" { - export function load(html: string, options?: CheerioOptionsInterface): CheerioStatic; + export = CheerioAPI; } From 2004f8fc47187af24b8d5ba9ae96e6ebf81f6a35 Mon Sep 17 00:00:00 2001 From: Almouro Date: Sat, 15 Aug 2015 20:21:35 +0200 Subject: [PATCH 116/794] Updated definition and tests to reflect Cheerio doc --- cheerio/cheerio-tests.ts | 335 ++++++++++++++++++++++++++++++++------- cheerio/cheerio.d.ts | 46 +++++- 2 files changed, 322 insertions(+), 59 deletions(-) diff --git a/cheerio/cheerio-tests.ts b/cheerio/cheerio-tests.ts index c02b1ed26..6cc9e6485 100644 --- a/cheerio/cheerio-tests.ts +++ b/cheerio/cheerio-tests.ts @@ -1,67 +1,294 @@ /// -import cheerio = require("cheerio"); +import cheerio = require('cheerio'); -cheerio(''); +/* + * LOADING + */ +let html = +`
      +
    • Apple
    • +
    • Orange
    • +
    • Pear
    • + +
    `; -var $ = cheerio.load(""); -var $el = $('selector'); -var $multiEl = $('seletor', 'selector', 'selector'); +// Preferred Method +var $ = cheerio.load(html); +// Directly load element +cheerio(html); +cheerio('ul', html); +cheerio('li', 'ul', html); -$el.addClass("class").addClass("test"); -$el.hasClass("test"); -$el.removeClass("class").removeClass("test"); - -$el.attr('class'); -$el.attr('class', 'test'); -$el.removeAttr("class").removeAttr("test"); - -$el.find("ul").find("> li"); - -$el.parent().parent(); -$el.next().next(); -$el.prev().prev(); -$el.siblings().siblings(); - -$el.children().children(); -$el.children("li").children("a"); - -$el.children().each((index, element) => { - return $(element).find('t'); +$ = cheerio.load(html, { + normalizeWhitespace: true, + xmlMode: true }); -$el.children().map((index, element) => { - return $(element).find('t'); +$ = cheerio.load(html, { + normalizeWhitespace: true, + xmlMode: true, + decodeEntities: true, + lowercaseTags: true, + lowerCaseAttributeNames: true, + recognizeCDATA: true, + recognizeSelfClosing: true }); -$el.children().filter((index) => { - return $el.children().eq(index).find('t').length >= 0; -}); +/** + * Selectors + */ +var $el = $('.class'); +var $multiEl = $('selector', 'selector', 'selector'); -$el.filter('span').filter('li'); +/** + * Attributes + */ -$el.first().last().find('t'); - -$('div').eq(0).find('b'); - -$('#id').append("test html", "other html").find('a'); -$('#id').prepend("test html", "other html").find('a'); -$('#id').after("test html", "other html").find('a'); -$('#id').before("test html", "other html").find('a'); - -$el.remove('div').remove('a'); - -$('#id').replaceWith('some html').parent(); -$('#id').empty().parent(); - -$el.html(); -$el.html("").find('div'); - -$el.text(); -$el.text('some text'); - -$el.toArray(); -$el.clone().find('a').parent(); -$.root().find('a'); +// attr +$el.attr('id'); +$el.attr('id', 'favorite').html(); +// data $el.data(); +$el.data('apple-color'); +$el.data('kind', 'mac'); + +// val +$('input[type="text"]').val(); +$('input[type="text"]').val('test').html(); + +// removeAttr +$el.removeAttr('class').html(); + +// hasClass, addClass, removeClass, toggleClass +$el.addClass('class').addClass('test'); +$el.hasClass('test'); +$el.removeClass('class').removeClass('test'); +$el.addClass('red').removeClass().html(); +$el.toggleClass('fruit green red').html(); + +// is +$el.is('#id'); +$el.is($el); +$el.is(() => { + return true; +}); + +/** + * Forms + */ +// serializeArray +$('
    ').serializeArray(); + +/** + * Traversing + */ + // find +$el.find('li').length; +$el.find($('.apple')).length; + +// .parent([selector]) +$el.parent().attr('id'); +$el.parent('.class').attr('id'); + +// .parents([selector]) +$el.parents().length; +$el.parents('.class').length; + +// .parentsUntil([selector][,filter]) +$el.parentsUntil().length; +$el.parentsUntil('.class').length; + +// .closest(selector) +$el.closest(); +$el.closest('.class'); + +// .next([selector]) +$el.next().hasClass('class'); +$el.next('.class').hasClass('class'); + +// .nextAll([selector]) +$el.nextAll().length; +$el.nextAll('.class').length; + +// .nextUntil([selector], [filter]) +$el.nextUntil(); +$el.nextUntil('.class'); + +// .prev([selector]) +$el.prev().hasClass('class'); +$el.prev('.class').hasClass('class'); + +// .prevAll([selector]) +$el.prevAll().length; +$el.prevAll('.class').length; + +// .prevUntil([selector], [filter]) +$el.prevUntil(); +$el.prevUntil('.class'); + +// .slice( start, [end] ) +$el.slice(1).eq(0).text(); +$el.slice(1, 2).length; + +// .siblings([selector]) +$el.siblings().length; +$el.siblings('.class').length; + +// .children([selector]) +$el.children().length; +$el.children('.class').text(); + +// .contents() +$el.contents().length; + +// .each( function(index, element) ) +$el.each((i, el) => { + $(el).html(); +}); + +// .map( function(index, element) ) +$el.map((i, el) => { + return $(el).text(); +}).get().join(' '); + +// .filter +$ = cheerio.load(html); +$el.filter('.class').attr('class'); +$el.filter($('.class')).attr('class'); +$el.filter($('.class')[0]).attr('class'); + +$el.filter((i, el) => { + return $(el).attr('class') === 'class'; +}).attr('class'); + +// .not +$el.not('.class').length; +$el.not($('.class')).length; +$el.not($('.class')[0]).length; + +$el.not((i, el) => { + return $(el).attr('class') === 'class'; +}).length; + +// .has +$el.has('.class').attr('id'); +$el.has($el[0]).attr('id'); + +// .first() +$el.children().first().text(); + +// .last() +$el.children().last().text(); + +// .eq( i ) +$el.eq(0).text(); +$el.eq(-1).text(); + +// .get( [i] ) +$el.get(0).tagName; +$el.get().length; + +// .index() +// .index( selector ) +// .index( nodeOrSelection ) +$el.index(); +$el.index('li'); +$el.index($('#fruit, li')); + +// .end() +$el.eq(0).end().length; + +// .add +$el.add('.class').length + +// .addBack( [filter] ) +$el.eq(0).addBack().length +$el.eq(0).addBack('.class').length + +/** + * Manipulation + */ + +// .append( content, [content, ...] ) +$el.append('
  • Plum
  • ').html(); +$el.append('
  • Plum
  • ', '
  • Plum
  • ').html(); + +// .prepend( content, [content, ...] ) +$el.prepend('
  • Plum
  • ').html(); +$el.prepend('
  • Plum
  • ', '
  • Plum
  • ').html(); + +// .after( content, [content, ...] ) +$el.after('
  • Plum
  • ').html(); +$el.after('
  • Plum
  • ', '
  • Plum
  • ').html(); + +// .insertAfter( content ) +$('
  • Plum
  • ').insertAfter('.class').html(); + +// .before( content, [content, ...] ) +$el.before('
  • Plum
  • ').html(); +$el.before('
  • Plum
  • ', '
  • Plum
  • ').html(); + +// .insertBefore( content ) +$('
  • Plum
  • ').insertBefore('.class').html(); + +// .remove( [selector] ) +$el.remove().html(); +$el.remove('.class').html(); + +// .replaceWith( content ) +$el.replaceWith($('
  • Plum
  • ')).html(); + +// .empty() +$el.empty().html(); + +// .html( [htmlString] ) +$el.html(); +$el.html('
  • Mango
  • ').html(); + +// .text( [textString] ) +$el.text(); +$el.text('text'); + +// .wrap( content ) +// See https://github.com/cheeriojs/cheerio/issues/731 +// $el.wrap($('
    ')).html(); + +// .css +$el.css('width'); +$el.css(['width', 'height']); +$el.css('width', '50px'); + +/** + * Rendering + */ +$.html(); +$.html('.class'); +$.xml(); + +/** + * Miscellaneous + */ + +// .clone() #### +$el.clone().html(); + +/** + * Utilities + */ + +// $.root +$.root().append('
      ').html(); + +// $.contains( container, contained ) +$.contains($el[0], $el[0]); + +// $.parseHTML( data [, context ] [, keepScripts ] ) +$.parseHTML(html); +$.parseHTML(html, null, true); + +/** + * Not in doc + */ +$el.toArray(); diff --git a/cheerio/cheerio.d.ts b/cheerio/cheerio.d.ts index bbd47810f..840cceef5 100644 --- a/cheerio/cheerio.d.ts +++ b/cheerio/cheerio.d.ts @@ -17,12 +17,17 @@ interface Cheerio { attr(name: string, value: any): Cheerio; data(): any; + data(name: string): any; + data(name: string, value: any): any; val(): string; val(value: string): Cheerio; removeAttr(name: string): Cheerio; + has(selector: string): Cheerio; + has(element: CheerioElement): Cheerio; + hasClass(className: string): boolean; addClass(classNames: string): Cheerio; @@ -41,6 +46,9 @@ interface Cheerio { is(selection: Cheerio): boolean; is(func: (index: number, element: CheerioElement) => boolean): boolean; + // Form + serializeArray(): {name: string, value: string}[]; + // Traversing find(selector: string): Cheerio; @@ -52,10 +60,12 @@ interface Cheerio { parentsUntil(element: CheerioElement, filter?: string): Cheerio; parentsUntil(element: Cheerio, filter?: string): Cheerio; + closest(): Cheerio; closest(selector: string): Cheerio; next(selector?: string): Cheerio; nextAll(): Cheerio; + nextAll(selector: string): Cheerio; nextUntil(selector?: string, filter?: string): Cheerio; nextUntil(element: CheerioElement, filter?: string): Cheerio; @@ -63,6 +73,7 @@ interface Cheerio { prev(selector?: string): Cheerio; prevAll(): Cheerio; + prevAll(selector: string): Cheerio; prevUntil(selector?: string, filter?: string): Cheerio; prevUntil(element: CheerioElement, filter?: string): Cheerio; @@ -83,15 +94,24 @@ interface Cheerio { filter(selection: Cheerio): Cheerio; filter(element: CheerioElement): Cheerio; filter(elements: CheerioElement[]): Cheerio; - filter(func: (index: number) => boolean): Cheerio; + filter(func: (index: number, element: CheerioElement) => boolean): Cheerio; + + not(selector: string): Cheerio; + not(selection: Cheerio): Cheerio; + not(element: CheerioElement): Cheerio; + not(func: (index: number, element: CheerioElement) => boolean): Cheerio; first(): Cheerio; last(): Cheerio; eq(index: number): Cheerio; - get(): Document[]; - get(index: number): Document; + get(): CheerioElement[]; + get(index: number): CheerioElement; + + index(): number; + index(selector: string): number; + index(selection: Cheerio): number; end(): Cheerio; @@ -101,6 +121,9 @@ interface Cheerio { add(elements: CheerioElement[]): Cheerio; add(selection: Cheerio): Cheerio; + addBack():Cheerio; + addBack(filter: string):Cheerio; + // Manipulation append(content: string, ...contents: any[]): Cheerio; @@ -118,11 +141,19 @@ interface Cheerio { after(content: Document[], ...contents: any[]): Cheerio; after(content: Cheerio, ...contents: any[]): Cheerio; + insertAfter(content: string): Cheerio; + insertAfter(content: Document): Cheerio; + insertAfter(content: Cheerio): Cheerio; + before(content: string, ...contents: any[]): Cheerio; before(content: Document, ...contents: any[]): Cheerio; before(content: Document[], ...contents: any[]): Cheerio; before(content: Cheerio, ...contents: any[]): Cheerio; + insertBefore(content: string): Cheerio; + insertBefore(content: Document): Cheerio; + insertBefore(content: Cheerio): Cheerio; + remove(selector?: string): Cheerio; replaceWith(content: string): Cheerio; @@ -138,6 +169,11 @@ interface Cheerio { text(): string; text(text: string): Cheerio; + // See https://github.com/cheeriojs/cheerio/issues/731 + /*wrap(content: string): Cheerio; + wrap(content: Document): Cheerio; + wrap(content: Cheerio): Cheerio;*/ + css(propertyName: string): string; css(propertyNames: string[]): string[]; css(propertyName: string, value: string): Cheerio; @@ -203,7 +239,7 @@ interface CheerioStatic extends CheerioSelector { interface CheerioElement { // Document References // Node Console - + tagName: string; type: string; name: string; attribs: Object; @@ -221,5 +257,5 @@ interface CheerioAPI extends CheerioSelector { declare var cheerio:CheerioAPI; declare module "cheerio" { - export = CheerioAPI; + export = cheerio; } From 3e6f9cbd89c1e8df81a0ffb16cbc8bab965881ae Mon Sep 17 00:00:00 2001 From: Almouro Date: Sun, 16 Aug 2015 11:51:43 +0200 Subject: [PATCH 117/794] Support ES6 import syntax --- cheerio/cheerio-tests.ts | 2 +- cheerio/cheerio.d.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cheerio/cheerio-tests.ts b/cheerio/cheerio-tests.ts index 6cc9e6485..c41939a30 100644 --- a/cheerio/cheerio-tests.ts +++ b/cheerio/cheerio-tests.ts @@ -1,6 +1,6 @@ /// -import cheerio = require('cheerio'); +import cheerio from 'cheerio'; /* * LOADING diff --git a/cheerio/cheerio.d.ts b/cheerio/cheerio.d.ts index 840cceef5..8118d3366 100644 --- a/cheerio/cheerio.d.ts +++ b/cheerio/cheerio.d.ts @@ -257,5 +257,5 @@ interface CheerioAPI extends CheerioSelector { declare var cheerio:CheerioAPI; declare module "cheerio" { - export = cheerio; + export default cheerio; } From 81166431feac33c727dc0b02014b7265efa85c32 Mon Sep 17 00:00:00 2001 From: Almouro Date: Sun, 16 Aug 2015 12:12:43 +0200 Subject: [PATCH 118/794] Updated Cheerio Element definition according to doc --- cheerio/cheerio.d.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/cheerio/cheerio.d.ts b/cheerio/cheerio.d.ts index 8118d3366..57d526d1b 100644 --- a/cheerio/cheerio.d.ts +++ b/cheerio/cheerio.d.ts @@ -244,10 +244,15 @@ interface CheerioElement { name: string; attribs: Object; children: CheerioElement[]; + childNodes: CheerioElement[]; + lastChild: CheerioElement; next: CheerioElement; + nextSibling: CheerioElement; prev: CheerioElement; + previousSibling: CheerioElement; parent: CheerioElement; - root: CheerioElement; + parentNode: CheerioElement; + nodeValue: string; } interface CheerioAPI extends CheerioSelector { From d34aa2d731960f59d8fc6ebfd88679582369c2d7 Mon Sep 17 00:00:00 2001 From: rhysd Date: Mon, 17 Aug 2015 16:49:39 +0900 Subject: [PATCH 119/794] Added WebContents.print(), webContents.printToPDF() and aliases for BrowserWindow Added definitions for below APIs. - `WebContents.print([options])` https://github.com/atom/electron/blob/master/docs/api/browser-window.md#webcontentsprintoptions - `WebContents.printToPDF(options, callback)` https://github.com/atom/electron/blob/master/docs/api/browser-window.md#webcontentsprinttopdfoptions-callback - `BrowserWindow`'s aliases' https://github.com/atom/electron/blob/master/docs/api/browser-window.md#browserwindowprintoptions --- github-electron/github-electron-main-tests.ts | 29 ++++++++ github-electron/github-electron.d.ts | 73 +++++++++++++++++-- 2 files changed, 96 insertions(+), 6 deletions(-) diff --git a/github-electron/github-electron-main-tests.ts b/github-electron/github-electron-main-tests.ts index d353dfeb3..14480059c 100644 --- a/github-electron/github-electron-main-tests.ts +++ b/github-electron/github-electron-main-tests.ts @@ -51,6 +51,35 @@ app.on('ready', () => { // when you should delete the corresponding element. mainWindow = null; }); + + mainWindow.print({silent: true, printBackground: false}); + mainWindow.webContents.print({silent: true, printBackground: false}); + mainWindow.print(); + mainWindow.webContents.print(); + + mainWindow.print({silent: true, printBackground: false}); + mainWindow.webContents.print({silent: true, printBackground: false}); + mainWindow.print(); + mainWindow.webContents.print(); + + mainWindow.printToPDF({ + marginsType: 1, + pageSize: 'A3', + printBackground: true, + printSelectionOnly: true, + landscape: true, + }, (error: Error, data: Buffer) => {}); + + mainWindow.webContents.printToPDF({ + marginsType: 1, + pageSize: 'A3', + printBackground: true, + printSelectionOnly: true, + landscape: true, + }, (error: Error, data: Buffer) => {}); + + mainWindow.printToPDF({}, (err, data) => {}); + mainWindow.webContents.printToPDF({}, (err, data) => {}); }); // Desktop environment integration diff --git a/github-electron/github-electron.d.ts b/github-electron/github-electron.d.ts index 5df526bfc..5624b406b 100644 --- a/github-electron/github-electron.d.ts +++ b/github-electron/github-electron.d.ts @@ -377,17 +377,22 @@ declare module GitHubElectron { capturePage(rect: Rectangle, callback: (image: NativeImage) => void): void; capturePage(callback: (image: NativeImage) => void): void; /** - * Prints the window's web page. Calling window.print() in a web page is - * equivalent to calling BrowserWindow.print({silent: false, printBackground: false}). + * Same with webContents.print([options]) */ print(options?: { - /** - * When false, Electron will pick up system's default printer and default - * settings for printing. - */ silent?: boolean; printBackground?: boolean; }): void; + /** + * Same with webContents.printToPDF([options]) + */ + printToPDF(options: { + marginsType?: number; + pageSize?: string; + printBackground?: boolean; + printSelectionOnly?: boolean; + landscape?: boolean; + }, callback: (error: Error, data: Buffer) => void): void; /** * Same with webContents.loadUrl(url). */ @@ -659,6 +664,62 @@ declare module GitHubElectron { * @param isFulfilled Whether the JS promise is fulfilled. */ (isFulfilled: boolean) => void): void; + /** + * + * Prints window's web page. When silent is set to false, Electron will pick up system's default printer and default settings for printing. + * Calling window.print() in web page is equivalent to call WebContents.print({silent: false, printBackground: false}). + * Note: + * On Windows, the print API relies on pdf.dll. If your application doesn't need print feature, you can safely remove pdf.dll in saving binary size. + */ + print(options?: { + /** + * Don't ask user for print settings, defaults to false + */ + silent?: boolean; + /** + * Also prints the background color and image of the web page, defaults to false. + */ + printBackground: boolean; + }): void; + /** + * Prints windows' web page as PDF with Chromium's preview printing custom settings. + */ + printToPDF(options: { + /** + * Specify the type of margins to use. Default is 0. + * 0 - default + * 1 - none + * 2 - minimum + */ + marginsType?: number; + /** + * String - Specify page size of the generated PDF. Default is A4. + * A4 + * A3 + * Legal + * Letter + * Tabloid + */ + pageSize?: string; + /** + * Whether to print CSS backgrounds. Default is false. + */ + printBackground?: boolean; + /** + * Whether to print selection only. Default is false. + */ + printSelectionOnly?: boolean; + /** + * true for landscape, false for portrait. Default is false. + */ + landscape?: boolean; + }, + /** + * Callback function on completed converting to PDF. + * error Error + * data Buffer - PDF file content + */ + callback: (error: Error, data: Buffer) => void): void; /** * Send args.. to the web page via channel in asynchronous message, the web page * can handle it by listening to the channel event of ipc module. From 240061021b321a7729a660f518ea61037b37bdcb Mon Sep 17 00:00:00 2001 From: Oguzhan Ergin Date: Mon, 17 Aug 2015 15:34:22 +0300 Subject: [PATCH 120/794] Added fs-ext definitions --- fs-ext/fs-ext.d.ts | 102 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 fs-ext/fs-ext.d.ts diff --git a/fs-ext/fs-ext.d.ts b/fs-ext/fs-ext.d.ts new file mode 100644 index 000000000..00f63c5a0 --- /dev/null +++ b/fs-ext/fs-ext.d.ts @@ -0,0 +1,102 @@ +// Type definitions for fs-ext +// Project: https://github.com/baudehlo/node-fs-ext +// Definitions by: Oguzhan Ergin +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "fs-ext" { + export * from "fs"; + + /** + * Asynchronous flock(2). No arguments other than a possible error are passed to the callback. + * @param fd File Descriptor + * @param flags Flags can be 'sh', 'ex', 'shnb', 'exnb', 'un' and correspond to the various LOCK_SH, LOCK_EX, LOCK_SH|LOCK_NB, etc. + **/ + export function flock(fd: number, flags: string, callback: (err: Error) => void): void; + + /** + * Synchronous flock(2). Throws an exception on error. + * @param fd File Descriptor + * @param flags Flags can be 'sh', 'ex', 'shnb', 'exnb', 'un' and correspond to the various LOCK_SH, LOCK_EX, LOCK_SH|LOCK_NB, etc. + **/ + export function flockSync(fd: number, flags: string):void; + + /** + * Asynchronous fcntl(2). + * @param fd File Descriptor + * @param cmd The supported commands are: 'getfd' ( F_GETFD ) , 'setfd' ( F_SETFD ) + * Requiring this module adds FD_CLOEXEC to the constants module, for use with F_SETFD. + * @param arg arg + **/ + export function fcntl(fd: number, cmd: string, arg: number, callback: (err: Error, result: number) => void):void; + + /** + * Asynchronous fcntl(2). + * @param fd File Descriptor + * @param cmd The supported commands are: 'getfd' ( F_GETFD ) , 'setfd' ( F_SETFD ) + * Requiring this module adds FD_CLOEXEC to the constants module, for use with F_SETFD. + **/ + export function fcntl(fd: number, cmd: string, callback: (err: Error, result: number) => void):void; + + /** + * Synchronous fcntl(2). Throws an exception on error. + * @param fd File Descriptor + * @param cmd The supported commands are: 'getfd' ( F_GETFD ) , 'setfd' ( F_SETFD ) + * Requiring this module adds FD_CLOEXEC to the constants module, for use with F_SETFD. + * @param arg arg + * @return Returns flags + **/ + export function fcntlSync(fd: number, cmd: string, arg?: number): number; + + /** + * Asynchronous lseek(2). + * @param fd File Descriptor + * @param offset Offset + * @param whence + * Whence can be 0 (SEEK_SET) to set the new position in bytes to offset, 1 (SEEK_CUR) to set the new + * position to the current position plus offset bytes (can be negative), or 2 (SEEK_END) to set to the end + * of the file plus offset bytes (usually negative or zero to seek to the end of the file). + **/ + export function seek(fd: number, offset: number, whence: number, callback: (err: Error, currFilePos: number) => void): void; + + /** + * Synchronous lseek(2). Throws an exception on error. Returns current file position. + * @param fd File Descriptor + * @param offset Offset + * @param whence + * Whence can be 0 (SEEK_SET) to set the new position in bytes to offset, 1 (SEEK_CUR) to set the new + * position to the current position plus offset bytes (can be negative), or 2 (SEEK_END) to set to the end + * of the file plus offset bytes (usually negative or zero to seek to the end of the file). + * @returns Returns current file position. + **/ + export function seekSync(fd: number, offset: number, whence: number): number; + + /** + * Asynchronous utime(2). + * @param path File path + * @param atime + * Arguments atime and mtime are in seconds as for the system call.Note that the number value of Date() is in milliseconds, + * so to use the 'now' value with fs.utime() you would have to divide by 1000 first, e.g. Date.now()/1000 + * Just like for utime(2), the absence of the atime and mtime means 'now'. + * @param mtime + * Arguments atime and mtime are in seconds as for the system call.Note that the number value of Date() is in milliseconds, + * so to use the 'now' value with fs.utime() you would have to divide by 1000 first, e.g. Date.now()/1000 + * Just like for utime(2), the absence of the atime and mtime means 'now'. + **/ + export function utime(path: string, atime: number, mtime: number, callback: (err: Error) => void):void; + + /** + * Synchronous version of utime(). Throws an exception on error. + * @param path File path + * @param atime + * Arguments atime and mtime are in seconds as for the system call.Note that the number value of Date() is in milliseconds, + * so to use the 'now' value with fs.utime() you would have to divide by 1000 first, e.g. Date.now()/1000 + * Just like for utime(2), the absence of the atime and mtime means 'now'. + * @param mtime + * Arguments atime and mtime are in seconds as for the system call.Note that the number value of Date() is in milliseconds, + * so to use the 'now' value with fs.utime() you would have to divide by 1000 first, e.g. Date.now()/1000 + * Just like for utime(2), the absence of the atime and mtime means 'now'. + **/ + export function utimeSync(path: string, atime: number, mtime: number):void; +} From 20305aba6d1c61007cb1d3073fece0a818b99cf0 Mon Sep 17 00:00:00 2001 From: zenorbi Date: Mon, 17 Aug 2015 17:04:24 +0200 Subject: [PATCH 121/794] Added definition for node-apn --- apn/apn-test.ts | 146 +++++++++++++++++++ apn/apn.d.ts | 364 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 510 insertions(+) create mode 100644 apn/apn-test.ts create mode 100644 apn/apn.d.ts diff --git a/apn/apn-test.ts b/apn/apn-test.ts new file mode 100644 index 000000000..a9e2c21a7 --- /dev/null +++ b/apn/apn-test.ts @@ -0,0 +1,146 @@ +/// +import apn = require("apn"); + +//Hand made TypeScript tests +//========================== + +//Create with a hex string +var device1 = new apn.Device("ca11ab1e"); +//Create with a Buffer +var device2 = new apn.Device(new Buffer("ca55e77e")); + +//Create the notification +var notification = new apn.Notification(); +notification.alert = { + title: "The Title", + body: "This is the body", +}; +notification.badge = 5; +//Fluid api +notification.setAlertTitle("The Title") + .setAlertText("This is the body") + .setLaunchImage("LaunchImage"); + +//Establish the connection +var connection = new apn.Connection({ + cert: "path/to/cert.pem", + key: "path/to/cert.pem" +}); +//Testing some specialized event listeners +connection.on("error", (error) => { + console.log("push error", error.name, error.message); +}); +connection.on("transmissionError", (errorCode, notification, device) => { + console.log("push failed", errorCode, "notification", notification.alert, "device id: ", device.toString()); +}); + +//Send it using hex string +connection.pushNotification(notification, "ba5eba11"); +//Send it using Buffer +connection.pushNotification(notification, new Buffer("5ca1ab1e")); +//Send it using Device +connection.pushNotification(notification, device1); + +//Connecting to feedback service +var feedbackService = new apn.Feedback({ + cert: "path/to/cert.pem", + key: "path/to/cert.pem", + interval: 0 +}); +feedbackService.on("error", (error:Error) => { + console.log("push feedback error", error.name, error.message); +}); +function processFeedbackData(device:Buffer, time:number) { +} +feedbackService.on("feedback", (feedbackData) => { + feedbackData.forEach((data) => { + processFeedbackData(data.device, data.time); + }) +}); +feedbackService.start(); + + +//Original examples from apn package +//================================== + +//sending-to-multiple-devices.js +//------------------------------ + +var tokens = ["", ""]; + +if(tokens[0] === "") { + console.log("Please set token to a valid device token for the push notification service"); + process.exit(); +} + +// Create a connection to the service using mostly default parameters. + +var service = new apn.connection({ production: false }); + +service.on("connected", function() { + console.log("Connected"); +}); + +service.on("transmitted", function(notification, device) { + console.log("Notification transmitted to:" + device.token.toString("hex")); +}); + +service.on("transmissionError", function(errCode, notification, device) { + console.error("Notification caused error: " + errCode + " for device ", device, notification); + if (errCode === 8) { + console.log("A error code of 8 indicates that the device token is invalid. This could be for a number of reasons - are you using the correct environment? i.e. Production vs. Sandbox"); + } +}); + +service.on("timeout", function () { + console.log("Connection Timeout"); +}); + +service.on("disconnected", function() { + console.log("Disconnected from APNS"); +}); + +service.on("socketError", console.error); + + +// If you plan on sending identical paylods to many devices you can do something like this. +function pushNotificationToMany() { + console.log("Sending the same notification each of the devices with one call to pushNotification."); + var note = new apn.notification(); + note.setAlertText("Hello, from node-apn!"); + note.badge = 1; + + service.pushNotification(note, tokens); +} + +pushNotificationToMany(); + + +// If you have a list of devices for which you want to send a customised notification you can create one and send it to and individual device. +function pushSomeNotifications() { + console.log("Sending a tailored notification to %d devices", tokens.length); + tokens.forEach(function(token, i) { + var note = new apn.notification(); + note.setAlertText("Hello, from node-apn! You are number: " + i); + note.badge = i; + + service.pushNotification(note, token); + }); +} + +pushSomeNotifications(); + +//feedback.js +//----------- + +function handleFeedback(feedbackData:apn.FeedbackData[]) { + feedbackData.forEach(function(feedbackItem) { + console.log("Device: " + feedbackItem.device.toString("hex") + " has been unreachable, since: " + feedbackItem.time); + }); +} + +// Setup a connection to the feedback service using a custom interval (10 seconds) +var feedback = new apn.feedback({ production: false, interval: 10 }); + +feedback.on("feedback", handleFeedback); +feedback.on("feedbackError", console.error); diff --git a/apn/apn.d.ts b/apn/apn.d.ts new file mode 100644 index 000000000..ed38086ef --- /dev/null +++ b/apn/apn.d.ts @@ -0,0 +1,364 @@ +// Type definitions for node-apn +// Project: https://github.com/argon/node-apn +// Definitions by: Zenorbi +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +declare module "apn" { + import events = require("events"); + import net = require("net"); + export interface ConnectionOptions { + /** + * The filename of the connection certificate to load from disk, or a Buffer/String containing the certificate data. (Defaults to: `cert.pem`) + */ + cert?:string|Buffer; + /** + * The filename of the connection key to load from disk, or a Buffer/String containing the key data. (Defaults to: `key.pem`) + */ + key?:string|Buffer; + /** + * An array of trusted certificates. Each element should contain either a filename to load, or a Buffer/String (in PEM format) to be used directly. If this is omitted several well known "root" CAs will be used. - You may need to use this as some environments don't include the CA used by Apple (entrust_2048). + */ + ca?:(string|Buffer)[]; + /** + * File path for private key, certificate and CA certs in PFX or PKCS12 format, or a Buffer containing the PFX data. If supplied will always be used instead of certificate and key above. + */ + pfx?:string|Buffer; + /** + * The passphrase for the connection key, if required + */ + passphrase?:string; + /** + * Specifies which environment to connect to: Production (if true) or Sandbox - The hostname will be set automatically. (Defaults to NODE_ENV == "production", i.e. false unless the NODE_ENV environment variable is set accordingly) + */ + production?:boolean; + /** + * Enable when you are using a VoIP certificate to enable paylods up to 4096 bytes. + */ + voip?:boolean; + /** + * Gateway port (Defaults to: `2195`) + */ + port?:number; + /** + * Reject Unauthorized property to be passed through to tls.connect() (Defaults to `true`) + */ + rejectUnauthorized?:boolean; + /** + * Number of notifications to cache for error purposes (See "Handling Errors" below, (Defaults to: `1000`) + */ + cacheLength?:number; + /** + * Whether the cache should grow in response to messages being lost after errors. (Will still emit a 'cacheTooSmall' event) (Defaults to: `true`) + */ + autoAdjustCache?:boolean; + /** + * The maximum number of connections to create for sending messages. (Defaults to: `1`) + */ + maxConnections?:number; + /** + * The duration of time the module should wait, in milliseconds, when trying to establish a connection to Apple before failing. 0 = Disabled. {Defaults to: `10000`} + */ + connectTimeout?:number; + /** + * The duration the socket should stay alive with no activity in milliseconds. 0 = Disabled. (Defaults to: `3600000` - 1h) + */ + connectionTimeout?:number; + /** + * The maximum number of connection failures that will be tolerated before `apn` will "terminate". (Defaults to: 10) + */ + connectionRetryLimit?:number; + /** + * Whether to buffer notifications and resend them after failure. (Defaults to: `true`) + */ + buffersNotifications?:number; + /** + * Whether to aggresively empty the notification buffer while connected - if set to true node-apn may enter a tight loop under heavy load while delivering notifications. (Defaults to: `false`) + */ + fastMode?:boolean; + } + export class Connection extends events.EventEmitter { + constructor(options:ConnectionOptions); + /** + * This is the business end of the module. Create a `Notification` object and pass it in, along with a single recipient or an array of them and node-apn will take care of the rest, delivering the notification to each recipient. + * + * A "recipient" is either a `Device` object, a `String`, or a `Buffer` containing the device token. `Device` objects are used internally and will be created if necessary. Where applicable, all events will return a `Device` regardless of the type passed to this method. + */ + pushNotification(notification:Notification, recipient:Device|string|Buffer|(Device|string|Buffer)[]):void; + /** + * Used to manually adjust the "cacheLength" property in the options. This is ideal if you choose to use the `cacheTooSmall` event to tweak your environment. It is safe for increasing and reducing cache size. + */ + setCacheLength(newLength:number):void; + /** + * Indicate to node-apn that when the queue of pending notifications is fully drained that it should close all open connections. This will mean that if there are no other pending resources (open sockets, running timers, etc.) the application will terminate. If notifications are pushed after the connection has completely shutdown a new connection will be established and, if applicable, `shutdown` will need to be called again. + */ + shutdown():void; + /** + * Emitted when an error occurs during initialisation of the module, usually due to a problem with the keys and certificates. + */ + on(event: "error", listener: (error:Error) => void):Connection; + /** + * Emitted when the connection socket experiences an error. This may be useful for debugging but no action should be necessary. + */ + on(event: "socketError", listener: (error:Error) => void):Connection; + /** + * Emitted when a notification has been sent to Apple - not a guarantee that it has been accepted by Apple, an error relating to it may occur later on. A notification may also be "transmitted" several times if a preceding notification caused an error requiring retransmission. + */ + on(event: "transmitted", listener: (notification:Notification, decive:Device) => void):Connection; + /** + * Emitted when all pending notifications have been transmitted to Apple and the pending queue is empty. This may be called more than once if a notification error occurs and notifications must be re-sent. + */ + on(event: "completed", listener: () => void):Connection; + /** + * Emitted when Apple returns a notification as invalid but the notification has already been expunged from the cache - usually due to high throughput and indicates that notifications will be getting lost. The parameter is an estimate of how many notifications have been lost. You should experiment with increasing the cache size or enabling ```autoAdjustCache``` if you see this frequently. + * + * **Note**: With ```autoAdjustCache``` enabled this event will still be emitted when an adjustment is triggered. + */ + on(event: "cacheTooSmall", listener: (sizeDifference:number) => void):Connection; + /** + * Emitted when a connection to Apple is successfully established. The parameter indicates the number of open connections. No action is required as the connection is managed internally. + */ + on(event: "connected", listener: (openSockets:net.Socket[]) => void):Connection; + /** + * Emitted when the connection to Apple has been closed, this could be for numerous reasons, for example an error has occurred or the connection has timed out. The parameter is the same as for `connected` and again, no action is required. + */ + on(event: "disconnected", listener: (openSockets:net.Socket[]) => void):Connection; + /** + * Emitted when the connectionTimeout option has been specified and no activity has occurred on a socket for a specified duration. The socket will be closed immediately after this event and a `disconnected` event will also be emitted. + */ + on(event: "timeout", listener: () => void):Connection; + /** + * Emitted when a message has been received from Apple stating that a notification was invalid or if an internal error occurred before that notification could be pushed to Apple. If the notification is still in the cache it will be passed as the second argument, otherwise null. Where possible the associated `Device` object will be passed as a third parameter, however in cases where the token supplied to the module cannot be parsed into a `Buffer` the supplied value will be returned. + + * Error codes smaller than 512 correspond to those returned by Apple as per their [docs][errors]. Other errors are applicable to `node-apn` itself. Definitions can be found in `lib/errors.js`. + */ + on(event: "transmissionError", listener: (errorCode:number, notification:Notification, device:Device|Buffer) => void):Connection; + on(event: string, listener: Function):Connection; + } + export interface NotificationAlertOptions { + title?:string; + body:string; + "title-loc-key"?:string; + "title-loc-args"?:string[]; + "action-loc-key"?:string; + "loc-key"?:string; + "loc-args"?:string[]; + "launch-image"?:string; + } + export class Notification { + /** + * The maximum number of retries which should be performed when sending a notification if an error occurs. A value of 0 will only allow one attempt at sending (0 retries). Set to -1 to disable (default). + */ + public retryLimit:number; + /** + * The UNIX timestamp representing when the notification should expire. This does not contribute to the 2048 byte payload size limit. An expiry of 0 indicates that the notification expires immediately. + */ + public expiry:number; + /** + * From Apple's Documentation, Provide one of the following values: + * + * - 10 - The push message is sent immediately. (Default) + * > The push notification must trigger an alert, sound, or badge on the device. It is an error use this priority for a push that contains only the content-available key. + * - 5 - The push message is sent at a time that conserves power on the device receiving it. + */ + public priority:number; + /** + * The encoding to use when transmitting the notification to APNS, defaults to `utf8`. `utf16le` is also possible but as each character is represented by a minimum of 2 bytes, will at least halve the possible payload size. If in doubt leave as default. + */ + public encoding:string; + /** + * This object represents the root JSON object that you can add custom information for your application to. The properties below will only be added to the payload (under `aps`) when the notification is prepared for sending. + */ + public payload:any; + /** + * The value to specify for `payload.aps.badge` + */ + public badge:number; + /** + * The value to specify for `payload.aps.sound` + */ + public sound:string; + /** + * The value to specify for `payload.aps.alert` can be either a `String` or an `Object` as outlined by the payload documentation. + */ + public alert:string|NotificationAlertOptions; + /** + * Setting this to true will specify "content-available" in the payload when it is compiled. + */ + public newsstandAvailable:boolean; + /** + * Setting this to true will specify "content-available" in the payload when it is compiled. + */ + public contentAvailable:boolean; + /** + * The value to specify for the `mdm` field where applicable. + */ + public mdm:string|Object; + /** + * The value to specify for `payload.aps['url-args']`. This used for Safari Push NOtifications and should be an array of values in accordance with the Web Payload Documentation. + */ + public urlArgs:string[]; + /** + * When this parameter is set and `notification#trim()` is called it will attempt to truncate the string at the nearest space. + */ + public truncateAtWordEnd:boolean; + /** + * You can optionally pass in an object representing the payload, or configure properties on the returned object. + */ + constructor(payload?:any); + /** + * Set the `aps.alert` text body. This will use the most space-efficient means. + */ + setAlertText(alertText:string):Notification; + /** + * Set the `title` property of the `aps.alert` object - used with Safari Push Notifications + */ + setAlertTitle(alertTitle:string):Notification; + /** + * Set the `action` property of the `aps.alert` object - used with Safari Push Notifications + */ + setAlertAction(alertAction:string):Notification; + /** + * Set the `action-loc-key` property of the `aps.alert` object. + */ + setActionLocKey(key:string):Notification; + /** + * Set the `loc-key` property of the `aps.alert` object. + */ + setLocKey(key:string):Notification; + /** + * Set the `loc-args` property of the `aps.alert` object. + */ + setLocArgs(args:string[]):Notification; + /** + * Set the `launch-image` property of the `aps.alert` object. + */ + setLaunchImage(image:string):Notification; + /** + * Set the `mdm` property on the payload. + */ + setMDM(mdm:string|Object):Notification; + /** + * Set the `content-available` property of the `aps` object. + */ + setNewsstandAvailable(available:boolean):Notification; + /** + * Set the `content-available` property of the `aps` object. + */ + setContentAvailable(available:boolean):Notification; + /** + * Set the `url-args` property of the `aps` object. + */ + setUrlArgs(urlArgs:string[]):Notification; + /** + * Attempt to automatically trim the notification alert text body to meet the payload size limit of 2048 bytes. + */ + trim():number; + } + export class Device { + public token:Buffer; + /** + * `deviceToken` can be a `Buffer` or a `String` containing a "hex" representation of the token. Throws an error if the deviceToken supplied is invalid. + */ + constructor(deviceToken:string|Buffer); + } + + export interface FeedbackOptions { + /** + * The filename of the connection certificate to load from disk, or a Buffer/String containing the certificate data. (Defaults to: `cert.pem`) + */ + cert?:string|Buffer; + /** + * The filename of the connection key to load from disk, or a Buffer/String containing the key data. (Defaults to: `key.pem`) + */ + key?:string|Buffer; + /** + * An array of trusted certificates. Each element should contain either a filename to load, or a Buffer/String (in PEM format) to be used directly. If this is omitted several well known "root" CAs will be used. - You may need to use this as some environments don't include the CA used by Apple (entrust_2048). + */ + ca?:(string|Buffer)[]; + /** + * File path for private key, certificate and CA certs in PFX or PKCS12 format, or a Buffer containing the PFX data. If supplied will be used instead of certificate and key above. + */ + pfx?:string|Buffer; + /** + * The passphrase for the connection key, if required + */ + passphrase?:string; + /** + * Specifies which environment to connect to: Production (if true) or Sandbox - The hostname will be set automatically. (Defaults to NODE_ENV == "production", i.e. false unless the NODE_ENV environment variable is set accordingly) + */ + production?:boolean; + /** + * Feedback server port (Defaults to: `2196`) + */ + port?:number; + /** + * Sets the behaviour for triggering the `feedback` event. When `true` the event will be triggered once per connection with an array of timestamp and device token tuples. Otherwise a `feedback` event will be emitted once per token received. (Defaults to: true) + */ + batchFeedback?:boolean; + /** + * The maximum number of tokens to pass when emitting the event - a value of 0 will cause all tokens to be passed after connection is reset. After this number of tokens are received the `feedback` event will be emitted. (Only applies when `batchFeedback` is enabled) + */ + batchSize?:number; + /** + * How often to automatically poll the feedback service. Set to `0` to disable. (Defaults to: `3600`) + */ + interval?:number; + } + export interface FeedbackData { + time:number; + device:Buffer; + } + /** + * Connection to the Apple Push Notification Feedback Service and if `interval` isn't disabled automatically begins polling the service. Many of the options are the same as `apn.Connection()` + */ + export class Feedback { + constructor(options:FeedbackOptions); + /** + * Trigger a query of the feedback service. If `interval` is non-zero then this method will be called automatically. + */ + start():void; + /** + * You can cancel the interval by calling `feedback.cancel()`. If you do not wish to have the service automatically queried then set `interval` to 0 and use `feedback.start()` to manually invoke it one time. + */ + cancel():void; + /** + * Emitted when an error occurs initialising the module. Usually caused by failing to load the certificates. + */ + on(event: "error", listener: (error:Error) => void):Feedback; + /** + * Emitted when an error occurs receiving or processing the feedback and in the case of a socket error occurring. These errors are usually informational and node-apn will automatically recover. + */ + on(event: "feedbackError", listener: (error:Error) => void):Feedback; + /** + * Emitted when data has been received from the feedback service, typically once per connection. `feedbackData` is an array of objects, each containing the `time` returned by the server (epoch time) and the `device` a `Buffer` containing the device token. + */ + on(event: "feedback", listener: (feedbackData:FeedbackData[]) => void):Feedback; + on(event: string, listener: Function):Feedback; + } + + export enum Errors { + "noErrorsEncountered"= 0, + "processingError"= 1, + "missingDeviceToken"= 2, + "missingTopic"= 3, + "missingPayload"= 4, + "invalidTokenSize"= 5, + "invalidTopicSize"= 6, + "invalidPayloadSize"= 7, + "invalidToken"= 8, + "apnsShutdown"= 10, + "none"= 255, + "retryLimitExceeded"= 512, + "moduleInitialisationFailed"= 513, + "connectionRetryLimitExceeded"= 514, // When a connection is unable to be established. Usually because of a network / SSL error this will be emitted + "connectionTerminated"= 515 + } + + //Lowercase aliases + export {Connection as connection}; + export {Device as device}; + export {Errors as error}; + export {Feedback as feedback}; + export {Notification as notification}; +} From 9732f123672c2d2a6f6cda9a10c5e5c3c7c3dbab Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 17 Aug 2015 11:43:17 -0400 Subject: [PATCH 122/794] Fixing typo in ui-grid definition. "notifiyDataChange" should be "notifyDataChange" --- ui-grid/ui-grid.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ui-grid/ui-grid.d.ts b/ui-grid/ui-grid.d.ts index 981f363b2..9dbb6dac9 100644 --- a/ui-grid/ui-grid.d.ts +++ b/ui-grid/ui-grid.d.ts @@ -248,7 +248,7 @@ declare module uiGrid { clearRowInvisible(rowEntity: any): void; getVisibleRows(grid: IGridInstance): Array; handleWindowResize(): void; - notifiyDataChange(type: string): void; + notifyDataChange(type: string): void; refreshRows(): ng.IPromise; registerColumnsProcessor(processorFunction: IColumnProcessor, priority: number): void; registerRowsProcessor(rowProcessor: IRowProcessor, priority: number): void; From ad3abeb456a9b299278e91cedda4f4d5f8c4818a Mon Sep 17 00:00:00 2001 From: benishouga Date: Tue, 18 Aug 2015 01:09:15 +0900 Subject: [PATCH 123/794] Support the string for the second argument of Router.run. --- react-router/react-router-test.ts | 14 ++++++++++---- react-router/react-router.d.ts | 1 + 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/react-router/react-router-test.ts b/react-router/react-router-test.ts index 62180a258..115c8b77f 100644 --- a/react-router/react-router-test.ts +++ b/react-router/react-router-test.ts @@ -312,12 +312,18 @@ class RunTest { var v2: Router.Router = Router.run(React.createElement(Router.Route, null), Router.HistoryLocation, (Handler, state) => { React.render(React.createElement(Handler, null), document.body); }); - - // React.createFactory() version - var v3: Router.Router = Router.run(React.createFactory(Router.Route)(), (Handler) => { + var v3: Router.Router = Router.run(React.createElement(Router.Route, null), '/foo/bar', (Handler, state) => { React.render(React.createElement(Handler, null), document.body); }); - var v4: Router.Router = Router.run(React.createFactory(Router.Route)(), Router.HistoryLocation, (Handler, state) => { + + // React.createFactory() version + var v4: Router.Router = Router.run(React.createFactory(Router.Route)(), (Handler) => { + React.render(React.createElement(Handler, null), document.body); + }); + var v5: Router.Router = Router.run(React.createFactory(Router.Route)(), Router.HistoryLocation, (Handler, state) => { + React.render(React.createElement(Handler, null), document.body); + }); + var v6: Router.Router = Router.run(React.createFactory(Router.Route)(), '/foo/bar', (Handler, state) => { React.render(React.createElement(Handler, null), document.body); }); } diff --git a/react-router/react-router.d.ts b/react-router/react-router.d.ts index d8dd12c97..51664b03a 100644 --- a/react-router/react-router.d.ts +++ b/react-router/react-router.d.ts @@ -175,6 +175,7 @@ declare module ReactRouter { function create(options: RouterCreateOption): Router; function run(routes: Route, callback: RouterRunCallback): Router; function run(routes: Route, location: LocationBase, callback: RouterRunCallback): Router; + function run(routes: Route, location: string, callback: RouterRunCallback): Router; // From 232240bea530fe0ca1f427fab81d46d7b6f7eca9 Mon Sep 17 00:00:00 2001 From: Adam Babcock Date: Mon, 17 Aug 2015 11:25:39 -0500 Subject: [PATCH 124/794] Support for request-ip --- request-ip/request-ip-tests.ts | 10 ++++++++++ request-ip/request-ip.d.ts | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 request-ip/request-ip-tests.ts create mode 100644 request-ip/request-ip.d.ts diff --git a/request-ip/request-ip-tests.ts b/request-ip/request-ip-tests.ts new file mode 100644 index 000000000..8c5111e33 --- /dev/null +++ b/request-ip/request-ip-tests.ts @@ -0,0 +1,10 @@ +/// +/// + +import express = require('express'); +import requestIp = require('request-ip'); + +var ipMiddleware = function(req:express.Request, res:express.Response, next:Function) { + var clientIp = requestIp.getClientIp(req); + next(); +}; diff --git a/request-ip/request-ip.d.ts b/request-ip/request-ip.d.ts new file mode 100644 index 000000000..e71ed1a37 --- /dev/null +++ b/request-ip/request-ip.d.ts @@ -0,0 +1,32 @@ +// Type definitions for request-ip +// Project: https://github.com/pbojinov/request-ip +// Definitions by: Adam Babcock +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "request-ip" { + interface Request { + headers: { + 'x-client-ip'?: string; + 'x-forwarded-for'?: string; + 'x-real-ip'?: string; + 'x-cluster-client-ip'?: string; + 'x-forwarded'?: string; + 'forwarded-for'?: string; + 'forwarded'?: string; + }; + connection: { + remoteAddress?: string; + socket?: { + remoteAddress?: string + }; + }; + info?: { + remoteAddress?: string + }; + socket?: { + remoteAddress?: string + }; + } + + export function getClientIp(req:Request):string; +} From 14394df1810b7899ae4b7c843dfbd326e9230529 Mon Sep 17 00:00:00 2001 From: Felipe Barriga Richards Date: Mon, 17 Aug 2015 14:50:12 -0300 Subject: [PATCH 125/794] lodash: Fix _.has and _.result --- lodash/lodash-tests.ts | 6 ++++++ lodash/lodash.d.ts | 21 +++++++++++---------- 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 2cbec6853..4e741f5dc 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1571,6 +1571,10 @@ result = _(any).noop(true, 'a', 1); var object = { 'cheese': 'crumpets', + 'one': 1, + 'nested': { + 'two': 2 + }, 'stuff': function () { return 'nonsense'; } @@ -1578,6 +1582,8 @@ var object = { result = _.result(object, 'cheese'); result = _.result(object, 'stuff'); +result = _.result(object, 'one'); +result = _.result(object, ['nested', 'two'] ); var tempObject = {}; result = _.runInContext(tempObject); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index c088f5459..7fd62eb4b 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -6810,13 +6810,12 @@ declare module _ { //_.has interface LoDashStatic { /** - * Checks if the specified object property exists and is a direct property, instead of an - * inherited property. - * @param object The object to check. - * @param property The property to check for. - * @return True if key is a direct property, else false. + * Checks if path is a direct property. + * @param object The object to query. + * @param path The path to check. + * @return True if path is a direct property, else False. **/ - has(object: any, property: string): boolean; + has(object: any, path: string|string[]): boolean; } //_.invert @@ -7822,12 +7821,14 @@ declare module _ { /** * Resolves the value of property on object. If property is a function it will be invoked with * the this binding of object and its result returned, else the property value is returned. If - * object is falsey then undefined is returned. - * @param object The object to inspect. - * @param property The property to get the value of. + * object is false then undefined is returned. + * @param object The object to query. + * @param path The path of the property to resolve. + * @param defaultValue The value returned if the resolved value is undefined. * @return The resolved value. **/ - result(object: any, property: string): any; + + result(object: any, path: string|string[], defaultValue?: T): T; } //_.runInContext From 5fb2a9fe67a2b50f1c928e05351b02abcd54b098 Mon Sep 17 00:00:00 2001 From: Felipe Barriga Richards Date: Mon, 17 Aug 2015 15:21:37 -0300 Subject: [PATCH 126/794] lodash: fix pull, remove, fill, pluck --- lodash/lodash-tests.ts | 1 + lodash/lodash.d.ts | 62 +++++++++++++++++++++--------------------- 2 files changed, 32 insertions(+), 31 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 2cbec6853..34080d18d 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -639,6 +639,7 @@ result = _(stoogesAgesDict).sum('age'); result = _.pluck(stoogesAges, 'name'); result = _(stoogesAges).pluck('name').value(); +result = _.pluck(stoogesAges, ['name']); // _.partition result = _.partition('abcd', (n) => n < 'c'); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index c088f5459..97c02f4b4 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -1092,16 +1092,16 @@ declare module _ { * @param values The values to remove. * @return array. **/ - pull( - array: Array, - ...values: any[]): any[]; + pull( + array: Array, + ...values: T[]): T[]; /** * @see _.pull **/ - pull( - array: List, - ...values: any[]): any[]; + pull( + array: List, + ...values: T[]): T[]; } interface LoDashStatic { @@ -1141,50 +1141,50 @@ declare module _ { * @param thisArg The this binding of callback. * @return A new array of removed elements. **/ - remove( - array: Array, - callback?: ListIterator, - thisArg?: any): any[]; + remove( + array: Array, + callback?: ListIterator, + thisArg?: any): T[]; /** * @see _.remove **/ - remove( - array: List, - callback?: ListIterator, - thisArg?: any): any[]; + remove( + array: List, + callback?: ListIterator, + thisArg?: any): T[]; /** * @see _.remove * @param pluckValue _.pluck style callback **/ - remove( - array: Array, - pluckValue?: string): any[]; + remove( + array: Array, + pluckValue?: string): T[]; /** * @see _.remove * @param pluckValue _.pluck style callback **/ - remove( - array: List, - pluckValue?: string): any[]; + remove( + array: List, + pluckValue?: string): T[]; /** * @see _.remove * @param whereValue _.where style callback **/ - remove( - array: Array, - wherealue?: Dictionary): any[]; + remove( + array: Array, + wherealue?: Dictionary): T[]; /** * @see _.remove * @param whereValue _.where style callback **/ - remove( - array: List, - wherealue?: Dictionary): any[]; + remove( + array: List, + wherealue?: Dictionary): T[]; /** * @see _.remove @@ -2494,7 +2494,7 @@ declare module _ { * @see _.fill */ fill( - value: any, + value: TResult, start?: number, end?: number): LoDashArrayWrapper; } @@ -2504,7 +2504,7 @@ declare module _ { * @see _.fill */ fill( - value: any, + value: TResult, start?: number, end?: number): LoDashObjectWrapper>; } @@ -4069,21 +4069,21 @@ declare module _ { **/ pluck( collection: Array, - property: string): any[]; + property: string|string[]): any[]; /** * @see _.pluck **/ pluck( collection: List, - property: string): any[]; + property: string|string[]): any[]; /** * @see _.pluck **/ pluck( collection: Dictionary, - property: string): any[]; + property: string|string[]): any[]; } interface LoDashArrayWrapper { From 4410e5ba936478efb74705c4bf5de230c1f41c2d Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Mon, 17 Aug 2015 12:25:31 -0700 Subject: [PATCH 127/794] Missing comma. --- angular-ui-bootstrap/angular-ui-bootstrap-tests.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/angular-ui-bootstrap/angular-ui-bootstrap-tests.ts b/angular-ui-bootstrap/angular-ui-bootstrap-tests.ts index a5dc969ed..80d06c254 100644 --- a/angular-ui-bootstrap/angular-ui-bootstrap-tests.ts +++ b/angular-ui-bootstrap/angular-ui-bootstrap-tests.ts @@ -121,8 +121,8 @@ testApp.config(( placement: 'bottom', animation: false, popupDelay: 1000, - appendToBody: true - useContentExp: true + appendToBody: true, + useContentExp: true, }); $tooltipProvider.setTriggers({ 'customOpenTrigger': 'customCloseTrigger' From 4d0f988e3c906e7a66bbd79dc11443c533038cb5 Mon Sep 17 00:00:00 2001 From: Joe Skeen Date: Mon, 17 Aug 2015 13:27:17 -0600 Subject: [PATCH 128/794] Definitions for gulp-sort --- gulp-sort/gulp-sort-tests.ts | 49 ++++++++++++++++++++++++++++++++++++ gulp-sort/gulp-sort.d.ts | 44 ++++++++++++++++++++++++++++++++ 2 files changed, 93 insertions(+) create mode 100644 gulp-sort/gulp-sort-tests.ts create mode 100644 gulp-sort/gulp-sort.d.ts diff --git a/gulp-sort/gulp-sort-tests.ts b/gulp-sort/gulp-sort-tests.ts new file mode 100644 index 000000000..0dd260f66 --- /dev/null +++ b/gulp-sort/gulp-sort-tests.ts @@ -0,0 +1,49 @@ +/** Tests taken from https://github.com/pgilad/gulp-sort#usage */ +/// +/// +/// + +import gulp = require('gulp'); +import sort = require('gulp-sort'); + +// default sort +gulp.src('./src/js/**/*.js') + .pipe(sort()) + .pipe(gulp.dest('./build/js')); + +// pass in a custom comparator function +gulp.src('./src/js/**/*.js') + .pipe(sort(customComparator)) + .pipe(gulp.dest('./build/js')); + +// sort descending +gulp.src('./src/js/**/*.js') + .pipe(sort({ + asc: false + })) + .pipe(gulp.dest('./build/js')); + +// sort with a custom comparator +gulp.src('./src/js/**/*.js') + .pipe(sort({ + comparator: function(file1, file2) { + if (file1.path.indexOf('build') > -1) { + return 1; + } + if (file2.path.indexOf('build') > -1) { + return -1; + } + return 0; + } + })) + .pipe(gulp.dest('./build/js')); + +function customComparator(file1, file2) { + if (file1.path.indexOf('build') > -1) { + return 1; + } + if (file2.path.indexOf('build') > -1) { + return -1; + } + return 0; +} \ No newline at end of file diff --git a/gulp-sort/gulp-sort.d.ts b/gulp-sort/gulp-sort.d.ts new file mode 100644 index 000000000..7289c1f51 --- /dev/null +++ b/gulp-sort/gulp-sort.d.ts @@ -0,0 +1,44 @@ +// Type definitions for gulp-sort +// Project: https://github.com/pgilad/gulp-sort +// Definitions by: Joe Skeen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +/** Sort files in stream by path or any custom sort comparator */ +declare module 'gulp-sort' { + + import gulpUtil = require('gulp-util'); + + interface IOptions { + /** + * A function to compare two files. + * Returns: + * -1 if file1 should be before file2, + * 0 if file1 is equivalent to file2, and + * 1 if file1 should be after file2 + */ + comparator?: IComparatorFunction; + /** Whether to sort in ascending order, default is true */ + asc?; + } + + interface IComparatorFunction { + /** + * A function to compare two files. + * Returns: + * -1 if file1 should be before file2, + * 0 if file1 is equivalent to file2, and + * 1 if file1 should be after file2 + */ + (file1: gulpUtil.File, file2: gulpUtil.File): number; + } + + /** Sort files in stream by path or any custom sort comparator */ + function gulpSort(): NodeJS.ReadWriteStream; + function gulpSort(comparator: IComparatorFunction): NodeJS.ReadWriteStream; + function gulpSort(options: IOptions): NodeJS.ReadWriteStream; + + export = gulpSort; +} From 64cfad5c09adff9a47d004d7b9c7aad23be86c83 Mon Sep 17 00:00:00 2001 From: Joe Skeen Date: Mon, 17 Aug 2015 13:31:19 -0600 Subject: [PATCH 129/794] Fix implicit any issues --- gulp-sort/gulp-sort-tests.ts | 3 ++- gulp-sort/gulp-sort.d.ts | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/gulp-sort/gulp-sort-tests.ts b/gulp-sort/gulp-sort-tests.ts index 0dd260f66..12685c085 100644 --- a/gulp-sort/gulp-sort-tests.ts +++ b/gulp-sort/gulp-sort-tests.ts @@ -5,6 +5,7 @@ import gulp = require('gulp'); import sort = require('gulp-sort'); +import gulpUtil = require('gulp-util'); // default sort gulp.src('./src/js/**/*.js') @@ -38,7 +39,7 @@ gulp.src('./src/js/**/*.js') })) .pipe(gulp.dest('./build/js')); -function customComparator(file1, file2) { +function customComparator(file1: gulpUtil.File, file2: gulpUtil.File) { if (file1.path.indexOf('build') > -1) { return 1; } diff --git a/gulp-sort/gulp-sort.d.ts b/gulp-sort/gulp-sort.d.ts index 7289c1f51..c06b9c3e0 100644 --- a/gulp-sort/gulp-sort.d.ts +++ b/gulp-sort/gulp-sort.d.ts @@ -21,7 +21,7 @@ declare module 'gulp-sort' { */ comparator?: IComparatorFunction; /** Whether to sort in ascending order, default is true */ - asc?; + asc?: boolean; } interface IComparatorFunction { From b8d40ffd99a3c4acc584c88ee51c3f5656d921ec Mon Sep 17 00:00:00 2001 From: psnider Date: Mon, 17 Aug 2015 20:27:44 +0000 Subject: [PATCH 130/794] add decls for mailparser --- mailparser/mailparser-tests.ts | 69 +++++++++++++++++++++++++++ mailparser/mailparser.d.ts | 86 ++++++++++++++++++++++++++++++++++ 2 files changed, 155 insertions(+) create mode 100644 mailparser/mailparser-tests.ts create mode 100644 mailparser/mailparser.d.ts diff --git a/mailparser/mailparser-tests.ts b/mailparser/mailparser-tests.ts new file mode 100644 index 000000000..51d562788 --- /dev/null +++ b/mailparser/mailparser-tests.ts @@ -0,0 +1,69 @@ +import mailparser_mod = require("mailparser"); +import MailParser = mailparser_mod.MailParser; +import ParsedMail = mailparser_mod.ParsedMail; + + + +var mailparser = new MailParser(); + + +mailparser.on("headers", function(headers){ + console.log(headers.received); +}); + +mailparser.on("end", function(mail){ + mail; // object structure for parsed e-mail +}); + + +// Decode a simple e-mail +// This example decodes an e-mail from a string + +var email = "From: 'Sender Name' \r\n"+ + "To: 'Receiver Name' \r\n"+ + "Subject: Hello world!\r\n"+ + "\r\n"+ + "How are you today?"; + // setup an event listener when the parsing finishes +mailparser.on("end", function(mail_object){ + console.log("From:", mail_object.from); //[{address:'sender@example.com',name:'Sender Name'}] + console.log("Subject:", mail_object.subject); // Hello world! + console.log("Text body:", mail_object.text); // How are you today? +}); + // send the email source to the parser +mailparser.write(email); +mailparser.end(); + + +// Pipe file to MailParser +// This example pipes a readableStream file to MailParser +mailparser = new MailParser(); +import fs = require("fs"); +mailparser.on("end", function(mail_object){ + console.log("Subject:", mail_object.subject); +}); + +fs.createReadStream("email.eml").pipe(mailparser); + + +// Attachments +mailparser.on("end", function(mail_object : ParsedMail){ + mail_object.attachments.forEach(function(attachment){ + console.log(attachment.fileName); + }); +}); + + +// Attachment streaming +var mp = new MailParser({ + streamAttachments: true +}) + +mp.on("attachment", function(attachment, mail){ + var output = fs.createWriteStream(attachment.generatedFileName); + attachment.stream.pipe(output); +}); + + + + diff --git a/mailparser/mailparser.d.ts b/mailparser/mailparser.d.ts new file mode 100644 index 000000000..9e67cc78a --- /dev/null +++ b/mailparser/mailparser.d.ts @@ -0,0 +1,86 @@ +// Type definitions for mailparser v0.5.2 +// Project: https://www.npmjs.com/package/mailparser +// Definitions by: Peter Snider +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +/// + + +declare module 'mailparser' { + import WritableStream = NodeJS.WritableStream; + import EventEmitter = NodeJS.EventEmitter; + + interface Options { + debug?: boolean; // if set to true print all incoming lines to console + streamAttachments?: boolean; // if set to true, stream attachments instead of including them + unescapeSMTP?: boolean; // if set to true replace double dots in the beginning of the file + defaultCharset?: string; // the default charset for text/plain and text/html content, if not set reverts to Latin-1 + showAttachmentLinks?: boolean; // if set to true, show inlined attachment links filename + } + + + interface EmailAddress { + address: string; + name: string; + } + + + interface Attachment { + contentType: string; + fileName: string; + contentDisposition: string; // e.g. 'attachment' + contentId: string; // e.g. '5.1321281380971@localhost' + transferEncoding: string; // e.g. 'base64' + length: number; // length of the attachment in bytes + generatedFileName: string; // e.g. 'image.png' + checksum: string; // the md5 hash of the file, e.g. 'e4cef4c6e26037bcf8166905207ea09b' + content: Buffer; // possibly a SlowBuffer + } + + // emitted with the 'end' event + interface ParsedMail { + headers: any; // unprocessed headers in the form of - {key: value} - if there were multiple fields with the same key then the value is an array + from: EmailAddress[]; // should be only one though) + to: EmailAddress[]; + cc?: EmailAddress[]; + bcc?: EmailAddress[]; + subject: string; // the subject line + references?: string[]; // an array of reference message id values (not set if no reference values present) + inReplyTo?: string[]; // an array of In-Reply-To message id values (not set if no in-reply-to values present) + priority?: string; // priority of the e-mail, always one of the following: normal (default), high, low + text: string; // text body + html: string; // html body + date?: Date; // If date could not be resolved or is not found this field is not set. Check the original date string from headers.date + attachments?: Attachment[]; + } + + + + class MailParser implements WritableStream { + constructor(options? : Options); + on(event : string, callback : (any : any) => void) : void; + + // from WritableStream + writable: boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + + // from EventEmitter + static listenerCount(emitter: EventEmitter, event: string): number; + addListener(event: string, listener: Function): EventEmitter; + on(event: string, listener: Function): EventEmitter; + once(event: string, listener: Function): EventEmitter; + removeListener(event: string, listener: Function): EventEmitter; + removeAllListeners(event?: string): EventEmitter; + setMaxListeners(n: number): void; + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + } +} + From ceb059b2abcef0ea59486185f4cee366df07aaf8 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Mon, 17 Aug 2015 14:06:50 -0700 Subject: [PATCH 131/794] Removed union types from definition files. --- jquery.uniform/jquery.uniform.d.ts | 11 ++++++++--- jqueryui/jqueryui.d.ts | 2 +- log4js/log4js.d.ts | 6 +++++- 3 files changed, 14 insertions(+), 5 deletions(-) diff --git a/jquery.uniform/jquery.uniform.d.ts b/jquery.uniform/jquery.uniform.d.ts index e91a41c93..d5eee3e47 100644 --- a/jquery.uniform/jquery.uniform.d.ts +++ b/jquery.uniform/jquery.uniform.d.ts @@ -5,7 +5,7 @@ /// -interface UniformOptions { +interface UniformCoreOptions { activeClass?: string; autoHide?: boolean; buttonClass?: string; @@ -34,12 +34,17 @@ interface UniformOptions { useID?: boolean; wrapperClass?: string; } + +interface UniformOptions extends UniformCoreOptions { + [option: string]: any; +} + interface Uniform { - (options?: UniformOptions & {[option: string]: any;}): JQuery; + (options?: UniformOptions): JQuery; update(elemOrSelector?: any): void; restore(elemOrSelector?: any): void; elements: JQuery[]; - defaults: UniformOptions; + defaults: UniformOptions; } interface JQueryStatic { uniform: Uniform; diff --git a/jqueryui/jqueryui.d.ts b/jqueryui/jqueryui.d.ts index 80cda8976..e658d0d10 100644 --- a/jqueryui/jqueryui.d.ts +++ b/jqueryui/jqueryui.d.ts @@ -1670,7 +1670,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(methodName: 'serialize', options: { key?: string; attribute?: string; expression?: RegExp }): string; sortable(optionLiteral: string, options: JQueryUI.SortableOptions): any; sortable(optionLiteral: string, optionName: string, optionValue: any): JQuery; diff --git a/log4js/log4js.d.ts b/log4js/log4js.d.ts index 70059142c..5ecec0db1 100644 --- a/log4js/log4js.d.ts +++ b/log4js/log4js.d.ts @@ -232,6 +232,10 @@ declare module "log4js" { | GelfAppenderConfig | MultiprocessAppenderConfig - type AppenderConfig = CoreAppenderConfig | (AppenderConfigBase & { [prop: string]: any; }); + interface CustomAppenderConfig extends AppenderConfigBase { + [prop: string]: any; + } + + type AppenderConfig = CoreAppenderConfig | CustomAppenderConfig; } From a3f73092d3cb3062544526201577aef1104ae1bb Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Mon, 17 Aug 2015 14:43:51 -0700 Subject: [PATCH 132/794] fixed errors in tests. --- jqueryui/jqueryui.d.ts | 5 ++++- vinyl/vinyl-tests.ts | 34 ++++++++++++++++++++++++++-------- 2 files changed, 30 insertions(+), 9 deletions(-) diff --git a/jqueryui/jqueryui.d.ts b/jqueryui/jqueryui.d.ts index e658d0d10..a58a60c11 100644 --- a/jqueryui/jqueryui.d.ts +++ b/jqueryui/jqueryui.d.ts @@ -54,7 +54,10 @@ declare module JQueryUI { } interface AutocompleteUIParams { - + /** + * The item selected from the menu, if any. Otherwise the property is null + */ + item?: any; } interface AutocompleteEvent { diff --git a/vinyl/vinyl-tests.ts b/vinyl/vinyl-tests.ts index eb203bdae..cb1ceaea6 100644 --- a/vinyl/vinyl-tests.ts +++ b/vinyl/vinyl-tests.ts @@ -73,7 +73,7 @@ describe('File', () => { it('should set stat to given value', done => { var val = {}; - var file = new File({stat: val}); + var file = new File({stat: val}); file.stat.should.equal(val); done(); }); @@ -150,8 +150,8 @@ describe('File', () => { }); describe('isDirectory()', () => { - var fakeStat = { - isDirectory: () => { + var fakeStat = { + isDirectory() { return true; } }; @@ -191,8 +191,20 @@ describe('File', () => { file2.cwd.should.equal(file.cwd); file2.base.should.equal(file.base); file2.path.should.equal(file.path); - file2.contents.should.not.equal(file.contents, 'buffer ref should be different'); - file2.contents.toString('utf8').should.equal(file.contents.toString('utf8')); + + let fileContents = file.contents; + let file2Contents = file2.contents; + + file2Contents.should.not.equal(fileContents, 'buffer ref should be different'); + + let fileUtf8Contents = fileContents instanceof Buffer ? + fileContents.toString('utf8') : + (fileContents).toString(); + let file2Utf8Contents = file2Contents instanceof Buffer ? + file2Contents.toString('utf8') : + (file2Contents).toString(); + + file2Utf8Contents.should.equal(fileUtf8Contents); done(); }); @@ -294,7 +306,10 @@ describe('File', () => { var ret = file.pipe(stream); ret.should.equal(stream, 'should return the stream'); - file.contents.write(testChunk); + let fileContents = file.contents; + if (fileContents instanceof Buffer) { + fileContents.write(testChunk.toString()); + } }); it('should do nothing with null', done => { @@ -360,7 +375,10 @@ describe('File', () => { var ret = file.pipe(stream, {end: false}); ret.should.equal(stream, 'should return the stream'); - file.contents.write(testChunk); + let fileContents = file.contents; + if (fileContents instanceof Buffer) { + fileContents.write(testChunk.toString()); + } }); it('should do nothing with null', done => { @@ -475,7 +493,7 @@ describe('File', () => { var val = "test"; var file = new File(); try { - file.contents = val; + file.contents = new Buffer(val); } catch (err) { should.exist(err); done(); From 379748b491fe77072cf7519ee86bd27a8993fe4b Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Mon, 17 Aug 2015 14:48:00 -0700 Subject: [PATCH 133/794] Remove test for undocumented '_renderItem' function in 'jqueryui'. --- jqueryui/jqueryui-tests.ts | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/jqueryui/jqueryui-tests.ts b/jqueryui/jqueryui-tests.ts index 98b45ca28..84d137331 100644 --- a/jqueryui/jqueryui-tests.ts +++ b/jqueryui/jqueryui-tests.ts @@ -769,13 +769,7 @@ function test_autocomplete() { $("#project-icon").attr("src", "images/" + ui.item.icon); return false; } - }) - .data("autocomplete")._renderItem = (ul, item) => { - return $("
    • ") - .data("item.autocomplete", item) - .append("" + item.label + "
      " + item.desc + "
      ") - .appendTo(ul); - }; + }); $("#developer").autocomplete({ source: (request, response) => { From b51f8765a35d5b3e2fd1029f35c8b1cdda7c305e Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Mon, 17 Aug 2015 15:04:54 -0700 Subject: [PATCH 134/794] Made tests pass for 'jqueryui'. --- jquery/jquery.d.ts | 4 ++ jqueryui/jqueryui-tests.ts | 4 +- jqueryui/jqueryui.d.ts | 90 ++++++++++++++++++++++---------------- 3 files changed, 59 insertions(+), 39 deletions(-) diff --git a/jquery/jquery.d.ts b/jquery/jquery.d.ts index dc5c4ebb6..3599c808f 100644 --- a/jquery/jquery.d.ts +++ b/jquery/jquery.d.ts @@ -185,6 +185,10 @@ interface JQueryXHR extends XMLHttpRequest, JQueryPromise { * Property containing the parsed response if the response Content-Type is json */ responseJSON?: any; + /** + * A function to be called if the request fails. + */ + error(xhr: JQueryXHR, textStatus: string, errorThrown: string): void; } /** diff --git a/jqueryui/jqueryui-tests.ts b/jqueryui/jqueryui-tests.ts index 84d137331..34f1f4b7e 100644 --- a/jqueryui/jqueryui-tests.ts +++ b/jqueryui/jqueryui-tests.ts @@ -1642,11 +1642,11 @@ function test_tabs() { }); $("#tabs").tabs({ beforeLoad: function (event, ui) { - ui.jqXHR.error(function () { + ui.jqXHR.error = function () { ui.panel.html( "Couldn't load this tab. We'll try to fix this as soon as possible. " + "If this wouldn't be a demo."); - }); + }; } }); $("#tabs").tabs({ diff --git a/jqueryui/jqueryui.d.ts b/jqueryui/jqueryui.d.ts index a58a60c11..63ea4f444 100644 --- a/jqueryui/jqueryui.d.ts +++ b/jqueryui/jqueryui.d.ts @@ -723,19 +723,20 @@ declare module JQueryUI { step?: any; // number or string } - interface SpinnerUIParams { + interface SpinnerUIParam { + value: number; } - interface SpinnerEvent { - (event: Event, ui: SpinnerUIParams): void; + interface SpinnerEvent { + (event: Event, ui: T): void; } interface SpinnerEvents { - change?: SpinnerEvent; - create?: SpinnerEvent; - spin?: SpinnerEvent; - start?: SpinnerEvent; - stop?: SpinnerEvent; + change?: SpinnerEvent<{}>; + create?: SpinnerEvent<{}>; + spin?: SpinnerEvent; + start?: SpinnerEvent<{}>; + stop?: SpinnerEvent<{}>; } interface Spinner extends Widget, SpinnerOptions { @@ -756,21 +757,33 @@ declare module JQueryUI { activate?: TabsEvent; } - interface TabsUIParams { + interface TabsActivationUIParams { newTab: JQuery; oldTab: JQuery; newPanel: JQuery; oldPanel: JQuery; } - interface TabsEvent { - (event: Event, ui: TabsUIParams): void; + interface TabsBeforeLoadUIParams { + tab: JQuery; + panel: JQuery; + jqXHR: JQueryXHR; + ajaxSettings: any; + } + + interface TabsCreateOrLoadUIParams { + tab: JQuery; + panel: JQuery; + } + + interface TabsEvent { + (event: Event, ui: UI): void; } interface TabsEvents { - activate?: TabsEvent; - beforeActivate?: TabsEvent; - beforeLoad?: TabsEvent; + activate?: TabsEvent; + beforeActivate?: TabsEvent; + beforeLoad?: TabsEvent; load?: TabsEvent; } @@ -1583,29 +1596,32 @@ interface JQuery { droppable(optionLiteral: string, options: JQueryUI.DraggableOptions): any; droppable(optionLiteral: string, optionName: string, optionValue: any): JQuery; - menu(): JQuery; - menu(methodName: 'blur'): void; - menu(methodName: 'collapse', event?: JQueryEventObject): void; - menu(methodName: 'collapseAll', event?: JQueryEventObject, all?: boolean): void; - menu(methodName: 'destroy'): void; - menu(methodName: 'disable'): void; - menu(methodName: 'enable'): void; - menu(methodName: string, event: JQueryEventObject, item: JQuery): void; - menu(methodName: 'focus', event: JQueryEventObject, item: JQuery): void; - menu(methodName: 'isFirstItem'): boolean; - menu(methodName: 'isLastItem'): boolean; - menu(methodName: 'next', event?: JQueryEventObject): void; - menu(methodName: 'nextPage', event?: JQueryEventObject): void; - menu(methodName: 'previous', event?: JQueryEventObject): void; - menu(methodName: 'previousPage', event?: JQueryEventObject): void; - menu(methodName: 'refresh'): void; - menu(methodName: 'select', event?: JQueryEventObject): void; - menu(methodName: 'widget'): JQuery; - menu(methodName: string): JQuery; - menu(options: JQueryUI.MenuOptions): JQuery; - menu(optionLiteral: string, optionName: string): any; - menu(optionLiteral: string, options: JQueryUI.MenuOptions): any; - menu(optionLiteral: string, optionName: string, optionValue: any): JQuery; + menu: { + (): JQuery; + (methodName: 'blur'): void; + (methodName: 'collapse', event?: JQueryEventObject): void; + (methodName: 'collapseAll', event?: JQueryEventObject, all?: boolean): void; + (methodName: 'destroy'): void; + (methodName: 'disable'): void; + (methodName: 'enable'): void; + (methodName: string, event: JQueryEventObject, item: JQuery): void; + (methodName: 'focus', event: JQueryEventObject, item: JQuery): void; + (methodName: 'isFirstItem'): boolean; + (methodName: 'isLastItem'): boolean; + (methodName: 'next', event?: JQueryEventObject): void; + (methodName: 'nextPage', event?: JQueryEventObject): void; + (methodName: 'previous', event?: JQueryEventObject): void; + (methodName: 'previousPage', event?: JQueryEventObject): void; + (methodName: 'refresh'): void; + (methodName: 'select', event?: JQueryEventObject): void; + (methodName: 'widget'): JQuery; + (methodName: string): JQuery; + (options: JQueryUI.MenuOptions): JQuery; + (optionLiteral: string, optionName: string): any; + (optionLiteral: string, options: JQueryUI.MenuOptions): any; + (optionLiteral: string, optionName: string, optionValue: any): JQuery; + active: boolean; + } progressbar(): JQuery; progressbar(methodName: 'destroy'): void; From 9f02d024a6938f9cacb17ced718d818775656645 Mon Sep 17 00:00:00 2001 From: Raphael ATALLAH Date: Mon, 17 Aug 2015 15:54:05 -0700 Subject: [PATCH 135/794] Updated typescript definitions for angular-odata-resources. Added support for $select --- .../angular-odata-resources-tests.ts | 9 +++++++++ .../angular-odata-resources.d.ts | 13 ++++++++----- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/angular-odata-resources/angular-odata-resources-tests.ts b/angular-odata-resources/angular-odata-resources-tests.ts index 5b8dbcc52..23286adc0 100644 --- a/angular-odata-resources/angular-odata-resources-tests.ts +++ b/angular-odata-resources/angular-odata-resources-tests.ts @@ -197,3 +197,12 @@ users = odataResourceClass.odata() var countResult = odataResourceClass.odata().count(); var total = countResult.result; + + + +var usersSelect1 = odataResourceClass.odata() + .select('name', 'user'); + + +var usersSelect2 = odataResourceClass.odata() + .select(['name', 'user']); \ No newline at end of file diff --git a/angular-odata-resources/angular-odata-resources.d.ts b/angular-odata-resources/angular-odata-resources.d.ts index 0a83df2c3..fb6fa5b81 100644 --- a/angular-odata-resources/angular-odata-resources.d.ts +++ b/angular-odata-resources/angular-odata-resources.d.ts @@ -278,14 +278,17 @@ declare module OData { private expandables; constructor(callback: ProviderCallback); filter(operand1: any, operand2?: any, operand3?: any): Provider; - orderBy(arg1: any, arg2?: any): Provider; + orderBy(arg1: string, arg2?: string): Provider; take(amount: number): Provider; skip(amount: number): Provider; private execute(); - query(success?: any, error?: any): T[]; - single(success?: any, error?: any): T; - get(data: any, success?: any, error?: any): T; - expand(params: any, otherParam1?: any, otherParam2?: any, otherParam3?: any, otherParam4?: any, otherParam5?: any, otherParam6?: any, otherParam7?: any): Provider; + query(success?: ((p:T)=>void), error?: (()=>void)): T[]; + single(success?: ((p:T)=>void), error?: (()=>void)): T; + get(key: any, success?: ((p:T)=>void), error?: (()=>void)): T; + expand(...params: string[]): Provider; + expand(params: string[]): Provider; + select(...params: string[]): Provider; + select(params: string[]): Provider; count(success?: (result: ICountResult) => any, error?: () => any):ICountResult; withInlineCount(): Provider; } From 85674ef1dda1853af8429539afcfc0f2c360f1e2 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Mon, 17 Aug 2015 15:53:19 -0700 Subject: [PATCH 136/794] Added missing type argument. --- jqueryui/jqueryui.d.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/jqueryui/jqueryui.d.ts b/jqueryui/jqueryui.d.ts index 63ea4f444..5cd04f22d 100644 --- a/jqueryui/jqueryui.d.ts +++ b/jqueryui/jqueryui.d.ts @@ -753,8 +753,6 @@ declare module JQueryUI { heightStyle?: string; hide?: any; // boolean, number, string or object show?: any; // boolean, number, string or object - - activate?: TabsEvent; } interface TabsActivationUIParams { @@ -784,7 +782,8 @@ declare module JQueryUI { activate?: TabsEvent; beforeActivate?: TabsEvent; beforeLoad?: TabsEvent; - load?: TabsEvent; + load?: TabsEvent; + create?: TabsEvent; } interface Tabs extends Widget, TabsOptions { From e99ef514ee0989bb5ce126e43dffd52b15df0be8 Mon Sep 17 00:00:00 2001 From: Raphael ATALLAH Date: Mon, 17 Aug 2015 16:06:16 -0700 Subject: [PATCH 137/794] Fixed return type for query method --- angular-odata-resources/angular-odata-resources.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/angular-odata-resources/angular-odata-resources.d.ts b/angular-odata-resources/angular-odata-resources.d.ts index fb6fa5b81..f0619deed 100644 --- a/angular-odata-resources/angular-odata-resources.d.ts +++ b/angular-odata-resources/angular-odata-resources.d.ts @@ -282,7 +282,7 @@ declare module OData { take(amount: number): Provider; skip(amount: number): Provider; private execute(); - query(success?: ((p:T)=>void), error?: (()=>void)): T[]; + query(success?: ((p:T[])=>void), error?: (()=>void)): T[]; single(success?: ((p:T)=>void), error?: (()=>void)): T; get(key: any, success?: ((p:T)=>void), error?: (()=>void)): T; expand(...params: string[]): Provider; From fdb0de3a61d9a15fe60c33af92dbcbb792d60b48 Mon Sep 17 00:00:00 2001 From: Raphael ATALLAH Date: Mon, 17 Aug 2015 16:09:18 -0700 Subject: [PATCH 138/794] angular-odata-resources: added $promise property on the return type of count --- angular-odata-resources/angular-odata-resources.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/angular-odata-resources/angular-odata-resources.d.ts b/angular-odata-resources/angular-odata-resources.d.ts index f0619deed..7c625d40c 100644 --- a/angular-odata-resources/angular-odata-resources.d.ts +++ b/angular-odata-resources/angular-odata-resources.d.ts @@ -267,6 +267,7 @@ declare module OData { interface ICountResult{ result: number; + $promise: angular.IPromise; } class Provider { From 12d453946f096a52f48327d7744f5404eaf94877 Mon Sep 17 00:00:00 2001 From: Michael Randolph Date: Mon, 17 Aug 2015 19:31:51 -0400 Subject: [PATCH 139/794] node-jsfl-runner typings --- node-jsfl-runner/node-jsfl-runner-tests.ts | 21 +++++++++++++ node-jsfl-runner/node-jsfl-runner.d.ts | 35 ++++++++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 node-jsfl-runner/node-jsfl-runner-tests.ts create mode 100644 node-jsfl-runner/node-jsfl-runner.d.ts diff --git a/node-jsfl-runner/node-jsfl-runner-tests.ts b/node-jsfl-runner/node-jsfl-runner-tests.ts new file mode 100644 index 000000000..f92f4bfde --- /dev/null +++ b/node-jsfl-runner/node-jsfl-runner-tests.ts @@ -0,0 +1,21 @@ +/// + +import * as jsfl from 'node-jsfl-runner'; + +let myJSFL: jsfl.JSFL = { + init: (param: string): void => { + + } +} + +jsfl.createJSFL(myJSFL, 'fileName.jsfl', ['Hello!'], (err: NodeJS.ErrnoException) => { + +}); + +jsfl.runJSFL('fileName.jsfl', (err: NodeJS.ErrnoException) => { + +}); + +jsfl.deleteJSFL('fileName.jsfl', (err: NodeJS.ErrnoException) => { + +}); \ No newline at end of file diff --git a/node-jsfl-runner/node-jsfl-runner.d.ts b/node-jsfl-runner/node-jsfl-runner.d.ts new file mode 100644 index 000000000..b3f0a8688 --- /dev/null +++ b/node-jsfl-runner/node-jsfl-runner.d.ts @@ -0,0 +1,35 @@ +// Type definitions for node-jsfl-runner +// Project: https://www.npmjs.com/package/node-jsfl-runner +// Definitions by: Michael Randolph +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +declare module "node-jsfl-runner" { + interface JSFL { + init: (...args: any[]) => void; + [index: string]: any; + } + + /** + * Creates a JSFL file from a JSFL object + * @param jsfl A valid JSFL object + * @param fileName Path to output JSFL file location + * @param initParams Parameters to pass to JSFL init function + * @param callback Callback + */ + function createJSFL(jsfl: JSFL, fileName: string, initParams: Array, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Deletes a JSFL file + * @param fileName Path to JSFL file to delete + * @param callback Callback + */ + function deleteJSFL(fileName: string, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Runs a JSFL file + * @param fileName Path to JSFL file to run + * @param callback Callback + */ + function runJSFL(fileName: string, callback: (err: NodeJS.ErrnoException) => void): void; +} \ No newline at end of file From 245a296826db9afbe62f7b65851124585df61b9f Mon Sep 17 00:00:00 2001 From: Tim Perry Date: Tue, 11 Aug 2015 16:40:38 +0100 Subject: [PATCH 140/794] Make concat types support its full auto-flattening API --- lodash/lodash-tests.ts | 1 + lodash/lodash.d.ts | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 2cbec6853..22ff04e8b 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -123,6 +123,7 @@ result = <_.LoDashObjectWrapper<_.Dictionary>>_(<{ [index: string]: stri //Wrapped array shortcut methods result = <_.LoDashArrayWrapper>_([1, 2, 3, 4]).concat(5, 6); +result = <_.LoDashArrayWrapper>_([1, 2, 3, 4]).concat([5, 6]); result = _([1, 2, 3, 4]).join(','); result = _([1, 2, 3, 4]).pop(); result = <_.LoDashArrayWrapper>_([1, 2, 3, 4]).push(5, 6, 7); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index c088f5459..932146a3b 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -252,7 +252,7 @@ declare module _ { interface LoDashObjectWrapper extends LoDashWrapperBase> { } interface LoDashArrayWrapper extends LoDashWrapperBase> { - concat(...items: T[]): LoDashArrayWrapper; + concat(...items: Array>): LoDashArrayWrapper; join(seperator?: string): string; pop(): T; push(...items: T[]): LoDashArrayWrapper; From 337f471b428d53f03f209edf6d7f2c90ccae815b Mon Sep 17 00:00:00 2001 From: Gabriel Monteagudo Date: Tue, 18 Aug 2015 02:00:33 -0300 Subject: [PATCH 141/794] Definitions for ydn-db --- ydn-db/ydn-db-tests.ts | 82 +++++++++++ ydn-db/ydn-db.d.ts | 306 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 388 insertions(+) create mode 100644 ydn-db/ydn-db-tests.ts create mode 100644 ydn-db/ydn-db.d.ts diff --git a/ydn-db/ydn-db-tests.ts b/ydn-db/ydn-db-tests.ts new file mode 100644 index 000000000..95279b831 --- /dev/null +++ b/ydn-db/ydn-db-tests.ts @@ -0,0 +1,82 @@ +/// + +var schema = { + stores: [{ + name: 'todo', + keyPath: "timeStamp" + }] +}; + + +/** + * Create and initialize the database. Depending on platform, this will + * create IndexedDB or WebSql or even localStorage storage mechanism. + * @type {ydn.db.Storage} + */ +var db = new ydn.db.Storage('todo_2', schema); + +var deleteTodo = function(id: any) { + db.remove('todo', id).fail(function(e) { + console.error(e); + }); + + getAllTodoItems(); +}; + +var getAllTodoItems = function() { + var todos = document.getElementById("todoItems"); + todos.innerHTML = ""; + + var df = db.values('todo'); + + df.done(function(items) { + var n = items.length; + for (var i = 0; i < n; i++) { + renderTodo(items[i]); + } + }); + + df.fail(function(e) { + console.error(e); + }) +}; + +var renderTodo = function(row: any) { + var todos = document.getElementById("todoItems"); + var li = document.createElement("li"); + var a = document.createElement("a"); + var t = document.createTextNode(row.text); + + a.addEventListener("click", function() { + deleteTodo(row.timeStamp); + }, false); + + a.textContent = " [Delete]"; + li.appendChild(t); + li.appendChild(a); + todos.appendChild(li) +}; + +var addTodo = function() { + var todo = document.getElementById("todo"); + + var data = { + "text": todo.value, + "timeStamp": new Date().getTime() + }; + db.put('todo', data).fail(function(e) { + console.error(e); + }); + + todo.value = ""; + + getAllTodoItems(); +}; + +function init() { + getAllTodoItems(); +} + +db.onReady(function() { + init(); +}); diff --git a/ydn-db/ydn-db.d.ts b/ydn-db/ydn-db.d.ts new file mode 100644 index 000000000..564c8ad4c --- /dev/null +++ b/ydn-db/ydn-db.d.ts @@ -0,0 +1,306 @@ +// Type definitions for YDN-DB version 1 +// Project: http://dev.yathit.com/ydn-db/index.html +// Definitions by: Kyaw Tun , Gabriel Monteagudo +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface FullTextSource { + storeName: string; + keyPath: string; + weight?: number; +} + +interface FullTextCatalog { + name: string; + lang: string; + sources: FullTextSource[]; +} + +interface IndexSchemaJson { + name?: string; + keyPath: string|string[]; + type?: string; + unique?: boolean; + multiEntry?: boolean; +} + +interface StoreSchemaJson { + autoIncrement?: boolean; + dispatchEvents?: boolean; + name?: string; + indexes?: IndexSchemaJson[]; + keyPath?: string; + type?: string; +} + +interface DatabaseSchemaJson { + version?: number; + stores: StoreSchemaJson[]; + fullTextCatalogs?: FullTextCatalog; +} + +interface StorageOptions { + mechanisms?: string[]; + size?: number; + autoSchema?: boolean; + isSerial?: boolean; + requestType?: string; +} + +declare module ydn.db { + export class Request { + abort(): any; + always(callback: (data: any) => void): any; + done(callback: (data: any) => void): any; + fail(callback: (data: any) => void): any; + then(success_callback: (data: any) => any, error_callback: (data: Error) => any): any; + canAbort(): boolean; + } + + export function cmp(first: any, second: any): number; + + export function deleteDatabase(db_name: string, type?: string): void; + + export class Key { + constructor(json: Object); + constructor(key_string: string); + constructor(store_name: string, id: any, parent_key?: Key); + } + + export class Iterator { + join(peer_store_name: string, peer_field_name?: string, value?: any): any; + getKey(): any; + getPrimaryKey(): any; + reset(): Iterator; + restrict(peer_field_name: string, value: any): any; + resume(key: any, index_key: any): Iterator; + reverse(key: any, index_key: any): Iterator; + } + + enum EventType { + created, + deleted, + error, + fail, + ready, + updated + } + + enum Policy { + all, + atomic, + multi, + repeat, + single + } + + enum TransactionMode { + readonly, + readwrite + } + + enum Op { + ">", "<", "=", ">=", "<=", "^" + } + + export class IndexKeyIterator extends Iterator { + constructor(store_name: string, index_name: string, key_range?: any, reverse?: boolean); + + static where(store_name: string, index_name: string, op: Op, value: any, op2: Op, value2: any): any; + + } + + export class KeyIterator extends Iterator { + constructor(store_name: string, key_range?: any, reverse?: boolean); + + static where(store_name: string, op: Op, value: any, op2: Op, value2: any): any; + + } + + export class ValueIterator extends Iterator { + constructor(store_name: string, key_range?: any, reverse?: boolean); + + static where(store_name: string, op: Op, value: any, op2: Op, value2: any): any; + + } + + export class IndexValueIterator extends Iterator { + constructor(store_name: string, index_name: string, key_range?: any, reverse?: boolean); + + static where(store_name: string, index_name: string, op: Op, value: any, op2: Op, value2: any): any; + + } + + export class Streamer { + constructor(storage: ydn.db.Storage, store_name: string, opt_field_name?: string); + + push(key: any, value?: any): any; + + collect(callback: (values: any[]) => void): any; + + setSink(callback: (key: any, value: any, toWait: () => boolean) => void): any; + } + + export class ICursor { + getKey(i?: number): any; + getPrimaryKey(i?: number): any; + getValue(i?: number): any; + clear(i?: number): Request; + update(value: Object, i?: number): Request; + } + + export class Query { + count(): Request; + open(callback: (ICursor: any) => void, Iterator: any, TransactionMode: any): Request; + patch(Object: any): Request; + patch(field_name: string, value: any): Request; + patch(field_names: string[], value: any[]): Request; + order(field_name: string): Query; + order(field_name: string, descending: boolean): Query; + order(field_names: string[]): Query; + order(field_names: string[], descending: boolean): Query; + reverse(): Query; + list(): Request; + list(limit: number): Request; + where(field_name: string, op: Op, value: any): any; + where(field_name: string, op: Op, value: any, op2: Op, value2: any): any; + } + + export class DbOperator { + + add(store_name: string, value: any, key: any): Request; + add(store_name: string, value: any): Request; + + clear(store_name: string, key_or_key_range: any): Request; + clear(store_name: string): Request; + clear(store_names: string[]): Request; + + count(store_name: string, key_range?: any): Request; + count(store_name: string, index_name: string, key_range: any): Request; + count(store_names: string[]): Request; + + executeSql(sql: string, params?: any[]): Request; + + from(store_name: string): Query; + from(store_name: string, op: Op, value: any): Query; + from(store_name: string, op: Op, value: any, op2: Op, value2: any): Query; + + get(store_name: string, key: any): Request; + + keys(iter: Iterator, limit?: number): Request; + keys(store_name: string, key_range?: Object, limit?: number, offset?: number, reverse?: boolean): Request; + keys(store_name: string, index_name: string, key_range?: Object, limit?: number, offset?: number, reverse?: boolean): Request; + keys(store_name: string, limit?: boolean, offset?: number): Request; + + open(next_callback: (cursor: ICursor) => any, iterator: Iterator, mode: TransactionMode): Request; + + put(store_name: string, value: any, key: any): Request; + put(store_name: string, value: any[], key: any[]): Request; + put(store_name: string, value: any): Request; + put(store_name: string, value: any[]): Request; + + remove(store_name: string, id_or_key_range: any): Request; + remove(store_name: string, index_name: string, id_or_key_range: any): Request; + clear(store_name: string, key_or_key_range: any): Request; + + scan(solver: (keys: any[], values: any[]) => any, iterators: Iterator[]): Request; + + values(iter: Iterator, limit?: number): Request; + values(store_name: string, key_range?: Object, limit?: number, offset?: number, reverse?: boolean): Request; + values(store_name: string, index_name: string, key_range?: Object, limit?: number, offset?: number, reverse?: boolean): Request; + values(store_name: string, ids?: Array): Request; + values(keys?: Array): Request; + } + + export class Storage extends DbOperator { + + constructor(db_name?: string, schema?: DatabaseSchemaJson, options?: StorageOptions); + + addEventListener(type: EventType, handler: (event: any) => void, capture?: boolean): any; + addEventListener(type: EventType[], handler: (event: any) => void, capture?: boolean): any; + + branch(thread: Policy, isSerial: boolean, scope: string[], mode: TransactionMode, maxRequest: number): DbOperator; + + close(): any; + + get(store_name: string, key: any): Request; + + getName(callback: any): string; + + getSchema(callback: any): DatabaseSchemaJson; + + getType(): string; + + onReady(Error?: any): any; + + removeEventListener(type: EventType, handler: (event: any) => void, capture?: boolean): any; + removeEventListener(type: EventType[], handler: (event: any) => void, capture?: boolean): any; + + run(callback: (iStorage: ydn.db.Storage) => void, store_names: string[], mode: TransactionMode): Request; + + search(catalog_name: string): Request; + + setName(name: string): any; + + transaction(callback: (tx: any) => void, store_names: string[], mode: TransactionMode, completed_handler: (type: string, e?: Error) => void): any; + + } +} + +declare module ydb.db.algo { + + export class Solver { + + } + + export class NestedLoop extends Solver { + constructor(out: { push: (value: any) => void }, limit?: number); + } + + export class SortedMerge extends Solver { + constructor(out: { push: (value: any) => void }, limit?: number); + } + + export class ZigzagMerge extends Solver { + constructor(out: { push: (value: any) => void }, limit?: number); + } + +} + +declare module ydn.db.events { + + export class Event { + + name: string; + + type: ydn.db.EventType; + } + + export class RecordEvent extends Event { + + getStoreName(): string; + + getKey(): any; + + getValue(): any; + } + + + export class StorageEvent extends Event { + + getError(): Error; + + getVersion(): number; + + getOldVersion(): number; + } + + + export class StoreEvent extends Event { + + getStoreName(): string; + + getKeys(): any[]; + + getValues(): any[]; + } +} From 92ce54989d828b19f0759dd581f10055975ba81f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20Corbi=C3=A8re?= Date: Tue, 18 Aug 2015 19:26:06 +0200 Subject: [PATCH 142/794] [gulp-less] Update the definition of IOptions Add "modifyVars" Make "paths" optional --- gulp-less/gulp-less-tests.ts | 16 ++++++++++++++++ gulp-less/gulp-less.d.ts | 3 ++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/gulp-less/gulp-less-tests.ts b/gulp-less/gulp-less-tests.ts index 76e0a697c..a0671e766 100644 --- a/gulp-less/gulp-less-tests.ts +++ b/gulp-less/gulp-less-tests.ts @@ -4,6 +4,22 @@ import gulp = require("gulp"); import less = require("gulp-less"); +// Without options +gulp.task("less", () => { + gulp.src("less/**/*.less") + .pipe(less()) + .pipe(gulp.dest("public/css")); +}); + +// With an empty option object +gulp.task("less", () => { + gulp.src("less/**/*.less") + .pipe(less({})) + .pipe(gulp.dest("public/css")); +}); + + +// With some options gulp.task("less", () => { gulp.src("less/**/*.less") .pipe(less({ diff --git a/gulp-less/gulp-less.d.ts b/gulp-less/gulp-less.d.ts index 9ca5e35b7..84adca370 100644 --- a/gulp-less/gulp-less.d.ts +++ b/gulp-less/gulp-less.d.ts @@ -8,7 +8,8 @@ declare module "gulp-less" { interface IOptions { - paths: string[]; + modifyVars?: {}; + paths?: string[]; plugins?: any[]; } From 3aba989e923199d9c4834b2c69eb698c9276b344 Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Tue, 18 Aug 2015 19:04:19 +0100 Subject: [PATCH 143/794] Type definitions and tests for upper-case --- upper-case/upper-case.d.ts | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 upper-case/upper-case.d.ts diff --git a/upper-case/upper-case.d.ts b/upper-case/upper-case.d.ts new file mode 100644 index 000000000..c59348776 --- /dev/null +++ b/upper-case/upper-case.d.ts @@ -0,0 +1,9 @@ +// Type definitions for upper-case +// Project: https://github.com/blakeembrey/upper-case +// Definitions by: Sam Saint-Pettersen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "upper-case" { + function upperCase(string: any, locale?: string): string; + export = upperCase; +} From 6e22f9146c5f0cb87a2fc582dfa2d0a3c025fb72 Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Tue, 18 Aug 2015 19:06:32 +0100 Subject: [PATCH 144/794] Type definitions and tests for upper-case --- upper-case/upper-case-tests.ts | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 upper-case/upper-case-tests.ts diff --git a/upper-case/upper-case-tests.ts b/upper-case/upper-case-tests.ts new file mode 100644 index 000000000..7e1a4a0b5 --- /dev/null +++ b/upper-case/upper-case-tests.ts @@ -0,0 +1,9 @@ +/// + +import upperCase = require('upper-case'); + +console.log(upperCase(null)); // => "" +console.log(upperCase('string')); // => "STRING" +console.log(upperCase('string', 'tr')); // => "STRİNG" + +console.log(upperCase({ toString: function() { return 'test' } })); // => "TEST" From 95c2990f0ac17d991f72bbc51fb3217ce354809c Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Tue, 18 Aug 2015 19:07:18 +0100 Subject: [PATCH 145/794] Update upper-case-tests.ts --- upper-case/upper-case-tests.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/upper-case/upper-case-tests.ts b/upper-case/upper-case-tests.ts index 7e1a4a0b5..a7128bdf6 100644 --- a/upper-case/upper-case-tests.ts +++ b/upper-case/upper-case-tests.ts @@ -4,6 +4,5 @@ import upperCase = require('upper-case'); console.log(upperCase(null)); // => "" console.log(upperCase('string')); // => "STRING" -console.log(upperCase('string', 'tr')); // => "STRİNG" console.log(upperCase({ toString: function() { return 'test' } })); // => "TEST" From 4af10f4fae29eabec77058fc16b88af282bbea70 Mon Sep 17 00:00:00 2001 From: Dan Lewi Harkestad Date: Tue, 18 Aug 2015 20:09:11 +0200 Subject: [PATCH 146/794] Added tests covering all modifications. --- angular-ui-router/angular-ui-router-tests.ts | 48 ++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/angular-ui-router/angular-ui-router-tests.ts b/angular-ui-router/angular-ui-router-tests.ts index a05f13dd8..dccd8f7b1 100644 --- a/angular-ui-router/angular-ui-router-tests.ts +++ b/angular-ui-router/angular-ui-router-tests.ts @@ -14,12 +14,28 @@ myApp.config(( var matcher: ng.ui.IUrlMatcher = $urlMatcherFactory.compile("/foo/:bar?param1"); + $urlMatcherFactory.caseInsensitive(false); + var isCaseInsensitive = $urlMatcherFactory.caseInsensitive(); + + $urlMatcherFactory.defaultSquashPolicy("nosquash"); + + $urlMatcherFactory.strictMode(true); + var isStrictMode = $urlMatcherFactory.strictMode(); + $urlMatcherFactory.type("myType2", { encode: function (item: any) { return item; }, decode: function (item: any) { return item; }, is: function (item: any) { return true; } }); + $urlMatcherFactory.type("fullType", { + decode: (val) => parseInt(val, 10), + encode: (val) => val && val.toString(), + equals: (a, b) => this.is(a) && a === b, + is: (val) => angular.isNumber(val) && isFinite(val) && val % 1 === 0, + pattern: /\d+/ + }); + var obj: Object = matcher.exec('/user/bob', { x:'1', q:'hello' }); var concat: ng.ui.IUrlMatcher = matcher.concat('/test'); var str: string = matcher.format({ id:'bob', q:'yes' }); @@ -177,3 +193,35 @@ module UiViewScrollProviderTests { $uiViewScrollProvider.useAnchorScroll(); }]); } + +interface ITestUserService { + isLoggedIn: () => boolean; + handleLogin: () => ng.IPromise<{}>; +} + +module UrlRouterProviderTests { + var app = angular.module("urlRouterProviderTests", ["ui.router"]); + + app.config(($urlRouterProvider: ng.ui.IUrlRouterProvider) => { + // Prevent $urlRouter from automatically intercepting URL changes; + // this allows you to configure custom behavior in between + // location changes and route synchronization: + $urlRouterProvider.deferIntercept(); + }).run(($rootScope: ng.IRootScopeService, $urlRouter: ng.ui.IUrlRouterService, UserService: ITestUserService) => { + $rootScope.$on('$locationChangeSuccess', e => { + // UserService is an example service for managing user state + if (UserService.isLoggedIn()) return; + + // Prevent $urlRouter's default handler from firing + e.preventDefault(); + + UserService.handleLogin().then(() => { + // Once the user has logged in, sync the current URL to the router: + $urlRouter.sync(); + }); + }); + + // Configures $urlRouter's listener *after* your custom listener + $urlRouter.listen(); + }); +} From 763868e7deed5a5087aa1e0e2455656109d9e628 Mon Sep 17 00:00:00 2001 From: MugeSo Date: Wed, 19 Aug 2015 11:32:47 +0900 Subject: [PATCH 147/794] rsmq-worker: export Client interface --- rsmq-worker/rsmq-worker-tests.ts | 4 +- rsmq-worker/rsmq-worker.d.ts | 71 ++++++++++++++++---------------- 2 files changed, 39 insertions(+), 36 deletions(-) diff --git a/rsmq-worker/rsmq-worker-tests.ts b/rsmq-worker/rsmq-worker-tests.ts index 4568302dd..fa635e415 100644 --- a/rsmq-worker/rsmq-worker-tests.ts +++ b/rsmq-worker/rsmq-worker-tests.ts @@ -1,7 +1,9 @@ import RSMQWorker = require('rsmq-worker'); -var worker = new RSMQWorker("my-queue"); +var worker: RSMQWorker.Client; + +worker = new RSMQWorker("my-queue"); worker.changeInterval(1); worker.changeInterval([0, 1, 5, 10]); diff --git a/rsmq-worker/rsmq-worker.d.ts b/rsmq-worker/rsmq-worker.d.ts index 8783d914f..9823daa87 100644 --- a/rsmq-worker/rsmq-worker.d.ts +++ b/rsmq-worker/rsmq-worker.d.ts @@ -9,44 +9,45 @@ declare module "rsmq-worker" { import redis = require('redis'); import events = require('events'); - interface CallbackT { - (e?:Error, res?:R): void; + module RSMQWorker { + export interface Client extends events.EventEmitter { + start(): Client; + stop(): Client; + send(message: string, delay?: number, cb?: CallbackT): Client; + send(message: string, cb: CallbackT): Client; + del(id: string, cb?: CallbackT): Client; + changeInterval(interval: number|number[]): Client; + } + + export interface Options { + interval?: number; + maxReceiveCount?: number; + invisibletime?: number; + defaultDelay?: number; + autostart?: boolean; + timeout: number; + customExceedCheck?: CustomExceedCheckCallback; + rsmq?: RedisSMQ.Client; + redis?: redis.RedisClient; + redisPrefix?: string; + host?: string; + port?: number; + options?: redis.ClientOpts; + } + + export interface CustomExceedCheckCallback { + (message: RedisSMQ.Message): boolean; + } + + export interface CallbackT { + (e?:Error, res?:R): void; + } } interface RSMQWorkerStatic { - new(queuename: string, options?: WorkerOptions): RSMQWorker; + new(queuename: string, options?: RSMQWorker.Options): RSMQWorker.Client; } - interface WorkerOptions { - interval?: number; - maxReceiveCount?: number; - invisibletime?: number; - defaultDelay?: number; - autostart?: boolean; - timeout: number; - customExceedCheck?: CustomExceedCheckCallback; - rsmq?: RedisSMQ.Client; - redis?: redis.RedisClient; - redisPrefix?: string; - host?: string; - port?: number; - options?: redis.ClientOpts; - } - - interface CustomExceedCheckCallback { - (message: RedisSMQ.Message): boolean; - } - - - interface RSMQWorker extends events.EventEmitter { - start(): RSMQWorker; - stop(): RSMQWorker; - send(message: string, delay?: number, cb?: CallbackT): RSMQWorker; - send(message: string, cb: CallbackT): RSMQWorker; - del(id: string, cb?: CallbackT): RSMQWorker; - changeInterval(interval: number|number[]): RSMQWorker; - } - - var worker: RSMQWorkerStatic; - export = worker; + var RSMQWorker: RSMQWorkerStatic; + export = RSMQWorker; } From a0f49f14ee51736e8dbd625942214674c9fe9a1f Mon Sep 17 00:00:00 2001 From: MugeSo Date: Wed, 19 Aug 2015 11:37:34 +0900 Subject: [PATCH 148/794] rsmq-worker: change Options.timeout optional --- rsmq-worker/rsmq-worker.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rsmq-worker/rsmq-worker.d.ts b/rsmq-worker/rsmq-worker.d.ts index 9823daa87..6af1564e1 100644 --- a/rsmq-worker/rsmq-worker.d.ts +++ b/rsmq-worker/rsmq-worker.d.ts @@ -25,7 +25,7 @@ declare module "rsmq-worker" { invisibletime?: number; defaultDelay?: number; autostart?: boolean; - timeout: number; + timeout?: number; customExceedCheck?: CustomExceedCheckCallback; rsmq?: RedisSMQ.Client; redis?: redis.RedisClient; From 6ddf6c5edea0f2385c5c4af837fefddb29ac8cfe Mon Sep 17 00:00:00 2001 From: zenorbi Date: Wed, 19 Aug 2015 09:48:06 +0200 Subject: [PATCH 149/794] Fixed feedbackData.device being a Device instead of a Buffer --- apn/apn-test.ts | 4 ++-- apn/apn.d.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/apn/apn-test.ts b/apn/apn-test.ts index a9e2c21a7..b47259d76 100644 --- a/apn/apn-test.ts +++ b/apn/apn-test.ts @@ -50,7 +50,7 @@ var feedbackService = new apn.Feedback({ feedbackService.on("error", (error:Error) => { console.log("push feedback error", error.name, error.message); }); -function processFeedbackData(device:Buffer, time:number) { +function processFeedbackData(device:apn.Device, time:number) { } feedbackService.on("feedback", (feedbackData) => { feedbackData.forEach((data) => { @@ -135,7 +135,7 @@ pushSomeNotifications(); function handleFeedback(feedbackData:apn.FeedbackData[]) { feedbackData.forEach(function(feedbackItem) { - console.log("Device: " + feedbackItem.device.toString("hex") + " has been unreachable, since: " + feedbackItem.time); + console.log("Device: " + feedbackItem.device.toString() + " has been unreachable, since: " + feedbackItem.time); }); } diff --git a/apn/apn.d.ts b/apn/apn.d.ts index ed38086ef..cd67743da 100644 --- a/apn/apn.d.ts +++ b/apn/apn.d.ts @@ -307,7 +307,7 @@ declare module "apn" { } export interface FeedbackData { time:number; - device:Buffer; + device:Device; } /** * Connection to the Apple Push Notification Feedback Service and if `interval` isn't disabled automatically begins polling the service. Many of the options are the same as `apn.Connection()` From 2daf450b8f86f09f6b0de1b5f86fce3cf185c687 Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 19 Aug 2015 14:21:19 +0200 Subject: [PATCH 150/794] updated enabled as per angular changes (after 1.3.14 > 1.4.0) --- angularjs/angular-animate.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/angularjs/angular-animate.d.ts b/angularjs/angular-animate.d.ts index 1ecc3d0d7..35fe10ca9 100644 --- a/angularjs/angular-animate.d.ts +++ b/angularjs/angular-animate.d.ts @@ -30,11 +30,11 @@ declare module angular.animate { /** * Globally enables / disables animations. * - * @param value If provided then set the animation on or off. * @param element If provided then the element will be used to represent the enable/disable operation. + * @param value If provided then set the animation on or off. * @returns current animation state */ - enabled(value?: boolean, element?: JQuery): boolean; + enabled(element?: JQuery, value?: boolean): boolean; /** * Performs an inline animation on the element. From 3ef00546da8850c9c962bffb87d65cd43a9b262b Mon Sep 17 00:00:00 2001 From: Marcin Porebski Date: Wed, 19 Aug 2015 15:09:10 +0200 Subject: [PATCH 151/794] url-template definitions --- url-template/url-template-tests.ts | 13 +++++++++++++ url-template/url-template.d.ts | 24 ++++++++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 url-template/url-template-tests.ts create mode 100644 url-template/url-template.d.ts diff --git a/url-template/url-template-tests.ts b/url-template/url-template-tests.ts new file mode 100644 index 000000000..f477a160a --- /dev/null +++ b/url-template/url-template-tests.ts @@ -0,0 +1,13 @@ +/// + + +import urlTemplate = require('url-template'); + +var emailUrl = urlTemplate.parse('/{email}/{folder}/{id}'); + +// Returns '/user@domain/test/42' +emailUrl.expand({ + email: 'user@domain', + folder: 'test', + id: 42 +}); diff --git a/url-template/url-template.d.ts b/url-template/url-template.d.ts new file mode 100644 index 000000000..6ed7f5e86 --- /dev/null +++ b/url-template/url-template.d.ts @@ -0,0 +1,24 @@ +// Type definitions for url-template 2.0.6 +// Project: https://github.com/bramstein/url-template +// Definitions by: Marcin Porębski +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module UrlTemplate +{ + interface TemplateParser { + parse(template: string): Template; + } + + interface Template { + expand(parameters: any): string; + } +} + +declare module "url-template" +{ + var urlTemplate: UrlTemplate.TemplateParser; + + export = urlTemplate; +} + + From 44e32d3b32c98cb1aa16ec5ea8e5b48b29e58b55 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Karl=20D=C3=BC=C3=BCna?= Date: Wed, 19 Aug 2015 17:13:35 +0300 Subject: [PATCH 152/794] easy-xapi-utils --- easy-xapi-utils/easy-xapi-utils-tests.ts | 43 ++++++++++++++++++++++++ easy-xapi-utils/easy-xapi-utils.d.ts | 16 +++++++++ 2 files changed, 59 insertions(+) create mode 100644 easy-xapi-utils/easy-xapi-utils-tests.ts create mode 100644 easy-xapi-utils/easy-xapi-utils.d.ts diff --git a/easy-xapi-utils/easy-xapi-utils-tests.ts b/easy-xapi-utils/easy-xapi-utils-tests.ts new file mode 100644 index 000000000..d80a7976c --- /dev/null +++ b/easy-xapi-utils/easy-xapi-utils-tests.ts @@ -0,0 +1,43 @@ +/** + * Created by karl on 14/07/15. + */ + +/// +/// +/// + +import express = require('express'); +import eXapi = require('easy-xapi'); +import eUtils = require('easy-xapi-utils'); + +eXapi.init({ + jSend: { + partial: true + } +}); + +var xApi = eXapi.create({ + root: __dirname, + log: { + name: 'Log', + level: 'info' + }, + port: 3000, + name: 'test', + mount: function (app) { + app.get('/', eUtils.isLoggedIn(), function (req, res) { + res.send('ok'); + }); + app.get('/role', eUtils.isLoggedIn('admin'), function (req, res) { + res.send('ok'); + }); + app.get('/', eUtils.isLoggedOut(), function (req, res) { + res.send('ok'); + }); + app.get('/role', eUtils.hasRole('guest'), function (req, res) { + res.send('ok'); + }); + } +}); + +xApi.listen(); diff --git a/easy-xapi-utils/easy-xapi-utils.d.ts b/easy-xapi-utils/easy-xapi-utils.d.ts new file mode 100644 index 000000000..637829098 --- /dev/null +++ b/easy-xapi-utils/easy-xapi-utils.d.ts @@ -0,0 +1,16 @@ +// Type definitions for easy-xapi-utils +// Project: https://github.com/DeadAlready/easy-xapi-utils +// Definitions by: Karl Düüna +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// +/// + +declare module "easy-xapi-utils" { + import express = require('express'); + + export function isLoggedIn(role?: string): express.RequestHandler; + export function isLoggedOut(): express.RequestHandler; + export function hasRole(role: string): express.RequestHandler; +} From 146fd6207c80d1c4abb7f098b9ba722cfbc435f0 Mon Sep 17 00:00:00 2001 From: Igor Kriklivetc Date: Wed, 19 Aug 2015 17:23:41 +0300 Subject: [PATCH 153/794] Update to 15.1.6 --- devextreme/dx.devextreme-15.1.5.d.ts | 6497 ++++++++++++++++++++++++++ devextreme/dx.devextreme.d.ts | 91 +- 2 files changed, 6573 insertions(+), 15 deletions(-) create mode 100644 devextreme/dx.devextreme-15.1.5.d.ts diff --git a/devextreme/dx.devextreme-15.1.5.d.ts b/devextreme/dx.devextreme-15.1.5.d.ts new file mode 100644 index 000000000..aff710888 --- /dev/null +++ b/devextreme/dx.devextreme-15.1.5.d.ts @@ -0,0 +1,6497 @@ +// Type definitions for DevExtreme 15.1.5 +// Project: http://js.devexpress.com/ +// Definitions by: DevExpress Inc. +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module DevExpress { + /** A mixin that provides a capability to fire and subscribe to events. */ + export interface EventsMixin { + /** Subscribes to a specified event. */ + on(eventName: string, eventHandler: Function): T; + /** Subscribes to the specified events. */ + on(events: { [eventName: string]: Function; }): T; + /** Detaches all event handlers from the specified event. */ + off(eventName: string): Object; + /** Detaches a particular event handler from the specified event. */ + off(eventName: string, eventHandler: Function): T; + } + /** An object that serves as a namespace for the methods required to perform validation. */ + export module validationEngine { + export interface IValidator { + validate(): ValidatorValidationResult; + reset(): void; + } + export interface ValidatorValidationResult { + isValid: boolean; + name?: string; + value: any; + brokenRule: any; + validationRules: any[]; + } + export interface ValidationGroupValidationResult { + isValid: boolean; + brokenRules: any[]; + validators: IValidator[]; + } + export interface GroupConfig extends EventsMixin { + group: any; + validators: IValidator[]; + validate(): ValidationGroupValidationResult; + reset(): void; + } + /** Provides access to the object that represents the specified validation group. */ + export function getGroupConfig(group: any): GroupConfig + /** Provides access to the object that represents the default validation group. */ + export function getGroupConfig(): GroupConfig + /** Validates rules of the validators that belong to the specified validation group. */ + export function validateGroup(group: any): ValidationGroupValidationResult; + /** Validates rules of the validators that belong to the default validation group. */ + export function validateGroup(): ValidationGroupValidationResult; + /** Resets the values and validation result of the editors that belong to the specified validation group. */ + export function resetGroup(group: any): void; + /** Resets the values and validation result of the editors that belong to the default validation group. */ + export function resetGroup(): void; + /** Validates the rules that are defined within the dxValidator objects that are registered for the specified ViewModel. */ + export function validateModel(model: Object): ValidationGroupValidationResult; + /** Registers all the dxValidator objects by which the fields of the specified ViewModel are extended. */ + export function registerModelForValidation(model: Object) : void; + } + export var hardwareBackButton: JQueryCallback; + /** Processes the hardware back button click. */ + export function processHardwareBackButton(): void; + /** Specifies whether or not the entire application/site supports right-to-left representation. */ + export var rtlEnabled: boolean; + /** Registers a new component in the DevExpress.ui namespace, and a jQuery plugin and Knockout binding for the required component. */ + export function registerComponent(name: string, componentClass: Object): void; + /** Registers a new component in the specified namespace as a jQuery plugin, Angular directive and Knockout binding. */ + export function registerComponent(name: string, namespace: Object, componentClass: Object): void; + /** Requests that the browser call a specified function to update animation before the next repaint. */ + export function requestAnimationFrame(callback: Function): number; + /** Cancels an animation frame request scheduled with the requestAnimationFrame method. */ + export function cancelAnimationFrame(requestID: number): void; + /** Custom Knockout binding that links an HTML element with a specific action. */ + export class Action { } + /** Used to get URLs that vary in a locally running application and the application running on production. */ + export class EndpointSelector { + constructor(options: { + [key: string]: { + local?: string; + production?: string; + } + }); + /** Returns a local or a productional URL depending on how the application is currently running. */ + urlFor(key: string): string; + } + /** An object that serves as a namespace for the methods that are used to animate UI elements. */ + export module fx { + /** Defines animation options. */ + export interface AnimationOptions { + /** A function called after animation is completed. */ + complete?: (element: JQuery, config: AnimationOptions) => void; + /** A number specifying wait time before animation execution. */ + delay?: number; + /** A number specifying the time period to wait before the animation of the next stagger item starts. */ + staggerDelay?: number; + /** A number specifying the time in milliseconds spent on animation. */ + duration?: number; + /** A string specifying the type of an easing function used for animation. */ + easing?: string; + /** Specifies the initial animation state. */ + from?: any; + /** A function called before animation is started. */ + start?: (element: JQuery, config: AnimationOptions) => void; + /** Specifies a final animation state. */ + to?: any; + /** A string value specifying the animation type. */ + type?: string; + /** Specifies the animation direction for the "slideIn" and "slideOut" animation types. */ + direction?: string; + } + /** Animates the specified element. */ + export function animate(element: HTMLElement, config: AnimationOptions): Object; + /** Returns a value indicating whether the specified element is being animated. */ + export function isAnimating(element: HTMLElement): boolean; + /** Stops the animation. */ + export function stop(element: HTMLElement, jumpToEnd: boolean): void; + } + /** The manager that performs several specified animations at a time. */ + export class TransitionExecutor { + /** Deletes all the animations registered in the Transition Executor by using the enter(elements, animation) and leave(elements, animation) methods. */ + reset(): void; + /** Registers a set of elements that should be animated as "entering" using the specified animation configuration. */ + enter(elements: JQuery, animation: any): void; + /** Registers a set of elements that should be animated as "leaving" using the specified animation configuration. */ + leave(elements: JQuery, animation: any): void; + /** Starts all the animations registered using the enter(elements, animation) and leave(elements, animation) methods beforehand. */ + start(config: Object): JQueryPromise; + } + export class AnimationPresetCollection { + /** Resets all the changes made in the animation repository. */ + resetToDefaults(): void; + /** Deletes the specified animation or clears all the animation repository, if an animation name is not passed. */ + clear(name: string): void; + /** Adds the specified animation preset to the animation repository by the specified name. */ + registerPreset(name: string, config: any): void; + /** Applies the changes made in the animation repository. */ + applyChanges(): void; + /** Returns the configuration of the animation found in the animation repository by the specified name for the current device. */ + getPreset(name: string): void; + /** Registers predefined animations in the animation repository. */ + registerDefaultPresets(): void; + } + /** A repository of animations. */ + export var animationPresets: AnimationPresetCollection; + /** The device object defines the device on which the application is running. */ + export interface Device { + /** Indicates whether or not the device platform is Android. */ + android?: boolean; + /** Specifies the type of the device on which the application is running. */ + deviceType?: string; + /** Indicates whether or not the device platform is generic, which means that the application will look and behave according to a generic "light" or "dark" theme. */ + generic?: boolean; + /** Indicates whether or not the device platform is iOS. */ + ios?: boolean; + /** Indicates whether or not the device type is 'phone'. */ + phone?: boolean; + /** Specifies the platform of the device on which the application is running. */ + platform?: string; + /** Indicates whether or not the device type is 'tablet'. */ + tablet?: boolean; + /** Specifies an array with the major and minor versions of the device platform. */ + version?: Array; + /** Indicates whether or not the device platform is Windows8. */ + win8?: boolean; + /** Specifies a performance grade of the current device. */ + grade?: string; + } + export class Devices implements EventsMixin { + constructor(options: { window: Window }); + /** Overrides actual device information to force the application to operate as if it was running on the specified device. */ + current(deviceName: any): void; + /** Returns information about the current device. */ + current(): Device; + orientationChanged: JQueryCallback; + /** Returns the current device orientation. */ + orientation(): string; + /** Returns real information about the current device regardless of the value passed to the devices.current(deviceName) method. */ + real(): Device; + on(eventName: "orientationChanged", eventHandler: (e: { orientation: string }) => void): Devices; + on(eventName: string, eventHandler: Function): Devices; + on(events: { [eventName: string]: Function; }): Devices; + off(eventName: "orientationChanged"): Devices; + off(eventName: string): Devices; + off(eventName: "orientationChanged", eventHandler: (e: { orientation: string }) => void): Devices; + off(eventName: string, eventHandler: Function): Devices; + } + /** An object that serves as a namespace for the methods and events specifying information on the current device. */ + export var devices: Devices; + /** The position object specifies the widget positioning options. */ + export interface PositionOptions { + /** The target element position that the widget is positioned against. */ + at?: string; + /** The element within which the widget is positioned. */ + boundary?: Element; + /** A string value holding horizontal and vertical offset from the window's boundaries. */ + boundaryOffset?: string; + /** Specifies how to move the widget if it overflows the screen. */ + collision?: any; + /** The position of the widget to align against the target element. */ + my?: string; + /** The target element that the widget is positioned against. */ + of?: HTMLElement; + /** A string value holding horizontal and vertical offset in pixels, separated by a space (e.g., "5 -10"). */ + offset?: string; + } + export interface ComponentOptions { + /** A handler for the initialized event. */ + onInitialized?: Function; + /** A handler for the optionChanged event. */ + onOptionChanged?: Function; + /** A handler for the disposing event. */ + onDisposing?: Function; + } + /** A base class for all components and widgets. */ + export class Component { + constructor(options?: ComponentOptions) + /** Prevents the component from refreshing until the endUpdate method is called. */ + beginUpdate(): void; + /** Enables the component to refresh after the beginUpdate method call. */ + endUpdate(): void; + /** Returns an instance of this component class. */ + instance(): Component; + /** Sets one or more options of this component. */ + option(options: Object): void; + /** Returns the configuration options of this component. */ + option(): Object; + /** Gets the value of the specified configuration option of this component. */ + option(optionName: string): any; + /** Sets a value to the specified configuration option of this component. */ + option(optionName: string, optionValue: any): void; + } + export interface DOMComponentOptions extends ComponentOptions { + /** Specifies whether or not the current component supports a right-to-left representation. */ + rtlEnabled?: boolean; + /** Specifies the height of the widget. */ + height?: any; + /** Specifies the width of the widget. */ + width?: any; + } + /** A base class for all components. */ + export class DOMComponent extends Component { + constructor(element: JQuery, options?: DOMComponentOptions); + constructor(element: HTMLElement, options?: DOMComponentOptions); + /** Returns the root HTML element of the widget. */ + element(): JQuery; + /** Specifies the device-dependent default configuration options for this component. */ + static defaultOptions(rule: { + device?: any; + options?: any; + }): void; + } + export module data { + export interface ODataError extends Error { + httpStatus?: number; + errorDetails?: any; + } + export interface StoreOptions { + inserted?: (values: Object, key: any) => void; + inserting?: (values: Object) => void; + loaded?: (result: Array) => void; + loading?: (loadOptions: LoadOptions) => void; + modified?: () => void; + modifying?: () => void; + removed?: (key: any) => void; + removing?: (key: any) => void; + updated?: (key: any, values: Object) => void; + updating?: (key: any, values: Object) => void; + /** A handler for the modified event. */ + onModified?: () => void; + /** A handler for the modifying event. */ + onModifying?: () => void; + /** A handler for the removed event. */ + onRemoved?: (key: any) => void; + /** A handler for the removing event. */ + onRemoving?: (key: any) => void; + /** A handler for the updated event. */ + onUpdated?: (key: any, values: Object) => void; + /** A handler for the updating event. */ + onUpdating?: (key: any, values: Object) => void; + /** A handler for the loaded event. */ + onLoaded?: (result: Array) => void; + /** A handler for the loading event. */ + onLoading?: (loadOptions: LoadOptions) => void; + /** A handler for the inserted event. */ + onInserted?: (values: Object, key: any) => void; + /** A handler for the inserting event. */ + onInserting?: (values: Object) => void; + /** Specifies the function called when the Store causes an error. */ + errorHandler?: (e: Error) => void; + /** Specifies the key properties within the data associated with the Store. */ + key?: any; + } + export interface LoadOptions { + filter?: Object; + sort?: Object; + select?: Object; + expand?: Object; + group?: Object; + skip?: number; + take?: number; + userData?: Object; + requireTotalCount?: boolean; + } + /** The base class for all Stores. */ + export class Store implements EventsMixin { + inserted: JQueryCallback; + inserting: JQueryCallback; + loaded: JQueryCallback; + loading: JQueryCallback; + modified: JQueryCallback; + modifying: JQueryCallback; + removed: JQueryCallback; + removing: JQueryCallback; + updated: JQueryCallback; + updating: JQueryCallback; + constructor(options?: StoreOptions); + /** Returns the data item specified by the key. */ + byKey(key: any): JQueryPromise; + /** Adds an item to the data associated with this Store. */ + insert(values: Object): JQueryPromise; + /** Returns the key expression specified via the key configuration option. */ + key(): any; + /** Returns the key of the Store item that matches the specified object. */ + keyOf(obj: Object): any; + /** Starts loading the data. */ + load(obj?: LoadOptions): JQueryPromise; + /** Removes the data item specified by the key. */ + remove(key: any): JQueryPromise; + /** Obtains the total count of items that will be returned by the load() function. */ + totalCount(obj?: { + filter?: Object; + select?: Object; + group?: Object; + sort?: Object; + }): JQueryPromise; + /** Updates the data item specified by the key. */ + update(key: any, values: Object): JQueryPromise; + on(eventName: "removing", eventHandler: (key: any) => void): Store; + on(eventName: "removed", eventHandler: (key: any) => void): Store; + on(eventName: "updating", eventHandler: (key: any, values: Object) => void): Store; + on(eventName: "updated", eventHandler: (key: any, values: Object) => void): Store; + on(eventName: "inserting", eventHandler: (values: Object) => void): Store; + on(eventName: "inserted", eventHandler: (values: Object, key: any) => void): Store; + on(eventName: "modifying", eventHandler: () => void): Store; + on(eventName: "modified", eventHandler: () => void): Store; + on(eventName: "loading", eventHandler: (loadOptions: LoadOptions) => void): Store; + on(eventName: "loaded", eventHandler: (result: Array) => void): Store; + on(eventName: string, eventHandler: Function): Store; + on(events: { [eventName: string]: Function; }): Store; + off(eventName: "removing"): Store; + off(eventName: "removed"): Store; + off(eventName: "updating"): Store; + off(eventName: "updated"): Store; + off(eventName: "inserting"): Store; + off(eventName: "inserted"): Store; + off(eventName: "modifying"): Store; + off(eventName: "modified"): Store; + off(eventName: "loading"): Store; + off(eventName: "loaded"): Store; + off(eventName: string): Store; + off(eventName: "removing", eventHandler: (key: any) => void): Store; + off(eventName: "removed", eventHandler: (key: any) => void): Store; + off(eventName: "updating", eventHandler: (key: any, values: Object) => void): Store; + off(eventName: "updated", eventHandler: (key: any, values: Object) => void): Store; + off(eventName: "inserting", eventHandler: (values: Object) => void): Store; + off(eventName: "inserted", eventHandler: (values: Object, key: any) => void): Store; + off(eventName: "modifying", eventHandler: () => void): Store; + off(eventName: "modified", eventHandler: () => void): Store; + off(eventName: "loading", eventHandler: (loadOptions: LoadOptions) => void): Store; + off(eventName: "loaded", eventHandler: (result: Array) => void): Store; + off(eventName: string, eventHandler: Function): Store; + } + export interface ArrayStoreOptions extends StoreOptions { + /** Specifies the array associated with this Store. */ + data?: Array; + } + /** A Store accessing an in-memory array. */ + export class ArrayStore extends Store { + constructor(options?: ArrayStoreOptions); + /** Clears all data associated with the current ArrayStore. */ + clear(): void; + /** Creates the Query object for the underlying array. */ + createQuery(): Query; + } + interface Promise { + then(doneFn?: Function, failFn?: Function, progressFn?: Function): Promise; + } + export interface CustomStoreOptions extends StoreOptions { + /** The user implementation of the byKey(key, extraOptions) method. */ + byKey?: (key: any) => Promise; + /** The user implementation of the insert(values) method. */ + insert?: (values: Object) => Promise; + /** The user implementation of the load(options) method. */ + load?: (options?: LoadOptions) => Promise; + /** The user implementation of the remove(key) method. */ + remove?: (key: any) => Promise; + /** The user implementation of the totalCount(options) method. */ + totalCount?: () => Promise; + /** The user implementation of the update(key, values) method. */ + update?: (key: any, values: Object) => Promise; + } + /** A Store object that enables you to implement your own data access logic. */ + export class CustomStore extends Store { + constructor(options: CustomStoreOptions); + } + export interface DataSourceOptions { + /** Specifies data filtering conditions. */ + filter?: Object; + /** Specifies data grouping conditions. */ + group?: Object; + /** The item mapping function. */ + map?: (record: any) => any; + /** Specifies the maximum number of items the page can contain. */ + pageSize?: number; + /** Specifies whether a DataSource loads data by pages, or all items at once. */ + paginate?: boolean; + /** The data post processing function. */ + postProcess?: (data: any[]) => any[]; + /** Specifies a value by which the required items are searched. */ + searchExpr?: Object; + /** Specifies the comparison operation used to search for the required items. */ + searchOperation?: string; + /** Specifies the value to which the search expression is compared. */ + searchValue?: Object; + /** Specifies the initial select option value. */ + select?: Object; + /** An array of the strings that represent the names of the navigation properties to be loaded simultaneously with the OData store's entity. */ + expand?: Object; + /** Specifies the initial sort option value. */ + sort?: Object; + /** Specifies the underlying Store instance used to access data. */ + store?: any; + /** A handler for the changed event. */ + onChanged?: () => void; + /** A handler for the loadingChanged event. */ + onLoadingChanged?: (isLoading: boolean) => void; + /** A handler for the loadError event. */ + onLoadError?: (e?: Error) => void; + } + /** An object that provides access to a data web service or local data storage for collection container widgets. */ + export class DataSource implements EventsMixin { + constructor(options?: DataSourceOptions); + changed: JQueryCallback; + loadError: JQueryCallback; + loadingChanged: JQueryCallback; + /** Disposes all resources associated with this DataSource. */ + dispose(): void; + /** Returns the current filter option value. */ + filter(): Object; + /** Sets the filter option value. */ + filter(filterExpr: Object): void; + /** Returns the current group option value. */ + group(): Object; + /** Sets the group option value. */ + group(groupExpr: Object): void; + /** Indicates whether or not the current page contains fewer items than the number of items specified by the pageSize configuration option. */ + isLastPage(): boolean; + /** Indicates whether or not at least one load() method execution has successfully finished. */ + isLoaded(): boolean; + /** Indicates whether or not the DataSource is currently being loaded. */ + isLoading(): boolean; + /** Returns the array of items currently operated by the DataSource. */ + items(): Array; + /** Returns the key expression. */ + key(): any; + /** Starts loading data. */ + load(): JQueryPromise>; + /** Returns an object that would be passed to the load() method of the underlying Store according to the current data shaping option values of the current DataSource instance. */ + loadOptions(): Object; + /** Returns the current pageSize option value. */ + pageSize(): number; + /** Sets the pageSize option value. */ + pageSize(value: number): void; + /** Specifies the index of the currently loaded page. */ + pageIndex(): number; + /** Specifies the index of the page to be loaded during the next load() method execution. */ + pageIndex(newIndex: number): void; + /** Returns the current paginate option value. */ + paginate(): boolean; + /** Sets the paginate option value. */ + paginate(value: boolean): void; + /** Returns the searchExpr option value. */ + searchExpr(): Object; + /** Sets the searchExpr option value. */ + searchExpr(expr: Object): void; + /** Returns the currently specified search operation. */ + searchOperation(): string; + /** Sets the current search operation. */ + searchOperation(op: string): void; + /** Returns the searchValue option value. */ + searchValue(): Object; + /** Sets the searchValue option value. */ + searchValue(value: Object): void; + /** Returns the current select option value. */ + select(): Object; + /** Sets the select option value. */ + select(expr: Object): void; + /** Returns the current sort option value. */ + sort(): Object; + /** Sets the sort option value. */ + sort(sortExpr: Object): void; + /** Returns the underlying Store instance. */ + store(): Store; + /** Returns the number of data items available in an underlying Store after the last load() operation without paging. */ + totalCount(): number; + on(eventName: "loadingChanged", eventHandler: (isLoading: boolean) => void): DataSource; + on(eventName: "loadError", eventHandler: (e?: Error) => void): DataSource; + on(eventName: "changed", eventHandler: () => void): DataSource; + on(eventName: string, eventHandler: Function): DataSource; + on(events: { [eventName: string]: Function; }): DataSource; + off(eventName: "loadingChanged"): DataSource; + off(eventName: "loadError"): DataSource; + off(eventName: "changed"): DataSource; + off(eventName: string): DataSource; + off(eventName: "loadingChanged", eventHandler: (isLoading: boolean) => void): DataSource; + off(eventName: "loadError", eventHandler: (e?: Error) => void): DataSource; + off(eventName: "changed", eventHandler: () => void): DataSource; + off(eventName: string, eventHandler: Function): DataSource; + } + /** An object used to work with primitive data types not supported by JavaScript when accessing an OData web service. */ + export class EdmLiteral { + /** Creates an EdmLiteral instance and assigns the specified value to it. */ + constructor(value: string); + /** Returns a string representation of the value associated with this EdmLiteral object. */ + valueOf(): string; + } + /** An object used to generate and hold the GUID. */ + export class Guid { + /** Creates a new Guid instance that holds the specified GUID. */ + constructor(value: string); + /** Creates a new Guid instance holding the generated GUID. */ + constructor(); + /** Returns a string representation of the Guid instance. */ + toString(): string; + /** Returns a string representation of the Guid instance. */ + valueOf(): string; + } + export interface LocalStoreOptions extends ArrayStoreOptions { + /** Specifies the time (in miliseconds) after the change operation, before the data is flushed. */ + flushInterval?: number; + /** Specifies whether the data is flushed immediatelly after each change operation, or after the delay specified via the flushInterval option. */ + immediate?: boolean; + /** The unique identifier used to distinguish the data within the HTML5 Web Storage. */ + name?: string; + } + /** A Store providing access to the HTML5 Web Storage. */ + export class LocalStore extends ArrayStore { + constructor(options?: LocalStoreOptions); + /** Removes all data associated with this Store. */ + clear(): void; + } + export interface ODataContextOptions extends ODataStoreOptions { + /** Specifies the list of entities to be accessed via the ODataContext. */ + entities?: Object; + /** Specifies the function called if the ODataContext causes an error. */ + errorHandler?: (e: Error) => void; + } + /** Provides access to the entire OData service. */ + export class ODataContext { + constructor(options?: ODataContextOptions); + /** Initiates the specified WebGet service operation that returns a value. For the information on service operations, refer to the OData documentation. */ + get(operationName: string, params: Object): JQueryPromise; + /** Initiates the specified WebGet service operation that returns nothing. For the information on service operations, refer to the OData documentation. */ + invoke(operationName: string, params: Object, httpMethod: Object): JQueryPromise; + /** Return a special proxy object to describe the entity link. */ + objectLink(entityAlias: string, key: any): Object; + } + export interface ODataStoreOptions extends StoreOptions { + /** A function used to customize a web request before it is sent. */ + beforeSend?: (request: { + url: string; + method: string; + timeout: number; + params: Object; + payload: Object; + headers: Object; + }) => void; + /** Specifies whether the ODataStore uses the JSONP approach to access non-CORS-compatible remote services. */ + jsonp?: boolean; + /** Specifies the type of the ODataStore key property. The following key types are supported out of the box: String, Int32, Int64, and Guid. */ + keyType?: any; + /** Specifies the URL of the data service being accessed via the current ODataContext. */ + url?: string; + /** Specifies the version of the OData protocol used to interact with the data service. */ + version?: number; + /** Specifies the value of the withCredentials field of the underlying jqXHR object. */ + withCredentials?: boolean; + } + /** A Store providing access to a separate OData web service entity. */ + export class ODataStore extends Store { + constructor(options?: ODataStoreOptions); + /** Creates the Query object for the OData endpoint. */ + createQuery(loadOptions: Object): Object; + /** Returns the data item specified by the key. */ + byKey(key: any, extraOptions?: { expand?: Object }): JQueryPromise; + } + /** An universal chainable data query interface object. */ + export interface Query { + /** Calculates a custom summary for the items in the current Query. */ + aggregate(step: (accumulator: any, value: any) => any): JQueryPromise; + /** Calculates a custom summary for the items in the current Query. */ + aggregate(seed: any, step: (accumulator: any, value: any) => any, finalize: (result: any) => any): JQueryPromise; + /** Calculates the average item value for the current Query. */ + avg(getter: Object): JQueryPromise; + /** Finds the item with the maximum getter value. */ + max(getter: Object): JQueryPromise; + /** Finds the item with the maximum value in the Query. */ + max(): JQueryPromise; + /** Finds the item with the minimum value in the Query. */ + min(): JQueryPromise; + /** Finds the item with the minimum getter value. */ + min(getter: Object): JQueryPromise; + /** Calculates the average item value for the current Query, if each Query item has a numeric type. */ + avg(): JQueryPromise; + /** Returns the total count of items in the current Query. */ + count(): JQueryPromise; + /** Executes the Query. */ + enumerate(): JQueryPromise; + /** Filters the current Query data. */ + filter(criteria: Array): Query; + /** Groups the current Query data. */ + groupBy(getter: Object): Query; + /** Applies the specified transformation to each item. */ + select(getter: Object): Query; + /** Limits the data item count. */ + slice(skip: number, take?: number): Query; + /** Sorts current Query data. */ + sortBy(getter: Object, desc: boolean): Query; + /** Sorts current Query data. */ + sortBy(getter: Object): Query; + /** Calculates the sum of item getter values in the current Query. */ + sum(getter: Object): JQueryPromise; + /** Calculates the sum of item values in the current Query. */ + sum(): JQueryPromise; + /** Adds one more sorting condition to the current Query. */ + thenBy(getter: Object): Query; + /** Adds one more sorting condition to the current Query. */ + thenBy(getter: Object, desc: boolean): Query; + /** Returns the array of current Query items. */ + toArray(): Array; + } + /** The global data layer error handler. */ + export var errorHandler: (e: Error) => void; + /** Encodes the specified string or array of bytes to base64 encoding. */ + export function base64_encode(input: any): string; + /** Creates a Query instance. */ + export function query(array: Array): Query; + /** Creates a Query instance for accessing the remote service specified by a URL. */ + export function query(url: string, queryOptions: Object): Query; + /** This section describes the utility objects provided by the DevExtreme data layer. */ + export var utils: { + /** Compiles a getter function from the getter expression. */ + compileGetter(expr: any): Function; + /** Compiles a setter function from the setter expression. */ + compileSetter(expr: any): Function; + odata: { + /** Holds key value converters for OData. */ + keyConverters: { + String(value: any): string; + Int32(value: any): number; + Int64(value: any): EdmLiteral; + Guid(value: any): Guid; + Boolean(value: any): boolean; + Single(value: any): EdmLiteral; + Decimal(value: any): EdmLiteral; + }; + } + } + } + /** An object that serves as a namespace for DevExtreme UI widgets as well as for methods implementing UI logic in DevExtreme sites/applications. */ + export module ui { + export interface WidgetOptions extends DOMComponentOptions { + /** A Boolean value specifying whether or not the widget changes its state when interacting with a user. */ + activeStateEnabled?: boolean; + /** A Boolean value specifying whether or not the widget can respond to user interaction. */ + disabled?: boolean; + /** A Boolean value specifying whether or not the widget changes its state when being hovered by an end user. */ + hoverStateEnabled?: boolean; + /** Specifies whether or not the widget can be focused. */ + focusStateEnabled?: boolean; + /** Specifies a shortcut key that sets focus on the widget element. */ + accessKey?: string; + /** A Boolean value specifying whether or not the widget is visible. */ + visible?: boolean; + /** Specifies the widget tab index. */ + tabIndex?: number; + /** Specifies the text of the hint displayed for the widget. */ + hint?: string; + } + /** The base class for widgets. */ + export class Widget extends DOMComponent { + constructor(options?: WidgetOptions); + /** Redraws the widget. */ + repaint(): void; + /** Sets focus on the widget. */ + focus(): void; + /** Registers a handler for pressing of the specified key. */ + registerKeyHandler(key: string, handler: Function): void; + } + export interface CollectionWidgetOptions extends WidgetOptions { + /** A data source used to fetch data to be displayed by the widget. */ + dataSource?: any; + itemClickAction?: any; + itemHoldAction?: Function; + /** The time period in milliseconds before the onItemHold event is raised. */ + itemHoldTimeout?: number; + itemRender?: any; + itemRenderedAction?: Function; + /** An array of items displayed by the widget. */ + items?: Array; + /** + * A function performed when a widget item is selected. + * @deprecated onSelectionChanged.md + */ + itemSelectAction?: Function; + /** The template to be used for rendering items. */ + itemTemplate?: any; + loopItemFocus?: boolean; + /** The text or HTML markup displayed by the widget if the item collection is empty. */ + noDataText?: string; + onContentReady?: any; + contentReadyAction?: any; + /** A handler for the itemClick event. */ + onItemClick?: any; + /** A handler for the itemContextMenu event. */ + onItemContextMenu?: Function; + /** A handler for the itemHold event. */ + onItemHold?: Function; + /** A handler for the itemRendered event. */ + onItemRendered?: Function; + /** A handler for the selectionChanged event. */ + onSelectionChanged?: Function; + /** The index of the currently selected widget item. */ + selectedIndex?: number; + /** The selected item object. */ + selectedItem?: Object; + /** An array of currently selected item objects. */ + selectedItems?: Array; + /** A handler for the itemDeleting event. */ + onItemDeleting?: Function; + /** A handler for the itemDeleted event. */ + onItemDeleted?: Function; + /** A handler for the itemReordered event. */ + onItemReordered?: Function; + } + /** The base class for widgets containing an item collection. */ + export class CollectionWidget extends Widget { + constructor(element: JQuery, options?: CollectionWidgetOptions); + constructor(element: HTMLElement, options?: CollectionWidgetOptions); + selectItem(itemElement: any): void; + unselectItem(itemElement: any): void; + deleteItem(itemElement: any): JQueryPromise; + isItemSelected(itemElement: any): boolean; + reorderItem(itemElement: any, toItemElement: any): JQueryPromise; + } + export interface DataExpressionMixinOptions { + /** A data source used to fetch data to be displayed by the widget. */ + dataSource?: any; + /** Specifies the name of the data source item field whose value is displayed by the widget. */ + displayExpr?: any; + /** Specifies the name of a data source item field whose value is held in the value configuration option. */ + valueExpr?: any; + itemRender?: any; + /** An array of items displayed by the widget. */ + items?: Array; + /** The template to be used for rendering items. */ + itemTemplate?: any; + /** The currently selected value in the widget. */ + value?: Object; + } + export interface EditorOptions extends WidgetOptions { + /** The currently specified value. */ + value?: Object; + /** A handler for the valueChanged event. */ + onValueChanged?: Function; + valueChangeAction?: Function; + /** A Boolean value specifying whether or not the widget is read-only. */ + readOnly?: boolean; + /** Holds the object that defines the error that occurred during validation. */ + validationError?: Object; + /** Specifies whether the editor's value is valid. */ + isValid?: boolean; + /** Specifies how the message about the validation rules that are not satisfied by this editor's value is displayed. */ + validationMessageMode?: string; + } + /** A base class for editors. */ + export class Editor extends Widget { + /** Resets the editor's value to undefined. */ + reset(): void; + } + /** An object that serves as a namespace for methods displaying a message in an application/site. */ + export var dialog: { + /** Creates an alert dialog message containing a single "OK" button. */ + alert(message: string, title: string): JQueryPromise; + /** Creates a confirm dialog that contains "Yes" and "No" buttons. */ + confirm(message: string, title: string): JQueryPromise; + /** Creates a custom dialog using the options specified by the passed configuration object. */ + custom(options: { title?: string; message?: string; buttons?: Array; }): { + show(): JQueryPromise; + hide(): void; + hide(value: any): void; + }; + }; + /** Creates a toast message. */ + export function notify(message: any, type: string, displayTime: number): void; + /** Creates a toast message. */ + export function notify(options: Object): void; + /** An object that serves as a namespace for the methods that work with DevExtreme CSS Themes. */ + export var themes: { + /** Returns the name of the currently applied theme. */ + current(): string; + /** Changes the current theme to the specified one. */ + current(themeName: string): void; + }; + /** Sets a specified template engine. */ + export function setTemplateEngine(name: string): void; + /** Sets a custom template engine defined via custom compile and render functions. */ + export function setTemplateEngine(options: Object): void; + /** An object that serves as a namespace for utility methods that can be helpful when working with the DevExtreme framework and UI widgets. */ + export var utils: { + /** Sets parameters for the viewport meta tag. */ + initMobileViewport(options: { allowZoom?: boolean; allowPan?: boolean; allowSelection?: boolean }): void; + }; + } +} +declare module DevExpress.ui { + export interface dxValidatorOptions extends DOMComponentOptions { + /** An array of validation rules to be checked for the editor with which the dxValidator object is associated. */ + validationRules?: Array; + /** Specifies the editor name to be used in the validation default messages. */ + name?: string; + /** An object that specifies what and when to validate and how to apply the validation result. */ + adapter?: Object; + /** Specifies the validation group the editor will be related to. */ + validationGroup?: string; + /** A handler for the validated event. */ + onValidated?: (params: validationEngine.ValidatorValidationResult) => void; + } + /** A widget that is used to validate the associated DevExtreme editors against the defined validation rules. */ + export class dxValidator extends DOMComponent implements validationEngine.IValidator { + constructor(element: JQuery, options?: dxValidatorOptions); + constructor(element: Element, options?: dxValidatorOptions); + /** Validates the value of the editor that is controlled by the current dxValidator object against the list of the specified validation rules. */ + validate(): validationEngine.ValidatorValidationResult; + /** Resets the value and validation result of the editor associated with the current dxValidator object. */ + reset(): void; + } + /** The widget that is used in the Knockout and Angular approaches to combine the editors to be validated. */ + export class dxValidationGroup extends DOMComponent { + constructor(element: JQuery); + constructor(element: Element); + /** Validates rules of the validators that belong to the current validation group. */ + validate(): validationEngine.ValidationGroupValidationResult; + /** Resets the value and validation result of the editors that are included to the current validation group. */ + reset(): void; + } + export interface dxValidationSummaryOptions extends CollectionWidgetOptions { + /** Specifies the validation group for which summary should be generated. */ + validationGroup?: string; + } + /** A widget for displaying the result of checking validation rules for editors. */ + export class dxValidationSummary extends CollectionWidget { + constructor(element: JQuery, options?: dxValidationSummaryOptions); + constructor(element: Element, options?: dxValidationSummaryOptions); + } + export interface dxResizableOptions extends DOMComponentOptions { + /** Specifies which borders of the widget element are used as a handle. */ + handles?: string; + /** Specifies the lower width boundary for resizing. */ + minWidth?: number; + /** Specifies the upper width boundary for resizing. */ + maxWidth?: number; + /** Specifies the lower height boundary for resizing. */ + minHeight?: number; + /** Specifies the upper height boundary for resizing. */ + maxHeight?: number; + /** A handler for the resizeStart event. */ + onResizeStart?: Function; + /** A handler for the resize event. */ + onResize?: Function; + /** A handler for the resizeEnd event. */ + onResizeEnd?: Function; + } + /** A widget that displays required content in a resizable element. */ + export class dxResizable extends DOMComponent { + constructor(element: JQuery, options?: dxResizableOptions); + constructor(element: Element, options?: dxResizableOptions); + } + export interface dxTooltipOptions extends dxPopoverOptions { + } + /** A tooltip widget. */ + export class dxTooltip extends dxPopover { + constructor(element: JQuery, options?: dxTooltipOptions); + constructor(element: Element, options?: dxTooltipOptions); + } + export interface dxDropDownListOptions extends dxDropDownEditorOptions { + /** Returns the value currently displayed by the widget. */ + displayValue?: string; + /** The minimum number of characters that must be entered into the text box to begin a search. */ + minSearchLength?: number; + /** Specifies the name of a data source item field or an expression whose value is compared to the search criterion. */ + searchExpr?: Object; + /** Specifies the binary operation used to filter data. */ + searchMode?: string; + /** Specifies the time delay, in milliseconds, after the last character has been typed in, before a search is executed. */ + searchTimeout?: number; + /** A handler for the valueChanged event. */ + onValueChanged?: Function; + /** Specifies DOM event names that update a widget's value. */ + valueChangeEvent?: string; + /** Specifies whether or not the widget supports searching. */ + searchEnabled?: boolean; + /** + * Specifies whether or not the widget displays items by pages. + * @deprecated dataSource.paginate.md + */ + pagingEnabled?: boolean; + /** The text or HTML markup displayed by the widget if the item collection is empty. */ + noDataText?: string; + /** A handler for the selectionChanged event. */ + onSelectionChanged?: Function; + /** A handler for the itemClick event. */ + onItemClick?: Function; + onContentReady?: Function; + } + /** A base class for drop-down list widgets. */ + export class dxDropDownList extends dxDropDownEditor { + constructor(element: JQuery, options?: dxDropDownListOptions); + constructor(element: Element, options?: dxDropDownListOptions); + } + export interface dxToolbarOptions extends CollectionWidgetOptions { + menuItemRender?: any; + /** The template used to render menu items. */ + menuItemTemplate?: any; + /** Informs the widget about its location in a view HTML markup. */ + renderAs?: string; + } + /** A toolbar widget. */ + export class dxToolbar extends CollectionWidget { + constructor(element: JQuery, options?: dxToolbarOptions); + constructor(element: Element, options?: dxToolbarOptions); + } + export interface dxToastOptions extends dxOverlayOptions { + animation?: fx.AnimationOptions; + /** The time span in milliseconds during which the dxToast widget is visible. */ + displayTime?: number; + height?: any; + /** The dxToast message text. */ + message?: string; + position?: PositionOptions; + shading?: boolean; + /** Specifies the dxToast widget type. */ + type?: string; + width?: any; + closeOnBackButton?: boolean; + } + /** The toast message widget. */ + export class dxToast extends dxOverlay { + constructor(element: JQuery, options?: dxToastOptions); + constructor(element: Element, options?: dxToastOptions); + } + export interface dxTextEditorOptions extends EditorOptions { + /** A handler for the change event. */ + onChange?: Function; + changeAction?: Function; + /** A handler for the copy event. */ + onCopy?: Function; + copyAction?: Function; + /** A handler for the cut event. */ + onCut?: Function; + cutAction?: Function; + /** A handler for the enterKey event. */ + onEnterKey?: Function; + enterKeyAction?: Function; + /** A handler for the focusIn event. */ + onFocusIn?: Function; + focusInAction?: Function; + /** A handler for the focusOut event. */ + onFocusOut?: Function; + focusOutAction?: Function; + /** A handler for the input event. */ + onInput?: Function; + inputAction?: Function; + /** A handler for the keyDown event. */ + onKeyDown?: Function; + keyDownAction?: Function; + /** A handler for the keyPress event. */ + onKeyPress?: Function; + keyPressAction?: Function; + /** A handler for the keyUp event. */ + onKeyUp?: Function; + keyUpAction?: Function; + /** A handler for the paste event. */ + onPaste?: Function; + pasteAction?: Function; + /** The text displayed by the widget when the widget value is empty. */ + placeholder?: string; + /** Specifies whether to display the Clear button in the widget. */ + showClearButton?: boolean; + /** Specifies the current value displayed by the widget. */ + value?: any; + /** Specifies DOM event names that update a widget's value. */ + valueChangeEvent?: string; + /** Specifies whether or not the widget checks the inner text for spelling mistakes. */ + spellcheck?: boolean; + /** Specifies HTML attributes applied to the inner input element of the widget. */ + attr?: Object; + /** The read-only option that holds the text displayed by the widget input element. */ + text?: string; + /** Specifies whether or not the widget supports the focused state and keyboard navigation. */ + focusStateEnabled?: boolean; + /** A Boolean value specifying whether or not the widget changes its state when being hovered by an end user. */ + hoverStateEnabled?: boolean; + /** The editor mask, which specifies the format of the entered string. */ + mask?: string; + /** Specifies a mask placeholder character. */ + maskChar?: string; + /** Specifies custom mask rules. */ + maskRules?: Object; + /** A message displayed when the entered text does not match the specified pattern. */ + maskInvalidMessage?: string; + } + /** A base class for text editing widgets. */ + export class dxTextEditor extends Editor { + constructor(element: JQuery, options?: dxTextEditorOptions); + constructor(element: Element, options?: dxTextEditorOptions); + /** Removes focus from the input element. */ + blur(): void; + /** Sets focus to the input element representing the widget. */ + focus(): void; + } + export interface dxTextBoxOptions extends dxTextEditorOptions { + /** Specifies the maximum number of characters you can enter into the textbox. */ + maxLength?: any; + /** The "mode" attribute value of the actual HTML input element representing the text box. */ + mode?: string; + } + /** A single-line text box widget. */ + export class dxTextBox extends dxTextEditor { + constructor(element: JQuery, options?: dxTextBoxOptions); + constructor(element: Element, options?: dxTextBoxOptions); + } + export interface dxTextAreaOptions extends dxTextBoxOptions { + /** Specifies whether or not the widget checks the inner text for spelling mistakes. */ + spellcheck?: boolean; + } + /** A widget used to display and edit multi-line text. */ + export class dxTextArea extends dxTextBox { + constructor(element: JQuery, options?: dxTextAreaOptions); + constructor(element: Element, options?: dxTextAreaOptions); + } + export interface dxTabsOptions extends CollectionWidgetOptions { + /** Specifies whether the widget enables an end-user to select only a single item or multiple items. */ + selectionMode?: string; + /** Specifies whether or not an end-user can scroll tabs by swiping. */ + scrollByContent?: boolean; + /** Specifies whether or not an end-user can scroll tabs. */ + scrollingEnabled?: boolean; + /** A Boolean value that specifies the availability of navigation buttons. */ + showNavButtons?: boolean; + } + /** A tab strip used to switch between pages. */ + export class dxTabs extends CollectionWidget { + constructor(element: JQuery, options?: dxTabsOptions); + constructor(element: Element, options?: dxTabsOptions); + } + export interface dxTabPanelOptions extends dxMultiViewOptions { + /** A handler for the titleClick event. */ + onTitleClick?: any; + /** A handler for the titleHold event. */ + onTitleHold?: Function; + /** A handler for the titleRendered event. */ + onTitleRendered?: Function; + titleTemplate?: any; + /** The template to be used for rendering an item title. */ + itemTitleTemplate?: any; + } + /** A widget used to display a view and to switch between several views by clicking the appropriate tabs. */ + export class dxTabPanel extends dxMultiView { + constructor(element: JQuery, options?: dxTabPanelOptions); + constructor(element: Element, options?: dxTabPanelOptions); + } + export interface dxSelectBoxOptions extends dxDropDownListOptions { + /** The template to be used for rendering the widget text field. */ + fieldTemplate?: any; + /** The text that is provided as a hint in the select box editor. */ + placeholder?: string; + /** Specifies whether or not the widget allows an end-user to enter a custom value. */ + fieldEditEnabled?: boolean; + } + /** A widget that allows you to select an item in a dropdown list. */ + export class dxSelectBox extends dxDropDownList { + constructor(element: JQuery, options?: dxSelectBoxOptions); + constructor(element: Element, options?: dxSelectBoxOptions); + } + export interface dxTagBoxOptions extends dxSelectBoxOptions { + /** Holds the list of selected values. */ + values?: Array; + } + /** A widget that allows you to select multiple items from a dropdown list. */ + export class dxTagBox extends dxSelectBox { + constructor(element: JQuery, options?: dxTagBoxOptions); + constructor(element: Element, options?: dxTagBoxOptions); + } + export interface dxScrollViewOptions extends dxScrollableOptions { + /** A handler for the pullDown event. */ + onPullDown?: Function; + pullDownAction?: Function; + /** Specifies the text shown in the pullDown panel when pulling the content down lowers the refresh threshold. */ + pulledDownText?: string; + /** Specifies the text shown in the pullDown panel while pulling the content down to the refresh threshold. */ + pullingDownText?: string; + /** A handler for the reachBottom event. */ + onReachBottom?: Function; + reachBottomAction?: Function; + /** Specifies the text shown in the pullDown panel displayed when content is scrolled to the bottom. */ + reachBottomText?: string; + /** Specifies the text shown in the pullDown panel displayed when the content is being refreshed. */ + refreshingText?: string; + /** Returns a value indicating if the scrollView content is larger then the widget container. */ + isFull(): boolean; + /** Locks the widget until the release(preventScrollBottom) method is called and executes the function passed to the onPullDown option and the handler assigned to the pullDown event. */ + refresh(): void; + /** Notifies the scroll view that data loading is finished. */ + release(preventScrollBottom: boolean): JQueryPromise; + /** Toggles the loading state of the widget. */ + toggleLoading(showOrHide: boolean): void; + } + /** A widget used to display scrollable content. */ + export class dxScrollView extends dxScrollable { + constructor(element: JQuery, options?: dxScrollViewOptions); + constructor(element: Element, options?: dxScrollViewOptions); + } + export interface dxScrollableLocation { + top?: number; + left?: number; + } + export interface dxScrollableOptions extends DOMComponentOptions { + /** A string value specifying the available scrolling directions. */ + direction?: string; + /** A Boolean value specifying whether or not the widget can respond to user interaction. */ + disabled?: boolean; + /** A handler for the scroll event. */ + onScroll?: Function; + scrollAction?: Function; + /** Specifies when the widget shows the scrollbar. */ + showScrollbar?: string; + /** A handler for the update event. */ + onUpdated?: Function; + updateAction?: Function; + /** Indicates whether to use native or simulated scrolling. */ + useNative?: boolean; + /** A Boolean value specifying whether to enable or disable the bounce-back effect. */ + bounceEnabled?: boolean; + /** A Boolean value specifying whether or not an end-user can scroll the widget content swiping it up or down. */ + scrollByContent?: boolean; + /** A Boolean value specifying whether or not an end-user can scroll the widget content using the scrollbar. */ + scrollByThumb?: boolean; + } + /** A widget used to display scrollable content. */ + export class dxScrollable extends DOMComponent { + constructor(element: JQuery, options?: dxScrollableOptions); + constructor(element: Element, options?: dxScrollableOptions); + /** Returns the height of the scrollable widget in pixels. */ + clientHeight(): number; + /** Returns the width of the scrollable widget in pixels. */ + clientWidth(): number; + /** Returns an HTML element of the widget. */ + content(): JQuery; + /** Scrolls the widget content by the specified number of pixels. */ + scrollBy(distance: number): void; + /** Scrolls widget content by the specified number of pixels in horizontal and vertical directions. */ + scrollBy(distanceObject: dxScrollableLocation): void; + /** Returns the height of the scrollable content in pixels. */ + scrollHeight(): number; + /** Returns the current scroll position against the leftmost position. */ + scrollLeft(): number; + /** Returns how far the scrollable content is scrolled from the top and from the left. */ + scrollOffset(): dxScrollableLocation; + /** Scrolls widget content to the specified position. */ + scrollTo(targetLocation: number): void; + /** Scrolls widget content to a specified position. */ + scrollTo(targetLocation: dxScrollableLocation): void; + /** Scrolls widget content to the specified element. */ + scrollToElement(element: Element): void; + /** Returns the current scroll position against the topmost position. */ + scrollTop(): number; + /** Returns the width of the scrollable content in pixels. */ + scrollWidth(): number; + /** Updates the dimensions of the scrollable contents. */ + update(): void; + } + export interface dxRadioGroupOptions extends CollectionWidgetOptions { + /** Specifies the radio group layout. */ + layout?: string; + } + /** A widget that enables a user to select one item within a list of items represented by radio buttons. */ + export class dxRadioGroup extends CollectionWidget { + constructor(element: JQuery, options?: dxRadioGroupOptions); + constructor(element: Element, options?: dxRadioGroupOptions); + } + export interface dxPopupOptions extends dxOverlayOptions { + animation?: fx.AnimationOptions; + /** Specifies whether or not to allow a user to drag the popup window. */ + dragEnabled?: boolean; + /** A Boolean value specifying whether or not to display the widget in full-screen mode. */ + fullScreen?: boolean; + position?: PositionOptions; + /** A Boolean value specifying whether or not to display the title in the popup window. */ + showTitle?: boolean; + /** The title in the overlay window. */ + title?: string; + /** A template to be used for rendering the widget title. */ + titleTemplate?: any; + width?: any; + /** Specifies items displayed on the top or bottom toolbar of the popup window. */ + buttons?: Array; + /** Specifies whether or not the widget displays the Close button. */ + showCloseButton?: boolean; + /** A handler for the titleRendered event. */ + onTitleRendered?: Function; + } + /** A widget that displays required content in a popup window. */ + export class dxPopup extends dxOverlay { + constructor(element: JQuery, options?: dxPopupOptions); + constructor(element: Element, options?: dxPopupOptions); + } + export interface dxPopoverOptions extends dxPopupOptions { + /** An object defining animation options of the widget. */ + animation?: fx.AnimationOptions; + /** Specifies the height of the widget. */ + height?: any; + /** An object defining widget positioning options. */ + position?: PositionOptions; + shading?: boolean; + /** A Boolean value specifying whether or not to display the title in the overlay window. */ + showTitle?: boolean; + /** The target element associated with a popover. */ + target?: any; + /** Specifies the width of the widget. */ + width?: any; + } + /** A widget that displays the required content in a popup window. */ + export class dxPopover extends dxPopup { + constructor(element: JQuery, options?: dxPopoverOptions); + constructor(element: Element, options?: dxPopoverOptions); + /** Displays the widget for the specified target element. */ + show(target?: any): JQueryPromise; + } + export interface dxOverlayOptions extends WidgetOptions { + /** An object that defines the animation options of the widget. */ + animation?: fx.AnimationOptions; + /** A Boolean value specifying whether or not the widget is closed if a user presses the Back hardware button. */ + closeOnBackButton?: boolean; + /** A Boolean value specifying whether or not the widget is closed if a user clicks outside of the overlapping window. */ + closeOnOutsideClick?: any; + /** A template to be used for rendering widget content. */ + contentTemplate?: any; + /** Specifies whether widget content is rendered when the widget is shown or when rendering the widget. */ + deferRendering?: boolean; + /** Specifies whether or not an end-user can drag the widget. */ + dragEnabled?: boolean; + /** Specifies whether or not an end user can resize the widget. */ + resizeEnabled?: boolean; + /** The height of the widget in pixels. */ + height?: any; + /** A handler for the hidden event. */ + onHidden?: Function; + hiddenAction?: Function; + /** A handler for the hiding event. */ + onHiding?: Function; + hidingAction?: Function; + /** An object defining widget positioning options. */ + position?: PositionOptions; + /** A Boolean value specifying whether or not the main screen is inactive while the widget is active. */ + shading?: boolean; + /** Specifies the shading color. */ + shadingColor?: string; + /** A handler for the showing event. */ + onShowing?: Function; + showingAction?: Function; + /** A handler for the shown event. */ + onShown?: Function; + shownAction?: Function; + /** A Boolean value specifying whether or not the widget is visible. */ + visible?: boolean; + /** The widget width in pixels. */ + width?: any; + } + /** A widget displaying the required content in an overlay window. */ + export class dxOverlay extends Widget { + constructor(element: JQuery, options?: dxOverlayOptions); + constructor(element: Element, options?: dxOverlayOptions); + /** An HTML element of the widget. */ + content(): JQuery; + /** Hides the widget. */ + hide(): JQueryPromise; + /** Recalculates the overlay's size and position. */ + repaint(): void; + /** Shows the widget. */ + show(): JQueryPromise; + /** Toggles the visibility of the widget. */ + toggle(showing: boolean): JQueryPromise; + /** A static method that specifies the base z-index for all overlay widgets. */ + static baseZIndex(zIndex: number): void; + } + export interface dxNumberBoxOptions extends dxTextEditorOptions { + /** The maximum value accepted by the number box. */ + max?: number; + /** The minimum value accepted by the number box. */ + min?: number; + /** Specifies whether or not to show spin buttons. */ + showSpinButtons?: boolean; + useTouchSpinButtons?: boolean; + /** Specifies by which value the widget value changes when a spin button is clicked. */ + step?: number; + /** The current number box value. */ + value?: number; + } + /** A textbox widget that enables a user to enter numeric values. */ + export class dxNumberBox extends dxTextEditor { + constructor(element: JQuery, options?: dxNumberBoxOptions); + constructor(element: Element, options?: dxNumberBoxOptions); + } + export interface dxNavBarOptions extends dxTabsOptions { + scrollingEnabled?: boolean; + } + /** A widget that contains items used to navigate through application views. */ + export class dxNavBar extends dxTabs { + constructor(element: JQuery, options?: dxNavBarOptions); + constructor(element: Element, options?: dxNavBarOptions); + } + export interface dxMultiViewOptions extends CollectionWidgetOptions { + /** Specifies whether or not to animate the displayed item change. */ + animationEnabled?: boolean; + /** A Boolean value specifying whether or not to scroll back to the first item after the last item is swiped. */ + loop?: boolean; + /** The index of the currently displayed item. */ + selectedIndex?: number; + /** A Boolean value specifying whether or not to allow users to change the selected index by swiping. */ + swipeEnabled?: boolean; + } + /** A widget used to display a view and to switch between several views. */ + export class dxMultiView extends CollectionWidget { + constructor(element: JQuery, options?: dxMultiViewOptions); + constructor(element: Element, options?: dxMultiViewOptions); + } + export interface dxMapOptions extends WidgetOptions { + /** Specifies whether or not the widget automatically adjusts center and zoom option values when adding a new marker or route. */ + autoAdjust?: boolean; + bounds?: { + northEast?: { + lat?: number; + lng?: number; + }; + southWest?: { + lat?: number; + lng?: number; + }; + /** An object, a string, or an array specifying the location displayed at the center of the widget. */ + center?: { + /** The latitude location displayed in the center of the widget. */ + lat?: number; + /** The longitude location displayed in the center of the widget. */ + lng?: number; + }; + /** A handler for the click event. */ + onClick?: any; + clickAction?: any; + /** Specifies whether or not map widget controls are available. */ + controls?: boolean; + /** Specifies the height of the widget. */ + height?: number; + /** A key used to authenticate the application within the required map provider. */ + key?: { + /** A key used to authenticate the application within the "Bing" map provider. */ + bing?: string; + /** A key used to authenticate the application within the "Google" map provider. */ + google?: string; + /** A key used to authenticate the application within the "Google Static" map provider. */ + googleStatic?: string; + } + /** A handler for the markerAdded event. */ + onMarkerAdded?: Function; + markerAddedAction?: Function; + /** A URL pointing to the custom icon to be used for map markers. */ + markerIconSrc?: string; + /** A handler for the markerRemoved event. */ + onMarkerRemoved?: Function; + markerRemovedAction?: Function; + /** An array of markers displayed on a map. */ + markers?: Array; + /** The name of the current map data provider. */ + provider?: string; + /** A handler for the ready event. */ + onReady?: Function; + readyAction?: Function; + /** A handler for the routeAdded event. */ + onRouteAdded?: Function; + routeAddedAction?: Function; + /** A handler for the routeRemoved event. */ + onRouteRemoved?: Function; + routeRemovedAction?: Function; + /** An array of routes shown on the map. */ + routes?: Array; + /** The type of a map to display. */ + type?: string; + /** Specifies the width of the widget. */ + width?: number; + /** The zoom level of the map. */ + zoom?: number; + /** Adds a marker to the map. */ + addMarker(markerOptions: Object): JQueryPromise; + /** Adds a route to the map. */ + addRoute(options: Object): JQueryPromise; + /** Removes a marker from the map. */ + removeMarker(marker: Object): JQueryPromise; + /** Removes a route from the map. */ + removeRoute(route: any): JQueryPromise; + }; + } + /** An interactive map widget. */ + export class dxMap extends Widget { + constructor(element: JQuery, options?: dxMapOptions); + constructor(element: Element, options?: dxMapOptions); + } + export interface dxLookupOptions extends dxDropDownListOptions { + /** An object defining widget animation options. */ + animation?: fx.AnimationOptions; + /** The text displayed on the Cancel button. */ + cancelButtonText?: string; + /** The text displayed on the Clear button. */ + clearButtonText?: string; + /** Specifies whether or not the widget cleans the search box when the popup window is displayed. */ + cleanSearchOnOpening?: boolean; + /** A Boolean value specifying whether or not the widget is closed if a user clicks outside of the overlaying window. */ + closeOnOutsideClick?: any; + /** The text displayed on the Apply button. */ + applyButtonText?: string; + /** A Boolean value specifying whether or not to display the lookup in full-screen mode. */ + fullScreen?: boolean; + focusStateEnabled?: boolean; + /** A Boolean value specifying whether or not to group widget items. */ + grouped?: boolean; + groupRender?: any; + /** The name of the template used to display a group header. */ + groupTemplate?: any; + /** The text displayed on the button used to load the next page from the data source. */ + nextButtonText?: string; + /** A handler for the pageLoading event. */ + onPageLoading?: Function; + /** Specifies whether the next page is loaded when a user scrolls the widget to the bottom or when the "next" button is clicked. */ + pageLoadMode?: string; + pageLoadingAction?: Function; + /** Specifies the text shown in the pullDown panel, which is displayed when the widget is scrolled to the bottom. */ + pageLoadingText?: string; + /** The text displayed by the widget when nothing is selected. */ + placeholder?: string; + /** The height of the widget popup element. */ + popupHeight?: any; + /** The width of the widget popup element. */ + popupWidth?: any; + /** An object defining widget positioning options. */ + position?: PositionOptions; + /** Specifies the text displayed in the pullDown panel when the widget is pulled below the refresh threshold. */ + pulledDownText?: string; + /** Specifies the text shown in the pullDown panel while the list is being pulled down to the refresh threshold. */ + pullingDownText?: string; + /** A handler for the pullRefresh event. */ + onPullRefresh?: Function; + pullRefreshAction?: Function; + /** A Boolean value specifying whether or not the widget supports the "pull down to refresh" gesture. */ + pullRefreshEnabled?: boolean; + /** Specifies the text displayed in the pullDown panel while the widget is being refreshed. */ + refreshingText?: string; + /** A handler for the scroll event. */ + onScroll?: Function; + scrollAction?: Function; + /** A Boolean value specifying whether or not the search bar is visible. */ + searchEnabled?: boolean; + /** The text that is provided as a hint in the lookup's search bar. */ + searchPlaceholder?: string; + /** A Boolean value specifying whether or not the main screen is inactive while the lookup is active. */ + shading?: boolean; + /** Specifies whether to display the Cancel button in the lookup window. */ + showCancelButton?: boolean; + /** + * A Boolean value specifying whether the widget loads the next page automatically when you reach the bottom of the list or when a button is clicked. + * @deprecated pageLoadMode.md + */ + showNextButton?: boolean; + /** The title of the lookup window. */ + title?: string; + /** A template to be used for rendering the widget title. */ + titleTemplate?: any; + /** Specifies whether or not the widget uses native scrolling. */ + useNativeScrolling?: boolean; + /** Specifies whether or not to show lookup contents in a dxPopover widget. */ + usePopover?: boolean; + /** A handler for the valueChanged event. */ + onValueChanged?: Function; + contentReadyAction?: Function; + titleRender?: any; + /** A handler for the titleRendered event. */ + onTitleRendered?: Function; + /** A Boolean value specifying whether or not to display the title in the popup window. */ + showPopupTitle?: boolean; + } + /** A widget that allows a user to select predefined values from a lookup window. */ + export class dxLookup extends dxDropDownList { + constructor(element: JQuery, options?: dxLookupOptions); + constructor(element: Element, options?: dxLookupOptions); + /** This section lists the data source fields that are used in a default template for lookup drop-down items. */ + } + export interface dxLoadPanelOptions extends dxOverlayOptions { + /** An object defining the animation options of the widget. */ + animation?: fx.AnimationOptions; + /** The delay in milliseconds after which the load panel is displayed. */ + delay?: number; + /** The height of the widget. */ + height?: number; + /** A URL pointing to an image to be used as a load indicator. */ + indicatorSrc?: string; + /** The text displayed in the load panel. */ + message?: string; + /** A Boolean value specifying whether or not to show a load indicator. */ + showIndicator?: boolean; + /** A Boolean value specifying whether or not to show the pane behind the load indicator. */ + showPane?: boolean; + /** The width of the widget. */ + width?: number; + } + /** A widget used to indicate whether or not an element is loading. */ + export class dxLoadPanel extends dxOverlay { + constructor(element: JQuery, options?: dxLoadPanelOptions); + constructor(element: Element, options?: dxLoadPanelOptions); + } + export interface dxLoadIndicatorOptions extends WidgetOptions { + /** Specifies the path to an image used as the indicator. */ + indicatorSrc?: string; + } + /** The widget used to indicate the loading process. */ + export class dxLoadIndicator extends Widget { + constructor(element: JQuery, options?: dxLoadIndicatorOptions); + constructor(element: Element, options?: dxLoadIndicatorOptions); + } + export interface dxListOptions extends CollectionWidgetOptions { + /** A Boolean value specifying whether or not to display a grouped list. */ + grouped?: boolean; + groupRender?: any; + /** The template to be used for rendering item groups. */ + groupTemplate?: any; + onItemDeleting?: Function; + /** A handler for the itemDeleted event. */ + onItemDeleted?: Function; + /** A handler for the groupRendered event. */ + onGroupRendered?: Function; + itemDeleteAction?: Function; + /** A handler for the itemReordered event. */ + onItemReordered?: Function; + itemReorderAction?: Function; + /** A handler for the itemClick event. */ + onItemClick?: any; + /** A handler for the itemSwipe event. */ + onItemSwipe?: Function; + itemSwipeAction?: Function; + /** The text displayed on the button used to load the next page from the data source. */ + nextButtonText?: string; + /** A handler for the pageLoading event. */ + onPageLoading?: Function; + pageLoadingAction?: Function; + /** Specifies the text shown in the pullDown panel, which is displayed when the list is scrolled to the bottom. */ + pageLoadingText?: string; + /** Specifies the text displayed in the pullDown panel when the list is pulled below the refresh threshold. */ + pulledDownText?: string; + /** Specifies the text shown in the pullDown panel while the list is being pulled down to the refresh threshold. */ + pullingDownText?: string; + /** A handler for the pullRefresh event. */ + onPullRefresh?: Function; + pullRefreshAction?: Function; + /** A Boolean value specifying whether or not the widget supports the "pull down to refresh" gesture. */ + pullRefreshEnabled?: boolean; + /** Specifies the text displayed in the pullDown panel while the list is being refreshed. */ + refreshingText?: string; + /** A handler for the scroll event. */ + onScroll?: Function; + scrollAction?: Function; + /** A Boolean value specifying whether to enable or disable list scrolling. */ + scrollingEnabled?: boolean; + /** Specifies when the widget shows the scrollbar. */ + showScrollbar?: string; + /** Specifies whether or not the widget uses native scrolling. */ + useNativeScrolling?: boolean; + /** A Boolean value specifying whether to enable or disable the bounce-back effect. */ + bounceEnabled?: boolean; + /** A Boolean value specifying if the list is scrolled by content. */ + scrollByContent?: boolean; + /** A Boolean value specifying if the list is scrolled using the scrollbar. */ + scrollByThumb?: boolean; + itemUnselectAction?: Function; + onItemContextMenu?: Function; + onItemHold?: Function; + /** Specifies whether or not an end-user can collapse groups. */ + collapsibleGroups?: boolean; + /** Specifies whether the next page is loaded when a user scrolls the widget to the bottom or when the "next" button is clicked. */ + pageLoadMode?: string; + /** Specifies whether or not to display controls used to select list items. */ + showSelectionControls?: boolean; + /** Specifies whether the list supports single item selection or multi-selection. */ + selectionMode?: string; + selectAllText?: string; + /** Specifies the array of items for a context menu called for a list item. */ + menuItems?: Array; + /** Specifies whether an item context menu is shown when a user holds or swipes an item. */ + menuMode?: string; + /** Specifies whether or not an end user can delete list items. */ + allowItemDeleting?: boolean; + /** Specifies the way a user can delete items from the list. */ + itemDeleteMode?: string; + /** Specifies whether or not an end user can reorder list items. */ + allowItemReordering?: boolean; + /** Specifies whether or not to show the loading panel when the DataSource bound to the widget is loading data. */ + indicateLoading?: boolean; + } + /** A list widget. */ + export class dxList extends CollectionWidget { + constructor(element: JQuery, options?: dxListOptions); + constructor(element: Element, options?: dxListOptions); + /** Returns the height of the widget in pixels. */ + clientHeight(): number; + /** Removes the specified item from the list. */ + deleteItem(itemIndex: any): JQueryPromise; + /** Removes the specified item from the list. */ + deleteItem(itemElement: Element): JQueryPromise; + /** Returns a Boolean value that indicates whether or not the specified item is selected. */ + isItemSelected(itemIndex: any): boolean; + /** Returns a Boolean value that indicates whether or not the specified item is selected. */ + isItemSelected(itemElement: Element): boolean; + /** Reloads list data. */ + reload(): void; + /** Moves the specified item to the specified position in the list. */ + reorderItem(itemElement: Element, toItemElement: Element): JQueryPromise; + /** Moves the specified item to the specified position in the list. */ + reorderItem(itemIndex: any, toItemIndex: any): JQueryPromise; + /** Scrolls the list content by the specified number of pixels. */ + scrollBy(distance: number): void; + /** Returns the height of the list content in pixels. */ + scrollHeight(): number; + /** Scrolls list content to the specified position. */ + scrollTo(location: number): void; + /** Scrolls the list to the specified item. */ + scrollToItem(itemElement: Element): void; + /** Scrolls the list to the specified item. */ + scrollToItem(itemIndex: any): void; + /** Returns how far the list content is scrolled from the top. */ + scrollTop(): number; + /** Selects the specified item from the list. */ + selectItem(itemElement: Element): void; + /** Selects the specified item from the list. */ + selectItem(itemIndex: any): void; + /** Deselects the specified item from the list. */ + unselectItem(itemElement: Element): void; + /** Unselects the specified item from the list. */ + unselectItem(itemIndex: any): void; + /** Updates the widget scrollbar according to widget content size. */ + updateDimensions(): JQueryPromise; + /** Expands the specified group. */ + expandGroup(groupIndex: number): JQueryPromise; + /** Collapses the specified group. */ + collapseGroup(groupIndex: number): JQueryPromise; + } + export interface dxGalleryOptions extends CollectionWidgetOptions { + /** The time, in milliseconds, spent on slide animation. */ + animationDuration?: number; + /** Specifies whether or not to animate the displayed item change. */ + animationEnabled?: boolean; + /** A Boolean value specifying whether or not to allow users to switch between items by clicking an indicator. */ + indicatorEnabled?: boolean; + /** A Boolean value specifying whether or not to scroll back to the first item after the last item is swiped. */ + loop?: boolean; + /** The index of the currently active gallery item. */ + selectedIndex?: number; + /** A Boolean value specifying whether or not to display an indicator that points to the selected gallery item. */ + showIndicator?: boolean; + /** A Boolean value that specifies the availability of the "Forward" and "Back" navigation buttons. */ + showNavButtons?: boolean; + /** The time interval in milliseconds, after which the gallery switches to the next item. */ + slideshowDelay?: number; + /** A Boolean value specifying whether or not to allow users to switch between items by swiping. */ + swipeEnabled?: boolean; + /** Specifies whether or not to display parts of previous and next images along the sides of the current image. */ + wrapAround?: boolean; + /** Specifies if the widget stretches images to fit the total gallery width. */ + stretchImages?: boolean; + /** Specifies the width of an area used to display a single image. */ + initialItemWidth?: number; + } + /** An image gallery widget. */ + export class dxGallery extends CollectionWidget { + constructor(element: JQuery, options?: dxGalleryOptions); + constructor(element: Element, options?: dxGalleryOptions); + /** Shows the specified gallery item. */ + goToItem(itemIndex: number, animation: boolean): JQueryPromise; + /** Shows the next gallery item. */ + nextItem(animation: boolean): JQueryPromise; + /** Shows the previous gallery item. */ + prevItem(animation: boolean): JQueryPromise; + } + export interface dxDropDownEditorOptions extends dxTextBoxOptions { + /** Specifies the current value displayed by the widget. */ + value?: Object; + /** A handler for the closed event. */ + onClosed?: Function; + /** A handler for the opened event. */ + onOpened?: Function; + /** Specifies whether or not the drop-down editor is displayed. */ + opened?: boolean; + closeAction?: Function; + openAction?: Function; + shownAction?: Function; + hiddenAction?: Function; + /** Specifies whether or not the widget allows an end-user to enter a custom value. */ + fieldEditEnabled?: boolean; + editEnabled?: boolean; + /** Specifies the way an end-user applies the selected value. */ + applyValueMode?: string; + } + /** A drop-down editor widget. */ + export class dxDropDownEditor extends dxTextBox { + constructor(element: JQuery, options?: dxDropDownEditorOptions); + constructor(element: Element, options?: dxDropDownEditorOptions); + /** Closes the drop-down editor. */ + close(): void; + /** Opens the drop-down editor. */ + open(): void; + /** Resets the widget's value to null. */ + reset(): void; + /** Returns an <input> element of the widget. */ + field(): JQuery; + /** Returns an HTML element of the popup window content. */ + content(): JQuery; + } + export interface dxDateBoxOptions extends dxTextEditorOptions { + /** A format used to display date/time information. */ + format?: string; + /** A Globalize format string specifying the date display format. */ + formatString?: string; + /** The last date that can be selected within the widget. */ + max?: Date; + /** The minimum date that can be selected within the widget. */ + min?: Date; + /** The text displayed by the widget when the widget value is not yet specified. This text is also used as a title of the date picker. */ + placeholder?: string; + /** + * Specifies whether or not a user can pick out a date using the drop-down calendar. + * @deprecated Use 'pickerType' option instead. + */ + useCalendar?: boolean; + /** A Date object specifying the date and time currently selected using the date box. */ + value?: Date; + /** + * Specifies whether or not the widget uses the native HTML input element. + * @deprecated Use 'pickerType' option instead. + */ + useNative?: boolean; + /** Specifies the interval between neighboring values in the popup list in minutes. */ + interval?: number; + /** Specifies the maximum zoom level of a calendar, which is used to pick the date. */ + maxZoomLevel?: string; + /** Specifies the minimal zoom level of a calendar, which is used to pick the date. */ + minZoomLevel?: string; + /** Specifies the type of date/time picker. */ + pickerType?: string; + } + /** A date box widget. */ + export class dxDateBox extends dxDropDownEditor { + constructor(element: JQuery, options?: dxDateBoxOptions); + constructor(element: Element, options?: dxDateBoxOptions); + } + export interface dxCheckBoxOptions extends EditorOptions { + /** Specifies the widget state. */ + value?: boolean; + /** Specifies the text displayed by the check box. */ + text?: string; + } + /** A check box widget. */ + export class dxCheckBox extends Editor { + constructor(element: JQuery, options?: dxCheckBoxOptions); + constructor(element: Element, options?: dxCheckBoxOptions); + } + export interface dxCalendarOptions extends EditorOptions { + /** Specifies a date displayed on the current calendar page. */ + currentDate?: Date; + /** Specifies the first day of a week. */ + firstDayOfWeek?: number; + /** The latest date the widget allows to select. */ + max?: Date; + /** The earliest date the widget allows to select. */ + min?: Date; + /** Specifies whether or not the widget displays a button that selects the current date. */ + showTodayButton?: boolean; + /** Specifies the current calendar zoom level. */ + zoomLevel?: string; + /** Specifies the maximum zoom level of the calendar. */ + maxZoomLevel?: string; + /** Specifies the minimum zoom level of the calendar. */ + minZoomLevel?: string; + /** The template to be used for rendering calendar cells. */ + cellTemplate?: any; + } + /** A calendar widget. */ + export class dxCalendar extends Editor { + constructor(element: JQuery, options?: dxCalendarOptions); + constructor(element: Element, options?: dxCalendarOptions); + } + export interface dxButtonOptions extends WidgetOptions { + /** A Boolean value specifying whether or not the widget changes its state when interacting with a user. */ + activeStateEnabled?: boolean; + /** A handler for the click event. */ + onClick?: any; + clickAction?: any; + /** Specifies the icon to be displayed on the button. */ + icon?: string; + iconSrc?: string; + /** A template to be used for rendering the dxButton widget. */ + template?: any; + /** The text displayed on the button. */ + text?: string; + /** Specifies the button type. */ + type?: string; + /** Specifies the name of the validation group to be accessed in the click event handler. */ + validationGroup?: string; + } + /** A button widget. */ + export class dxButton extends Widget { + constructor(element: JQuery, options?: dxButtonOptions); + constructor(element: Element, options?: dxButtonOptions); + } + export interface dxBoxOptions extends CollectionWidget { + /** Specifies how widget items are aligned along the main direction. */ + align?: string; + /** Specifies the direction of item positioning in the widget. */ + direction?: string; + /** Specifies how widget items are aligned cross-wise. */ + crossAlign?: string; + } + /** A container widget used to arrange inner elements. */ + export class dxBox extends CollectionWidget { + constructor(element: JQuery, options?: dxBoxOptions); + constructor(element: Element, options?: dxBoxOptions); + } + export interface dxResponsiveBoxOptions extends CollectionWidgetOptions { + /** Specifies the collection of rows for the grid used to position layout elements. */ + rows?: Array; + /** Specifies the collection of columns for the grid used to position layout elements. */ + cols?: Array; + /** Specifies the function returning the screen factor depending on the screen width. */ + screenByWidth?: (width: number) => string; + /** Specifies the screen factor with which all elements are located in a single column. */ + singleColumnScreen?: string; + } + /** A widget used to build an adaptive markup that is dependent on screen resolution. */ + export class dxResponsiveBox extends CollectionWidget { + constructor(element: JQuery, options?: dxBoxOptions); + constructor(element: Element, options?: dxBoxOptions); + } + export interface dxAutocompleteOptions extends dxDropDownListOptions { + /** Specifies the current value displayed by the widget. */ + value?: string; + /** The minimum number of characters that must be entered into the text box to begin a search. */ + minSearchLength?: number; + /** Specifies the maximum count of items displayed by the widget. */ + maxItemCount?: number; + /** Gets the currently selected item. */ + selectedItem?: Object; + } + /** A textbox widget that supports autocompletion. */ + export class dxAutocomplete extends dxDropDownList { + constructor(element: JQuery, options?: dxAutocompleteOptions); + constructor(element: Element, options?: dxAutocompleteOptions); + /** Opens the drop-down editor. */ + open(): void; + /** Closes the drop-down editor. */ + close(): void; + } + export interface dxAccordionOptions extends CollectionWidgetOptions { + /** A number specifying the time in milliseconds spent on the animation of the expanding or collapsing of a panel. */ + animationDuration?: number; + /** Specifies the height of the widget. */ + height?: any; + /** Specifies whether all items can be collapsed or whether at least one item must always be expanded. */ + collapsible?: boolean; + /** Specifies whether the widget can expand several items or only a single item at once. */ + multiple?: boolean; + /** The template to be used for rendering dxAccordion items. */ + itemTemplate?: any; + /** A handler for the itemTitleClick event. */ + onItemTitleClick?: any; + /** A handler for the itemTitleHold event. */ + onItemTitleHold?: Function; + /** The template to be used for rendering an item title. */ + itemTitleTemplate?: any; + /** The index number of the currently selected item. */ + selectedIndex?: number; + } + /** A widget that displays data source items on collapsible panels. */ + export class dxAccordion extends CollectionWidget { + constructor(element: JQuery, options?: dxAccordionOptions); + constructor(element: Element, options?: dxAccordionOptions); + /** Collapses the specified item. */ + collapseItem(index: number): JQueryPromise; + /** Expands the specified item. */ + expandItem(index: number): JQueryPromise; + } + export interface dxFileUploaderOptions extends EditorOptions { + /** A read-only option that holds a File instance representing the selected file. */ + value?: File; + /** Holds the File instances representing files selected in the widget. */ + values?: Array; + buttonText?: string; + /** The text displayed on the button that opens the file browser. */ + selectButtonText?: string; + /** The text displayed on the button that starts uploading. */ + uploadButtonText?: string; + /** Specifies the text displayed on the area to which an end-user can drop a file. */ + labelText?: string; + /** Specifies the value passed to the name attribute of the underlying input element. */ + name?: string; + /** Specifies whether the widget enables an end-user to select a single file or multiple files. */ + multiple?: boolean; + /** Specifies a file type or several types accepted by the widget. */ + accept?: string; + /** Specifies a target Url for the upload request. */ + uploadUrl?: string; + /** Specifies if an end user can remove a file from the selection and interrupt uploading. */ + allowCanceling?: boolean; + /** Specifies whether or not the widget displays the list of selected files. */ + showFileList?: boolean; + /** Gets the current progress in percentages. */ + progress?: number; + /** The message displayed by the widget when it is ready to upload the specified files. */ + readyToUploadMessage?: string; + /** The message displayed by the widget when uploading is finished. */ + uploadedMessage?: string; + /** The message displayed by the widget on uploading failure. */ + uploadFailedMessage?: string; + /** Specifies how the widget uploads files. */ + uploadMode?: string; + } + /** A widget used to select and upload a file or multiple files. */ + export class dxFileUploader extends Editor { + constructor(element: JQuery, options?: dxFileUploaderOptions); + constructor(element: Element, options?: dxFileUploaderOptions); + } + export interface dxTrackBarOptions extends EditorOptions { + /** The minimum value the widget can accept. */ + min?: number; + /** The maximum value the widget can accept. */ + max?: number; + /** The current widget value. */ + value?: number; + } + /** A base class for track bar widgets. */ + export class dxTrackBar extends Editor { + constructor(element: JQuery, options?: dxTrackBarOptions); + constructor(element: Element, options?: dxTrackBarOptions); + } + export interface dxProgressBarOptions extends dxTrackBarOptions { + /** Specifies a format for the progress status. */ + statusFormat?: any; + /** Specifies whether or not the widget displays a progress status. */ + showStatus?: boolean; + /** A handler for the complete event. */ + onComplete?: Function; + } + /** A widget used to indicate progress. */ + export class dxProgressBar extends dxTrackBar { + constructor(element: JQuery, options?: dxProgressBarOptions); + constructor(element: Element, options?: dxProgressBarOptions); + } + export interface dxSliderOptions extends dxTrackBarOptions { + /** The slider step size. */ + step?: number; + /** The current slider value. */ + value?: number; + /** Specifies whether or not to highlight a range selected within the widget. */ + showRange?: boolean; + /** Specifies the size of a step by which a slider handle is moved when a user uses the Page up or Page down keyboard shortcuts. */ + keyStep?: number; + /** Specifies options for the slider tooltip. */ + tooltip?: { + /** Specifies whether or not the tooltip is enabled. */ + enabled?: boolean; + /** Specifies format for the tooltip. */ + format?: any; + /** Specifies whether the tooltip is located over or under the slider. */ + position?: string; + /** Specifies whether the widget always shows a tooltip or only when a pointer is over the slider. */ + showMode?: string; + }; + /** Specifies options for labels displayed at the min and max values. */ + label?: { + /** Specifies whether or not slider labels are visible. */ + visible?: boolean; + /** Specifies whether labels are located over or under the scale. */ + position?: string; + /** Specifies a format for labels. */ + format?: any; + }; + } + /** A widget that allows a user to select a numeric value within a given range. */ + export class dxSlider extends dxTrackBar { + constructor(element: JQuery, options?: dxSliderOptions); + constructor(element: Element, options?: dxSliderOptions); + } + export interface dxRangeSliderOptions extends dxSliderOptions { + /** The left edge of the interval currently selected using the range slider. */ + start?: number; + /** The right edge of the interval currently selected using the range slider. */ + end?: number; + } + /** A widget that enables a user to select a range of numeric values. */ + export class dxRangeSlider extends dxSlider { + constructor(element: JQuery, options?: dxRangeSliderOptions); + constructor(element: Element, options?: dxRangeSliderOptions); + } +} +interface JQuery { + dxProgressBar(): JQuery; + dxProgressBar(options: "instance"): DevExpress.ui.dxProgressBar; + dxProgressBar(options: string): any; + dxProgressBar(options: string, ...params: any[]): any; + dxProgressBar(options: DevExpress.ui.dxProgressBarOptions): JQuery; + dxSlider(): JQuery; + dxSlider(options: "instance"): DevExpress.ui.dxSlider; + dxSlider(options: string): any; + dxSlider(options: string, ...params: any[]): any; + dxSlider(options: DevExpress.ui.dxSliderOptions): JQuery; + dxRangeSlider(): JQuery; + dxRangeSlider(options: "instance"): DevExpress.ui.dxRangeSlider; + dxRangeSlider(options: string): any; + dxRangeSlider(options: string, ...params: any[]): any; + dxRangeSlider(options: DevExpress.ui.dxRangeSliderOptions): JQuery; + dxFileUploader(): JQuery; + dxFileUploader(options: "instance"): DevExpress.ui.dxFileUploader; + dxFileUploader(options: string): any; + dxFileUploader(options: string, ...params: any[]): any; + dxFileUploader(options: DevExpress.ui.dxFileUploaderOptions): JQuery; + dxValidator(): JQuery; + dxValidator(options: "instance"): DevExpress.ui.dxValidator; + dxValidator(options: string): any; + dxValidator(options: string, ...params: any[]): any; + dxValidationGroup(): JQuery; + dxValidationGroup(options: "instance"): DevExpress.ui.dxValidationGroup; + dxValidationGroup(options: string): any; + dxValidationGroup(options: string, ...params: any[]): any; + dxValidationSummary(): JQuery; + dxValidationSummary(options: "instance"): DevExpress.ui.dxValidationSummary; + dxValidationSummary(options: string): any; + dxValidationSummary(options: string, ...params: any[]): any; + dxTooltip(): JQuery; + dxTooltip(options: "instance"): DevExpress.ui.dxTooltip; + dxTooltip(options: string): any; + dxTooltip(options: string, ...params: any[]): any; + dxTooltip(options: DevExpress.ui.dxTooltipOptions): JQuery; + dxResizable(): JQuery; + dxResizable(options: "instance"): DevExpress.ui.dxResizable; + dxResizable(options: string): any; + dxResizable(options: string, ...params: any[]): any; + dxResizable(options: DevExpress.ui.dxResizableOptions): JQuery; + dxDropDownList(): JQuery; + dxDropDownList(options: "instance"): DevExpress.ui.dxDropDownList; + dxDropDownList(options: string): any; + dxDropDownList(options: string, ...params: any[]): any; + dxDropDownList(options: DevExpress.ui.dxDropDownListOptions): JQuery; + dxToolbar(): JQuery; + dxToolbar(options: "instance"): DevExpress.ui.dxToolbar; + dxToolbar(options: string): any; + dxToolbar(options: string, ...params: any[]): any; + dxToolbar(options: DevExpress.ui.dxToolbarOptions): JQuery; + dxToast(): JQuery; + dxToast(options: "instance"): DevExpress.ui.dxToast; + dxToast(options: string): any; + dxToast(options: string, ...params: any[]): any; + dxToast(options: DevExpress.ui.dxToastOptions): JQuery; + dxTextEditor(): JQuery; + dxTextEditor(options: "instance"): DevExpress.ui.dxTextEditor; + dxTextEditor(options: string): any; + dxTextEditor(options: string, ...params: any[]): any; + dxTextEditor(options: DevExpress.ui.dxTextEditorOptions): JQuery; + dxTextBox(): JQuery; + dxTextBox(options: "instance"): DevExpress.ui.dxTextBox; + dxTextBox(options: string): any; + dxTextBox(options: string, ...params: any[]): any; + dxTextBox(options: DevExpress.ui.dxTextBoxOptions): JQuery; + dxTextArea(): JQuery; + dxTextArea(options: "instance"): DevExpress.ui.dxTextArea; + dxTextArea(options: string): any; + dxTextArea(options: string, ...params: any[]): any; + dxTextArea(options: DevExpress.ui.dxTextAreaOptions): JQuery; + dxTabs(): JQuery; + dxTabs(options: "instance"): DevExpress.ui.dxTabs; + dxTabs(options: string): any; + dxTabs(options: string, ...params: any[]): any; + dxTabs(options: DevExpress.ui.dxTabsOptions): JQuery; + dxTabPanel(): JQuery; + dxTabPanel(options: "instance"): DevExpress.ui.dxTabPanel; + dxTabPanel(options: string): any; + dxTabPanel(options: string, ...params: any[]): any; + dxTabPanel(options: DevExpress.ui.dxTabPanelOptions): JQuery; + dxSelectBox(): JQuery; + dxSelectBox(options: "instance"): DevExpress.ui.dxSelectBox; + dxSelectBox(options: string): any; + dxSelectBox(options: string, ...params: any[]): any; + dxSelectBox(options: DevExpress.ui.dxSelectBoxOptions): JQuery; + dxScrollView(): JQuery; + dxScrollView(options: "instance"): DevExpress.ui.dxScrollView; + dxScrollView(options: string): any; + dxScrollView(options: string, ...params: any[]): any; + dxScrollView(options: DevExpress.ui.dxScrollViewOptions): JQuery; + dxScrollable(): JQuery; + dxScrollable(options: "instance"): DevExpress.ui.dxScrollable; + dxScrollable(options: string): any; + dxScrollable(options: string, ...params: any[]): any; + dxScrollable(options: DevExpress.ui.dxScrollableOptions): JQuery; + dxRadioGroup(): JQuery; + dxRadioGroup(options: "instance"): DevExpress.ui.dxRadioGroup; + dxRadioGroup(options: string): any; + dxRadioGroup(options: string, ...params: any[]): any; + dxRadioGroup(options: DevExpress.ui.dxRadioGroupOptions): JQuery; + dxPopup(): JQuery; + dxPopup(options: "instance"): DevExpress.ui.dxPopup; + dxPopup(options: string): any; + dxPopup(options: string, ...params: any[]): any; + dxPopup(options: DevExpress.ui.dxPopupOptions): JQuery; + dxPopover(): JQuery; + dxPopover(options: "instance"): DevExpress.ui.dxPopover; + dxPopover(options: string): any; + dxPopover(options: string, ...params: any[]): any; + dxPopover(options: DevExpress.ui.dxPopoverOptions): JQuery; + dxOverlay(): JQuery; + dxOverlay(options: "instance"): DevExpress.ui.dxOverlay; + dxOverlay(options: string): any; + dxOverlay(options: string, ...params: any[]): any; + dxOverlay(options: DevExpress.ui.dxOverlayOptions): JQuery; + dxNumberBox(): JQuery; + dxNumberBox(options: "instance"): DevExpress.ui.dxNumberBox; + dxNumberBox(options: string): any; + dxNumberBox(options: string, ...params: any[]): any; + dxNumberBox(options: DevExpress.ui.dxNumberBoxOptions): JQuery; + dxNavBar(): JQuery; + dxNavBar(options: "instance"): DevExpress.ui.dxNavBar; + dxNavBar(options: string): any; + dxNavBar(options: string, ...params: any[]): any; + dxNavBar(options: DevExpress.ui.dxNavBarOptions): JQuery; + dxMultiView(): JQuery; + dxMultiView(options: "instance"): DevExpress.ui.dxMultiView; + dxMultiView(options: string): any; + dxMultiView(options: string, ...params: any[]): any; + dxMultiView(options: DevExpress.ui.dxMultiViewOptions): JQuery; + dxMap(): JQuery; + dxMap(options: "instance"): DevExpress.ui.dxMap; + dxMap(options: string): any; + dxMap(options: string, ...params: any[]): any; + dxMap(options: DevExpress.ui.dxMapOptions): JQuery; + dxLookup(): JQuery; + dxLookup(options: "instance"): DevExpress.ui.dxLookup; + dxLookup(options: string): any; + dxLookup(options: string, ...params: any[]): any; + dxLookup(options: DevExpress.ui.dxLookupOptions): JQuery; + dxLoadPanel(): JQuery; + dxLoadPanel(options: "instance"): DevExpress.ui.dxLoadPanel; + dxLoadPanel(options: string): any; + dxLoadPanel(options: string, ...params: any[]): any; + dxLoadPanel(options: DevExpress.ui.dxLoadPanelOptions): JQuery; + dxLoadIndicator(): JQuery; + dxLoadIndicator(options: "instance"): DevExpress.ui.dxLoadIndicator; + dxLoadIndicator(options: string): any; + dxLoadIndicator(options: string, ...params: any[]): any; + dxLoadIndicator(options: DevExpress.ui.dxLoadIndicatorOptions): JQuery; + dxList(): JQuery; + dxList(options: "instance"): DevExpress.ui.dxList; + dxList(options: string): any; + dxList(options: string, ...params: any[]): any; + dxList(options: DevExpress.ui.dxListOptions): JQuery; + dxGallery(): JQuery; + dxGallery(options: "instance"): DevExpress.ui.dxGallery; + dxGallery(options: string): any; + dxGallery(options: string, ...params: any[]): any; + dxGallery(options: DevExpress.ui.dxGalleryOptions): JQuery; + dxDropDownEditor(): JQuery; + dxDropDownEditor(options: "instance"): DevExpress.ui.dxDropDownEditor; + dxDropDownEditor(options: string): any; + dxDropDownEditor(options: string, ...params: any[]): any; + dxDropDownEditor(options: DevExpress.ui.dxDropDownEditorOptions): JQuery; + dxDateBox(): JQuery; + dxDateBox(options: "instance"): DevExpress.ui.dxDateBox; + dxDateBox(options: string): any; + dxDateBox(options: string, ...params: any[]): any; + dxDateBox(options: DevExpress.ui.dxDateBoxOptions): JQuery; + dxCheckBox(): JQuery; + dxCheckBox(options: "instance"): DevExpress.ui.dxCheckBox; + dxCheckBox(options: string): any; + dxCheckBox(options: string, ...params: any[]): any; + dxCheckBox(options: DevExpress.ui.dxCheckBoxOptions): JQuery; + dxBox(): JQuery; + dxBox(options: "instance"): DevExpress.ui.dxBox; + dxBox(options: string): any; + dxBox(options: string, ...params: any[]): any; + dxBox(options: DevExpress.ui.dxBoxOptions): JQuery; + dxButton(): JQuery; + dxButton(options: "instance"): DevExpress.ui.dxButton; + dxButton(options: string): any; + dxButton(options: string, ...params: any[]): any; + dxButton(options: DevExpress.ui.dxButtonOptions): JQuery; + dxCalendar(): JQuery; + dxCalendar(options: "instance"): DevExpress.ui.dxCalendar; + dxCalendar(options: string): any; + dxCalendar(options: string, ...params: any[]): any; + dxCalendar(options: DevExpress.ui.dxCalendarOptions): JQuery; + dxAccordion(): JQuery; + dxAccordion(options: "instance"): DevExpress.ui.dxAccordion; + dxAccordion(options: string): any; + dxAccordion(options: string, ...params: any[]): any; + dxAccordion(options: DevExpress.ui.dxAccordionOptions): JQuery; + dxAutocomplete(): JQuery; + dxAutocomplete(options: "instance"): DevExpress.ui.dxAutocomplete; + dxAutocomplete(options: string): any; + dxAutocomplete(options: string, ...params: any[]): any; + dxAutocomplete(options: DevExpress.ui.dxAutocompleteOptions): JQuery; +} + +declare module DevExpress.ui { + export interface dxTileViewOptions extends CollectionWidgetOptions { + /** A Boolean value specifying whether or not the widget changes its state when interacting with a user. */ + activeStateEnabled?: boolean; + /** Specifies the height of the base tile view item. */ + baseItemHeight?: number; + /** Specifies the width of the base tile view item. */ + baseItemWidth?: number; + /** Specifies the height of the widget. */ + height?: any; + /** Specifies the distance in pixels between adjacent tiles. */ + itemMargin?: number; + /** A Boolean value specifying whether or not to display a scrollbar. */ + showScrollbar?: boolean; + } + /** A widget displaying several blocks of data as tiles. */ + export class dxTileView extends CollectionWidget { + constructor(element: JQuery, options?: dxTileViewOptions); + constructor(element: Element, options?: dxTileViewOptions); + /** Returns the current scroll position of the widget content. */ + scrollPosition(): number; + } + export interface dxSwitchOptions extends EditorOptions { + /** Text displayed when the widget is in a disabled state. */ + offText?: string; + /** Text displayed when the widget is in an enabled state. */ + onText?: string; + /** A Boolean value specifying whether the current switch state is "On" or "Off". */ + value?: boolean; + } + /** A switch widget. */ + export class dxSwitch extends Editor { + constructor(element: JQuery, options?: dxSwitchOptions); + constructor(element: Element, options?: dxSwitchOptions); + } + export interface dxSlideOutViewOptions extends WidgetOptions { + /** Specifies whether or not the menu panel is visible. */ + menuVisible?: boolean; + /** Specifies whether or not the menu is shown when a user swipes the widget content. */ + swipeEnabled?: boolean; + /** A template to be used for rendering menu panel content. */ + menuTemplate?: any; + /** A template to be used for rendering widget content. */ + contentTemplate?: any; + } + /** The widget that allows you to slide-out the current view to reveal a custom menu. */ + export class dxSlideOutView extends Widget { + constructor(element: JQuery, options?: dxSlideOutViewOptions); + constructor(element: Element, options?: dxSlideOutViewOptions); + /** Returns an HTML element of the widget menu block. */ + menuContent(): JQuery; + /** Returns an HTML element of the widget content block. */ + content(): JQuery; + /** Displays the widget's menu block. */ + showMenu(): JQueryPromise; + /** Hides the widget's menu block. */ + hideMenu(): JQueryPromise; + /** Toggles the visibility of the widget's menu block. */ + toggleMenuVisibility(): JQueryPromise; + } + export interface dxSlideOutOptions extends CollectionWidgetOptions { + /** A Boolean value specifying whether or not the widget changes its state when interacting with a user. */ + activeStateEnabled?: boolean; + /** A Boolean value specifying whether or not to display a grouped menu. */ + menuGrouped?: boolean; + menuGroupRender?: any; + /** The name of the template used to display a group header. */ + menuGroupTemplate?: any; + menuItemRender?: any; + /** The template used to render menu items. */ + menuItemTemplate?: any; + /** A handler for the menuGroupRendered event. */ + onMenuGroupRendered?: Function; + /** A handler for the menuItemRendered event. */ + onMenuItemRendered?: Function; + /** Specifies whether or not the slide-out menu is displayed. */ + menuVisible?: boolean; + /** Indicates whether the menu can be shown/hidden by swiping the widget's main panel. */ + swipeEnabled?: boolean; + /** A template to be used for rendering widget content. */ + contentTemplate?: any; + } + /** The widget that allows you to slide-out the current view to reveal an item list. */ + export class dxSlideOut extends CollectionWidget { + constructor(element: JQuery, options?: dxSlideOutOptions); + constructor(element: Element, options?: dxSlideOutOptions); + /** Hides the widget's slide-out menu. */ + hideMenu(): JQueryPromise; + /** Displays the widget's slide-out menu. */ + showMenu(): JQueryPromise; + /** Toggles the visibility of the widget's slide-out menu. */ + toggleMenuVisibility(showing: boolean): JQueryPromise; + } + export interface dxPivotOptions extends CollectionWidgetOptions { + /** The index of the currently active pivot item. */ + selectedIndex?: number; + /** A Boolean value specifying whether or not to allow users to switch between items by swiping. */ + swipeEnabled?: boolean; + /** A template to be used for rendering widget content. */ + contentTemplate?: any; + } + /** A widget that is similar to a traditional tab control, but optimized for the phone with simplified end-user interaction. */ + export class dxPivot extends CollectionWidget { + constructor(element: JQuery, options?: dxPivotOptions); + constructor(element: Element, options?: dxPivotOptions); + } + export interface dxPanoramaOptions extends CollectionWidgetOptions { + /** An object exposing options for setting a background image for the panorama. */ + backgroundImage?: { + /** Specifies the height of the panorama's background image. */ + height?: number; + /** Specifies the URL of the image that is used as the panorama's background image. */ + url?: string; + /** Specifies the width of the panorama's background image. */ + width?: number; + }; + /** The index of the currently active panorama item. */ + selectedIndex?: number; + /** Specifies the widget content title. */ + title?: string; + } + /** A widget displaying the required content in a long horizontal canvas that extends beyond the frames of the screen. */ + export class dxPanorama extends CollectionWidget { + constructor(element: JQuery, options?: dxDropDownEditorOptions); + constructor(element: Element, options?: dxDropDownEditorOptions); + } + export interface dxDropDownMenuOptions extends WidgetOptions { + /** A handler for the buttonClick event. */ + onButtonClick?: any; + buttonClickAction?: any; + /** The name of the icon to be displayed by the DropDownMenu button. */ + buttonIcon?: string; + buttonIconSrc?: string; + /** The text displayed in the DropDownMenu button. */ + buttonText?: string; + /** A data source used to fetch data to be displayed by the widget. */ + dataSource?: any; + /** A handler for the itemClick event. */ + onItemClick?: any; + itemClickAction?: any; + itemRender?: any; + /** An array of items displayed by the widget. */ + items?: Array; + /** The template to be used for rendering items. */ + itemTemplate?: any; + /** Specifies whether or not to show the drop down menu within a dxPopover widget. */ + usePopover?: boolean; + /** The width of the menu popup in pixels. */ + popupWidth?: any; + /** The height of the menu popup in pixels. */ + popupHeight?: any; + /** Specifies whether or not the drop-down menu is displayed. */ + opened?: boolean; + /** A Boolean value specifying whether or not the widget changes its state when being hovered by an end user. */ + hoverStateEnabled?: boolean; + } + /** A drop-down menu widget. */ + export class dxDropDownMenu extends Widget { + constructor(element: JQuery, options?: dxDropDownEditorOptions); + constructor(element: Element, options?: dxDropDownEditorOptions); + /** This section lists the data source fields that are used in a default template for drop-down menu items. */ + /** Opens the drop-down menu. */ + open(): void; + /** Closes the drop-down menu. */ + close(): void; + } + export interface dxActionSheetOptions extends CollectionWidgetOptions { + cancelClickAction?: any; + /** A handler for the cancelClick event. */ + onCancelClick?: any; + /** The text displayed in the button that closes the action sheet. */ + cancelText?: string; + /** Specifies whether or not to display the Cancel button in action sheet. */ + showCancelButton?: boolean; + /** A Boolean value specifying whether or not the title of the action sheet is visible. */ + showTitle?: boolean; + /** Specifies the element the action sheet popover points at. */ + target?: any; + /** The title of the action sheet. */ + title?: string; + /** Specifies whether or not to show the action sheet within a dxPopover widget. */ + usePopover?: boolean; + /** A Boolean value specifying whether or not the dxActionSheet widget is visible. */ + visible?: boolean; + } + /** A widget consisting of a set of choices related to a certain task. */ + export class dxActionSheet extends CollectionWidget { + constructor(element: JQuery, options?: dxActionSheetOptions); + constructor(element: Element, options?: dxActionSheetOptions); + /** Hides the widget. */ + hide(): JQueryPromise; + /** Shows the widget. */ + show(): JQueryPromise; + /** Shows or hides the widget depending on the Boolean value passed as the parameter. */ + toggle(showing: boolean): JQueryPromise; + } +} +interface JQuery { + dxTileView(): JQuery; + dxTileView(options: "instance"): DevExpress.ui.dxTileView; + dxTileView(options: string): any; + dxTileView(options: string, ...params: any[]): any; + dxTileView(options: DevExpress.ui.dxTileViewOptions): JQuery; + dxSwitch(): JQuery; + dxSwitch(options: "instance"): DevExpress.ui.dxSwitch; + dxSwitch(options: string): any; + dxSwitch(options: string, ...params: any[]): any; + dxSwitch(options: DevExpress.ui.dxSwitchOptions): JQuery; + dxSlideOut(): JQuery; + dxSlideOut(options: "instance"): DevExpress.ui.dxSlideOut; + dxSlideOut(options: string): any; + dxSlideOut(options: string, ...params: any[]): any; + dxSlideOut(options: DevExpress.ui.dxSlideOutOptions): JQuery; + dxPivot(): JQuery; + dxPivot(options: "instance"): DevExpress.ui.dxPivot; + dxPivot(options: string): any; + dxPivot(options: string, ...params: any[]): any; + dxPivot(options: DevExpress.ui.dxPivotOptions): JQuery; + dxPanorama(): JQuery; + dxPanorama(options: "instance"): DevExpress.ui.dxPanorama; + dxPanorama(options: string): any; + dxPanorama(options: string, ...params: any[]): any; + dxPanorama(options: DevExpress.ui.dxPanoramaOptions): JQuery; + dxActionSheet(): JQuery; + dxActionSheet(options: "instance"): DevExpress.ui.dxActionSheet; + dxActionSheet(options: string): any; + dxActionSheet(options: string, ...params: any[]): any; + dxActionSheet(options: DevExpress.ui.dxActionSheetOptions): JQuery; + dxDropDownMenu(): JQuery; + dxDropDownMenu(options: "instance"): DevExpress.ui.dxDropDownMenu; + dxDropDownMenu(options: string): any; + dxDropDownMenu(options: string, ...params: any[]): any; + dxDropDownMenu(options: DevExpress.ui.dxDropDownMenuOptions): JQuery; +} +declare module DevExpress.data { + export interface XmlaStoreOptions { + /** The HTTP address to an XMLA OLAP server. */ + url?: string; + /** The name of the database associated with the Store. */ + catalog?: string; + /** The cube name. */ + cube?: string; + beforeSend?: (request: Object) => void; + } + /** A Store that provides access to an OLAP cube using the XMLA standard. */ + export class XmlaStore { + constructor(options: XmlaStoreOptions); + } + export interface PivotGridField { + index?: number; + /** A boolean value specifying whether or not the field is visible in the pivot grid and the Field Chooser. */ + visible?: boolean; + /** Name of the data source field containing data for the pivot grid field. */ + dataField?: string; + /** A caption that will be displayed in the pivot grid's field chooser to identify the field. */ + caption?: string; + /** Specifies a type of field values. */ + dataType?: string; + /** Specifies how the values of the current field are combined into groups. Cannot be used for the XmlaStore store type. */ + groupInterval?: any; + /** Specifies how to aggregate field data. Cannot be used for th XmlaStore store type. */ + summaryType?: string; + /** Allows you to use a custom aggregate function to calculate the summary values. Cannot be used for the XmlaStore store type. */ + calculateCustomSummary?: (options: { + summaryProcess?: string; + value?: any; + totalValue?: any; + }) => void; + /** Specifies the function that determines how to split data from the data source into ranges for header items. Cannot be used for the XmlaStore store type. */ + selector?: (data: Object) => any; + /** Type of the area where the field is located. */ + area?: string; + /** Index among the other fields displayed within the same area. */ + areaIndex?: number; + /** The name of the folder in which the field is located. */ + displayFolder?: string; + /** The name of the group to which the field belongs. */ + groupName?: string; + /** The index of the field within a group. */ + groupIndex?: number; + /** Specifies the initial sort order of field values. */ + sortOrder?: string; + /** Specifies how field data should be sorted. Can be used for the XmlaStore store type only. */ + sortBy?: string; + /** Specifies the data field against which the header items of this field should be sorted. */ + sortBySummaryField?: string; + /** The array of field names that specify a path to column/row whose summary field is used for sorting of this field's header items. */ + sortBySummaryPath?: Array; + /** The filter values for the current field. */ + filterValues?: Array; + /** The filter type for the current field. */ + filterType?: string; + /** Indicates whether all header items of the field's header level are expanded. */ + expanded?: boolean; + /** Specifies whether the field should be treated as a Data Field. */ + isMeasure?: boolean; + /** Specifies a display format for field values. */ + format?: string; + /** Specifies a callback function that returns the text to be displayed in the cells of a field. */ + customizeText?: (cellInfo: { value: any; valueText: string }) => string; + /** Specifies a precision for formatted field values. */ + precision?: number; + /** Specifies how to sort the header items. */ + sortingMethod?: (a: Object, b: Object) => number; + /** Allows an end-user to change sorting options. */ + allowSorting?: boolean; + /** Allows an end-user to sort columns by summary values. */ + allowSortingBySummary?: boolean; + /** Allows an end-user to change filtering options. */ + allowFiltering?: boolean; + /** Allows an end-user to expand/collapse all header items within a header level. */ + allowExpandAll?: boolean; + /** Specifies the absolute width of the field in the pivot grid. */ + width?: number; + } + export interface PivotGridDataSourceOptions { + /** Specifies the underlying Store instance used to access data. */ + store?: any; + /** Indicates whether or not the automatic field generation from data in the Store is enabled. */ + retrieveFields?: boolean; + /** Specifies data filtering conditions. */ + filter?: Object; + /** An array of pivot grid fields. */ + fields?: Array; + /** Indicates whether or not the local sorting of the XMLA data should be performed. */ + localSorting?: boolean; + /** A handler for the changed event. */ + onChanged?: () => void; + /** A handler for the loadingChanged event. */ + onLoadingChanged?: (isLoading: boolean) => void; + /** A handler for the loadError event. */ + onLoadError?: (e?: Object) => void; + /** A handler for the fieldsPrepared event. */ + onFieldsPrepared?: (e?: Array) => void; + } + /** An object that provides access to data for the dxPivotGrid widget. */ + export class PivotGridDataSource implements EventsMixin { + constructor(options?: PivotGridDataSource); + /** Starts loading data. */ + load(): JQueryPromise; + /** Indicates whether or not the PivotGridDataSource is currently being loaded. */ + isLoading(): boolean; + /** Gets data displayed in a PivotGrid. */ + getData(): Object; + /** Gets all fields within a specified area. */ + getAreaFields(area: string, collectGroups: boolean): Array; + /** Gets all fields from the data source. */ + fields(): Array; + /** Sets the fields option. */ + fields(fields: Array): void; + /** Gets current options of a specified field. */ + field(id: number): PivotGridField; + /** Sets one or more options of a specified field. */ + field(id: number, field: PivotGridField): void; + /** Collapses a specified header item. */ + collapseHeaderItem(area: string, path: Array): void; + /** Expands a specified header item. */ + expandHeaderItem(area: string, path: Array): void; + /** Disposes of all resources associated with this PivotGridDataSource. */ + dispose(): void; + on(eventName: string, eventHandler: Function): PivotGridDataSource; + on(events: { [eventName: string]: Function; }): PivotGridDataSource; + off(eventName: string): PivotGridDataSource; + off(eventName: string, eventHandler: Function): PivotGridDataSource; + } +} +declare module DevExpress.ui { + export interface dxSchedulerOptions extends WidgetOptions { + /** Specifies a date displayed on the current scheduler view by default. */ + currentDate?: Date; + /** Specifies the view used in the scheduler by default. */ + currentView?: string; + /** A data source used to fetch data to be displayed by the widget. */ + dataSource?: any; + /** Specifies the first day of a week. */ + firstDayOfWeek?: number; + /** The template to be used for rendering appointments. */ + appointmentTemplate?: any; + /** Lists the views to be available within the scheduler's View Selector. */ + views?: Array; + /** Specifies the resource kinds by which the scheduler's appointments are grouped in a timetable. */ + groups?: Array; + /** Specifies a start hour in the scheduler view's time interval. */ + startDayHour?: number; + /** Specifies an end hour in the scheduler view's time interval. */ + endDayHour?: number; + /** Specifies whether the scheduler data can be edited at runtime. */ + editing?: boolean; + /** Specifies an array of resources available in the scheduler. */ + resources?: Array<{ + /** Indicates whether or not several resources of this kind can be assigned to an appointment. */ + allowMultiple?: boolean; + /** Indicates whether or not resources of this kind have priority in the color identification of the appointments that have resources of different kinds assigned. */ + mainColor?: boolean; + /** A data source used to fetch resources to be available in the scheduler. */ + dataSource?: any; + /** Specifies the resource object field whose value is displayed by the Resource editor in the Appointment popup window. */ + displayExpr?: any; + /** Specifies the resource object field that is used as a value of the Resource editor in the Appointment popup window. */ + valueExpr?: any; + /** The name of the appointment object field that specifies a resource of this kind. */ + field?: string; + /** Specifies the label of the Appointment popup window field that allows end users to assign a resource of this kind. */ + label?: string; + }>; + /** A handler for the AppoinmentAdding event. */ + onAppointmentAdding?: Function; + /** A handler for the appointmentAdded event. */ + onAppointmentAdded?: Function; + /** A handler for the AppoinmentUpdating event. */ + onAppointmentUpdating?: Function; + /** A handler for the appointmentUpdated event. */ + onAppointmentUpdated?: Function; + /** A handler for the AppoinmentDeleting event. */ + onAppointmentDeleting?: Function; + /** A handler for the appointmentDeleted event. */ + onAppointmentDeleted?: Function; + /** A handler for the appointmentRendered event. */ + onAppointmentRendered?: Function; + } + /** A widget that displays scheduled data using different views and provides the capability to load, add and edit appointments. */ + export class dxScheduler extends Widget { + constructor(element: JQuery, options?: dxSchedulerOptions); + constructor(element: Element, options?: dxSchedulerOptions); + /** Add the appointment defined by the object passed as a parameter to the data associated with the widget. */ + addAppointment(appointment: Object): void; + /** Updates the appointment specified by the first method parameter by the appointment object specified by the second method parameter in the the data associated with the widget. */ + updateAppointment(target: Object, appointment: Object): void; + /** Deletes the appointment defined by the parameter from the the data associated with the widget. */ + deleteAppointment(appointment: Object): void; + } + export interface dxColorBoxOptions extends dxDropDownEditorOptions { + /** Specifies the text displayed on the button that applies changes and closes the drop-down editor. */ + applyButtonText?: string; + applyValueMode?: string; + /** Specifies the text displayed on the button that cancels changes and closes the drop-down editor. */ + cancelButtonText?: string; + /** Specifies whether or not the widget value includes the alpha channel component. */ + editAlphaChannel?: boolean; + /** Specifies the size of a step by which a handle is moved using a keyboard shortcut. */ + keyStep?: number; + } + /** A widget used to specify a color value. */ + export class dxColorBox extends dxDropDownEditor { + constructor(element: JQuery, options?: dxColorBoxOptions); + constructor(element: Element, options?: dxColorBoxOptions); + } + export interface dxColorPickerOptions extends dxColorBoxOptions { } + /** + * A widget used to specify a color value. + * @deprecated Use the dxColorBox widget instead + */ + export class dxColorPicker extends dxColorBox { + constructor(element: JQuery, options?: dxColorPickerOptions); + constructor(element: Element, options?: dxColorPickerOptions); + } + export interface dxTreeViewOptions extends CollectionWidgetOptions { + /** Specifies whether or not to animate item collapsing and expanding. */ + animationEnabled?: boolean; + /** Specifies whether a nested or plain array is used as a data source. */ + dataStructure?: string; + /** Specifies whether or not a user can expand all tree view items by the "*" hot key. */ + expandAllEnabled?: boolean; + /** + * An array of currently expanded item objects. + * @deprecated Use item.expanded field instead + */ + expandedItems?: Array; + /** Specifies whether or not a check box is displayed at each tree view item. */ + showCheckBoxes?: boolean; + /** Specifies whether or not to select nodes recursively. */ + selectNodesRecursive?: boolean; + /** Specifies whether the "Select All" check box is displayed over the tree view. */ + selectAllEnabled?: boolean; + /** Specifies the text displayed at the "Select All" check box. */ + selectAllText?: string; + /** Specifies the name of the data source item field used as a key. */ + keyExpr?: any; + /** Specifies the name of the data source item field whose value is displayed by the widget. */ + displayExpr?: any; + /** Specifies the name of the data source item field whose value defines whether or not the corresponding node is selected. */ + selectedExpr?: any; + /** Specifies the name of the data source item field whose value defines whether or not the corresponding node is expanded. */ + expandedExpr?: any; + /** Specifies the name of the data source item field that contains an array of nested items. */ + itemsExpr?: any; + /** Specifies the name of the data source item field that holds the key of the parent item. */ + parentIdExpr?: any; + /** Specifies the name of the data source item field whose value defines whether or not the corresponding node is disabled. */ + disabledExpr?: any; + /** Specifies the name of the data source item field whose value defines whether or not the corresponding node includes child nodes. */ + hasItemsExpr?: any; + /** Specifies if the virtual mode is enabled. */ + virtualModeEnabled?: boolean; + /** Specifies the parent ID value of the root item. */ + rootValue?: any; + /** A string value specifying available scrolling directions. */ + scrollDirection?: string; + /** A handler for the itemSelected event. */ + onItemSelected?: Function; + /** A handler for the itemExpanded event. */ + onItemExpanded?: Function; + /** A handler for the itemCollapsed event. */ + onItemCollapsed?: Function; + hoverStateEnabled?: boolean; + focusStateEnabled?: boolean; + } + /** A widget displaying specified data items as a tree. */ + export class dxTreeView extends CollectionWidget { + constructor(element: JQuery, options?: dxTreeViewOptions); + constructor(element: Element, options?: dxTreeViewOptions); + /** Updates the tree view scrollbars according to the current size of the widget content. */ + updateDimensions(): JQueryPromise; + /** Selects the specified item. */ + selectItem(itemElement: any): void; + /** Unselects the specified item. */ + unselectItem(itemElement: any): void; + /** Expands the specified item. */ + expandItem(itemElement: any): void; + /** Collapses the specified item. */ + collapseItem(itemElement: any): void; + /** Returns all nodes of the tree view. */ + getNodes(): Array; + /** Selects all widget items. */ + selectAll(): void; + /** Unselects all widget items. */ + unselectAll(): void; + } + export interface dxMenuBaseOptions extends CollectionWidgetOptions { + /** An object that defines the animation options of the widget. */ + animation?: fx.AnimationOptions; + /** A Boolean value specifying whether or not the widget changes its state when interacting with a user. */ + activeStateEnabled?: boolean; + /** Specifies the name of the CSS class associated with the menu. */ + cssClass?: string; + /** Holds an array of menu items. */ + items?: Array; + /** Specifies whether or not an item becomes selected if an end-user clicks it. */ + selectionByClick?: boolean; + /** Specifies the selection mode supported by the menu. */ + selectionMode?: string; + /** Specifies options of submenu showing and hiding. */ + showSubmenuMode?: { + /** Specifies the mode name. */ + name?: string; + /** Specifies the delay of submenu show and hiding. */ + delay?: { + /** The time span after which the submenu is shown. */ + show?: number; + /** The time span after which the submenu is hidden. */ + hide?: number; + }; + }; + /** A Boolean value specifying whether or not the widget changes its state when being hovered by an end user. */ + hoverStateEnabled?: boolean; + } + export class dxMenuBase extends CollectionWidget { + constructor(element: JQuery, options?: dxMenuBaseOptions); + constructor(element: Element, options?: dxMenuBaseOptions); + /** Selects the specified item. */ + selectItem(itemElement: any): void; + /** Unselects the specified item. */ + unselectItem(itemElement: any): void; + } + export interface dxMenuOptions extends dxMenuBaseOptions { + /** Specifies whether or not the submenu is hidden when the mouse pointer leaves it. */ + hideSubmenuOnMouseLeave?: boolean; + /** Specifies whether the menu has horizontal or vertical orientation. */ + orientation?: string; + /** Specifies options for showing and hiding the first level submenu. */ + showFirstSubmenuMode?: { + /** Specifies the mode name. */ + name?: string; + /** Specifies the delay of submenu showing and hiding. */ + delay?: { + /** The time span after which the submenu is shown. */ + show?: number; + /** The time span after which the submenu is hidden. */ + hide?: number; + }; + }; + /** Specifies the direction at which the submenus are displayed. */ + submenuDirection?: string; + /** A handler for the submenuHidden event. */ + onSubmenuHidden?: Function; + submenuHiddenAction?: Function; + /** A handler for the submenuHiding event. */ + onSubmenuHiding?: Function; + submenuHidingAction?: Function; + /** A handler for the submenuShowing event. */ + onSubmenuShowing?: Function; + submenuShowingAction?: Function; + /** A handler for the submenuShown event. */ + onSubmenuShown?: Function; + submenuShownAction?: Function; + } + /** A menu widget. */ + export class dxMenu extends dxMenuBase { + constructor(element: JQuery, options?: dxMenuOptions); + constructor(element: Element, options?: dxMenuOptions); + } + export interface dxContextMenuOptions extends dxMenuBaseOptions { + /** Holds an object that specifies options of alternative menu invocation. */ + alternativeInvocationMode?: { + /** Specifies whether or not the standard context menu invocation (on a right mouse click or on a long tap) is disabled. */ + enabled?: Boolean; + /** Specifies the element used to invoke the context menu. */ + invokingElement?: any; + }; + /** A handler for the hidden event. */ + onHidden?: Function; + /** A handler for the hiding event. */ + onHiding?: Function; + /** A handler for the positioning event. */ + onPositioning?: Function; + /** A handler for the showing event. */ + onShowing?: Function; + /** A handler for the shown event. */ + onShown?: Function; + /** An object defining widget positioning options. */ + position?: PositionOptions; + /** Specifies the direction at which submenus are displayed. */ + submenuDirection?: string; + /** The target element associated with a popover. */ + target?: any; + /** A Boolean value specifying whether or not the widget is visible. */ + visible?: boolean; + } + /** A context menu widget. */ + export class dxContextMenu extends dxMenuBase { + constructor(element: JQuery, options?: dxContextMenuOptions); + constructor(element: Element, options?: dxContextMenuOptions); + /** Toggles the visibility of the widget. */ + toggle(showing: boolean): JQueryPromise; + /** Shows the widget. */ + show(): JQueryPromise; + /** Hides the widget. */ + hide(): JQueryPromise; + } + export interface dxRemoteOperations { + /** Specifies whether or not filtering must be performed on the server side. */ + filtering?: boolean; + /** Specifies whether or not paging must be performed on the server side. */ + paging?: boolean; + /** Specifies whether or not sorting must be performed on the server side. */ + sorting?: boolean; + } + export interface dxDataGridColumn { + /** Specifies the content alignment within column cells. */ + alignment?: string; + /** Specifies whether the values in a column can be edited at runtime. Setting this option makes sense only when editing is enabled for a grid. */ + allowEditing?: boolean; + /** Specifies whether or not a column can be used for filtering grid records. Setting this option makes sense only when the filter row and column header filtering are visible. */ + allowFiltering?: boolean; + /** Specifies whether or not the column can be anchored to a grid edge by end users. Setting this option makes sense only when the columnFixing | enabled option is set to true. */ + allowFixing?: boolean; + /** Specifies if a column can be used for searching grid records. Setting this option makes sense only when the search panel is visible. */ + allowSearch?: boolean; + /** Specifies whether a column can be used for grouping grid records at runtime. Setting this option makes sense only when the group panel is visible. */ + allowGrouping?: boolean; + /** Specifies whether or not a column can be hidden by a user. Setting this option makes sense only when the column chooser is visible. */ + allowHiding?: boolean; + /** Specifies whether or not a particular column can be used in column reordering. Setting this option makes sense only when the allowColumnReordering option is set to true. */ + allowReordering?: boolean; + /** Specifies whether or not a particular column can be resized by a user. Setting this option makes sense only when the allowColumnResizing option is true. */ + allowResizing?: boolean; + /** Specifies whether grid records can be sorted by a specific column at runtime. Setting this option makes sense only when the sorting mode differs from none. */ + allowSorting?: boolean; + /** Specifies whether groups appear expanded or not when records are grouped by a specific column. Setting this option makes sense only when grouping is allowed for this column. */ + autoExpandGroup?: boolean; + /** Specifies a callback function that returns a value to be displayed in a column cell. */ + calculateCellValue?: (rowData: Object) => string; + /** Specifies a callback function that defines filters for customary calculated grid cells. */ + calculateFilterExpression?: (filterValue: any, selectedFilterOperation: string) => Array; + /** Specifies a caption for a column. */ + caption?: string; + /** Specifies a custom template for grid column cells. */ + cellTemplate?: any; + /** Specifies a CSS class to be applied to a column. */ + cssClass?: string; + /** Specifies a callback function that determines values for column cells to be used for grouping. */ + calculateGroupValue?: any; + /** Specifies a callback function that returns a value or the name of the field to be used for sorting column cells. */ + calculateSortValue?: any; + /** Specifies a callback function that returns the text to be displayed in the cells of a column. */ + customizeText?: (cellInfo: { value: any; valueText: string }) => string; + /** Specifies the field of a data source that provides data for a column. */ + dataField?: string; + /** Specifies the required type of column values. */ + dataType?: string; + /** Specifies a custom template for the cell of a grid column when it is in an editing state. */ + editCellTemplate?: any; + /** Specifies whether HTML tags are displayed as plain text or applied to the values of the column. */ + encodeHtml?: boolean; + /** In a boolean column, replaces all false items with a specified text. */ + falseText?: string; + /** Specifies the set of available filter operations. */ + filterOperations?: Array; + /** Specifies a filter value for a column. */ + filterValue?: any; + /** Specifies initial filter values for the column's header filter. */ + filterValues?: Array; + /** Specifies whether to include or exclude the records with the values selected in the column's header filter. */ + filterType?: string; + /** Indicates whether the column takes part in horizontal grid scrolling or is anchored to a grid edge. */ + fixed?: boolean; + /** Specifies the grid edge to which the column is anchored. */ + fixedPosition?: string; + /** Specifies a format for the values displayed in a column. */ + format?: string; + /** Specifies a custom template for the group cell of a grid column. */ + groupCellTemplate?: any; + /** Specifies the index of a column when grid records are grouped by the values of this column. */ + groupIndex?: number; + /** Specifies a custom template for the header of a grid column. */ + headerCellTemplate?: any; + /** Specifies options of a lookup column. */ + lookup?: { + /** Specifies whether or not a user can nullify values of a lookup column. */ + allowClearing?: boolean; + /** +Specifies the data source providing data for a lookup column. + */ + dataSource?: any; + /** Specifies the expression defining the data source field whose values must be displayed. */ + displayExpr?: any; + /** Specifies the expression defining the data source field whose values must be replaced. */ + valueExpr?: string; + }; + /** Specifies a precision for formatted values displayed in a column. */ + precision?: number; + /** Specifies a filter operation applied to a column. */ + selectedFilterOperation?: string; + /** Specifies whether or not the column displays its values by using editors. */ + showEditorAlways?: boolean; + /** Specifies whether or not to display the column when grid records are grouped by it. */ + showWhenGrouped?: boolean; + /** Specifies the index of a column when grid records are sorted by the values of this column. */ + sortIndex?: number; + /** Specifies the initial sort order of column values. */ + sortOrder?: string; + /** In a boolean column, replaces all true items with a specified text. */ + trueText?: string; + /** Specifies whether a column is visible or not. */ + visible?: boolean; + /** Specifies the sequence number of the column in the grid. */ + visibleIndex?: number; + /** Specifies a column width in pixels or percentages. */ + width?: any; + /** Specifies an array of validation rules to be checked when updating column cell values. */ + validationRules?: Array; + /** Specifies whether or not to display the header of a hidden column in the column chooser. */ + showInColumnChooser?: boolean; + /** Specifies the identifier of the column. */ + name?: string; + } + export interface dxDataGridOptions extends WidgetOptions { + /** Specifies whether the outer borders of the grid are visible or not. */ + showBorders?: boolean; + /** Indicates whether to show the error row for the grid. */ + errorRowEnabled?: boolean; + /** A handler for the rowValidating event. */ + onRowValidating?: (e: Object) => void; + /** A handler for the contextMenuPreparing event. */ + onContextMenuPreparing?: (e: Object) => void; + initNewRow?: (e: { data: Object }) => void; + /** A handler for the initNewRow event. */ + onInitNewRow?: (e: { data: Object }) => void; + rowInserted?: (e: { data: Object; key: any }) => void; + /** A handler for the rowInserted event. */ + onRowInserted?: (e: { data: Object; key: any }) => void; + rowInserting?: (e: { data: Object; cancel: boolean }) => void; + /** A handler for the rowInserting event. */ + onRowInserting?: (e: { data: Object; cancel: boolean }) => void; + rowRemoved?: (e: { data: Object; key: any }) => void; + /** A handler for the rowRemoved event. */ + onRowRemoved?: (e: { data: Object; key: any }) => void; + rowRemoving?: (e: { data: Object; key: any; cancel: boolean }) => void; + /** A handler for the rowRemoving event. */ + onRowRemoving?: (e: { data: Object; key: any; cancel: boolean }) => void; + rowUpdated?: (e: { data: Object; key: any }) => void; + /** A handler for the rowUpdated event. */ + onRowUpdated?: (e: { data: Object; key: any }) => void; + rowUpdating?: (e: { oldData: Object; newData: Object; key: any; cancel: boolean }) => void; + /** A handler for the rowUpdating event. */ + onRowUpdating?: (e: { oldData: Object; newData: Object; key: any; cancel: boolean }) => void; + /** Enables a hint that appears when a user hovers the mouse pointer over a cell with truncated content. */ + cellHintEnabled?: boolean; + /** Specifies whether or not grid columns can be reordered by a user. */ + allowColumnReordering?: boolean; + /** Specifies whether or not grid columns can be resized by a user. */ + allowColumnResizing?: boolean; + cellClick?: any; + /** A handler for the cellClick event. */ + onCellClick?: any; + cellHoverChanged?: (e: Object) => void; + /** A handler for the cellHoverChanged event. */ + onCellHoverChanged?: (e: Object) => void; + cellPrepared?: (e: Object) => void; + /** A handler for the cellPrepared event. */ + onCellPrepared?: (e: Object) => void; + /** Specifies whether or not the width of grid columns depends on column content. */ + columnAutoWidth?: boolean; + /** Specifies the options of a column chooser. */ + columnChooser?: { + /** Specifies text displayed by the column chooser panel when it does not contain any columns. */ + emptyPanelText?: string; + /** Specifies whether a user can invoke the column chooser or not. */ + enabled?: boolean; + /** Specifies the height of the column chooser panel. */ + height?: number; + /** Specifies text displayed in the title of the column chooser panel. */ + title?: string; + /** Specifies the width of the column chooser panel. */ + width?: number; + }; + /** Specifies options for column fixing. */ + columnFixing?: { + /** Indicates if column fixing is enabled. */ + enabled?: boolean; + /** Contains options that specify texts for column-fixing related commands in the column header's context menu. */ + texts?: { + /** Specifies text for a context menu item that fixes the column for which the context menu is invoked. */ + fix?: string; + /** Specifies text for a context menu item that unfixes the column for which the context menu is invoked. */ + unfix?: string; + /** Specifies text for a context menu subitem that fixes a column, for which the context menu is invoked, to the left grid edge. */ + leftPosition?: string; + /** Specifies text for a context menu subitem that fixes a column, for which the context menu is invoked, to the right grid edge. */ + rightPosition?: string; + }; + }; + /** Specifies options for filtering using a column header filter. */ + headerFilter?: { + /** Indicates whether or not the column header filter button is visible. */ + visible?: boolean; + /** Specifies the height of the dropdown menu invoked when using a column header filter. */ + height?: number; + /** Specifies the width of the dropdown menu invoked when using a column header filter. */ + width?: number; + /** Contains options that specify texts for the dropdown menu invoked when you use a column header filter. */ + texts?: { + /** Specifies text for the item specifying an empty value in the column header filter's dropdown menu. */ + emptyValue?: string; + /** Specifies text for a button that closes the column header filter's dropdown menu and applies specified filtering. */ + ok?: string; + /** Specifies text for a button that closes the column header filter's dropdown menu without applying performed selection. */ + cancel?: string; + } + }; + /** +An array of grid columns. + */ + columns?: Array; + onContentReady?: Function; + contentReadyAction?: Function; + /** Specifies a function that customizes grid columns after they are created. */ + customizeColumns?: (columns: Array) => void; + dataErrorOccurred?: (errorObject: Error) => void; + /** Specifies a data source for the grid. */ + dataSource?: any; + editingStart?: (e: { + data: Object; + key: any; + cancel: boolean; + column: dxDataGridColumn + }) => void; + /** A handler for the editingStart event. */ + onEditingStart?: (e: { + data: Object; + key: any; + cancel: boolean; + column: dxDataGridColumn + }) => void; + editorPrepared?: (e: Object) => void; + /** A handler for the editorPrepared event. */ + onEditorPrepared?: (e: Object) => void; + editorPreparing?: (e: Object) => void; + /** A handler for the editorPreparing event. */ + onEditorPreparing?: (e: Object) => void; + /** Contains options that specify how grid content can be changed. */ + editing?: { + /** Specifies whether or not grid records can be edited at runtime. */ + editEnabled?: boolean; + /** Specifies how grid values can be edited manually. */ + editMode?: string; + /** Specifies whether or not new records can be inserted into a grid. */ + insertEnabled?: boolean; + /** Specifies whether or not records can be deleted from a grid. */ + removeEnabled?: boolean; + /** Contains options that specify texts for editing-related grid controls. */ + texts?: { + /** Specifies text for a hint that appears when a user hovers the mouse pointer over the "Save" button. Setting this option makes sense only when the editMode option is set to batch. */ + saveAllChanges?: string; + /** Specifies text for a cancel button displayed when a row is in the editing state. Setting this option makes sense only when the editEnabled option is set to true. */ + cancelRowChanges?: string; + /** Specifies text for a hint that appears when a user hovers the mouse pointer over the "Revert" button. Setting this option makes sense only when the editMode option is set to batch. */ + cancelAllChanges?: string; + /** Specifies a message to be displayed by a confirmation window. Setting this option makes sense only when the edit mode is "row". */ + confirmDeleteMessage?: string; + /** Specifies text to be displayed in the title of a confirmation window. Setting this option makes sense only when the edit mode is "row". */ + confirmDeleteTitle?: string; + /** Specifies text for a button that deletes a row from a grid. Setting this option makes sense only when the removeEnabled option is set to true. */ + deleteRow?: string; + /** Specifies text for a hint that appears when a user hovers the mouse pointer over the "Add" button. Setting this option makes sense only when the insertEnabled option is true. */ + addRow?: string; + /** Specifies text for a button that turns a row into the editing state. Setting this option makes sense only when the editEnabled option is set to true. */ + editRow?: string; + /** Specifies text for a save button displayed when a row is in the editing state. Setting this option makes sense only when the editEnabled option is set to true. */ + saveRowChanges?: string; + /** Specifies text for a button that recovers a deleted row. Setting this option makes sense only if the grid uses the batch edit mode and the removeEnabled option is set to true. */ + undeleteRow?: string; + }; + }; + /** Specifies filter row options. */ + filterRow?: { + /** Specifies when to apply a filter. */ + applyFilter?: string; + /** Specifies text for the hint that pops up when a user hovers the mouse pointer over the "Apply Filter" button. */ + applyFilterText?: string; + /** Specifies descriptions for filter operations. */ + operationDescriptions?: { + "=": string; + "<>": string; + "<": string; + "<=": string; + ">": string; + ">=": string; + "startswith": string; + "contains": string; + "notcontains": string; + "endswith": string; + }; + /** Specifies text for the reset operation in a filter list. */ + resetOperationText?: string; + /** Specifies text for the operation of clearing the applied filter when a select box is used. */ + showAllText?: string; + /** Specifies whether or not an icon that allows the user to choose a filter operation is visible. */ + showOperationChooser?: boolean; + /** Specifies whether the filter row is visible or not. */ + visible?: boolean; + }; + /** Specifies the behavior of grouped grid records. */ + grouping?: { + /** Specifies whether the user can collapse grouped records in a grid or not. */ + allowCollapsing?: boolean; + /** Specifies whether groups appear expanded or not. */ + autoExpandAll?: boolean; + /** Specifies the message displayed in a group row when the corresponding group is continued from the previous page. */ + groupContinuedMessage?: string; + /** +Specifies the message displayed in a group row when the corresponding group continues on the next page. + */ + groupContinuesMessage?: string; + }; + /** Specifies options that configure the group panel. */ + groupPanel?: { + /** Specifies whether columns can be dragged onto or from the group panel. */ + allowColumnDragging?: boolean; + /** Specifies text displayed by the group panel when it does not contain any columns. */ + emptyPanelText?: string; + /** Specifies whether the group panel is visible or not. */ + visible?: boolean; + }; + /** Specifies options configuring the load panel. */ + loadPanel?: { + /** Specifies whether to show the load panel or not. */ + enabled?: boolean; + /** Specifies the height of the load panel in pixels. */ + height?: number; + /** Specifies a URL pointing to an image to be used as a loading indicator. */ + indicatorSrc?: string; + /** Specifies whether or not a loading indicator must be displayed on the load panel. */ + showIndicator?: boolean; + /** Specifies whether or not the pane of the load panel must be displayed. */ + showPane?: boolean; + /** Specifies text displayed by the load panel. */ + text?: string; + /** Specifies the width of the load panel in pixels. */ + width?: number; + }; + /** Specifies text displayed when a grid does not contain any records. */ + noDataText?: string; + /** Specifies the options of a grid pager. */ + pager?: { + /** Specifies the page sizes that can be selected at runtime. */ + allowedPageSizes?: any; + /** Specifies whether to show the page size selector or not. */ + showPageSizeSelector?: boolean; + /** Specifies whether to show the pager or not. */ + visible?: any; + /** Specifies the text accompanying the page navigator. */ + infoText?: string; + /** Specifies whether or not to display the text accompanying the page navigator. This text is specified by the infoText option. */ + showInfo?: boolean; + /** Specifies whether or not to display buttons that switch the grid to the previous or next page. */ + showNavigationButtons?: boolean; + }; + /** Specifies paging options. */ + paging?: { + /** Specifies whether dxDataGrid loads data page by page or all at once. */ + enabled?: boolean; + /** Specifies the grid page that should be displayed by default. */ + pageIndex?: number; + /** Specifies the size of grid pages. */ + pageSize?: number; + }; + /** Specifies whether or not grid rows must be shaded in a different way. */ + rowAlternationEnabled?: boolean; + rowClick?: any; + /** A handler for the rowClick event. */ + onRowClick?: any; + rowPrepared?: (e: Object) => void; + /** A handler for the rowPrepared event. */ + onRowPrepared?: (e: Object) => void; + /** Specifies a custom template for grid rows. */ + rowTemplate?: any; + /** A configuration object specifying scrolling options. */ + scrolling?: { + /** Specifies the scrolling mode. */ + mode?: string; + /** Specifies whether or not a grid must preload pages adjacent to the current page when using virtual scrolling. */ + preloadEnabled?: boolean; + }; + /** Specifies options of the search panel. */ + searchPanel?: { + /** Specifies whether or not search strings in the located grid records should be highlighted. */ + highlightSearchText?: boolean; + /** Specifies text displayed by the search panel when no search string was typed. */ + placeholder?: string; + /** Specifies whether the search panel is visible or not. */ + visible?: boolean; + /** Specifies the width of the search panel in pixels. */ + width?: number; + /** Sets a search string for the search panel. */ + text?: string; + }; + /** Specifies the operations that must be performed on the server side. */ + remoteOperations?: any; + /** Allows you to sort groups according to the values of group summary items. */ + sortByGroupSummaryInfo?: Array<{ + /** Specifies the group summary item whose values must be used to sort groups. */ + summaryItem?: string; + /** Specifies the identifier of the column that must be used in grouping so that sorting by group summary item values be applied. */ + groupColumn?: string; + /** Specifies the sort order of group summary item values. */ + sortOrder?: string; + }>; + /** Allows you to build a master-detail interface in the grid. */ + masterDetail?: { + /** Enables an end-user to expand/collapse detail sections. */ + enabled?: boolean; + /** Specifies whether detail sections appear expanded or collapsed. */ + autoExpandAll?: boolean; + /** Specifies the template for detail sections. */ + template?: any; + }; + /** Specifies options for exporting grid data. */ + export?: { + /** Indicates if the export feature is enabled in the grid. */ + enabled?: boolean; + /** Specifies a default name for the file to which grid data is exported. */ + fileName?: string; + /** Specifies whether to enable Excel filtering for the exported data in the resulting XLSX file. */ + excelFilterEnabled?: boolean; + /** Specifies whether to enable word wrapping for the exported data in the resulting XLSX file. */ + excelWrapTextEnabled?: boolean; + /** Specifies the URL of the server-side proxy that streams the resulting file to the end user to enable export in IE8, IE9 and Safari browsers. */ + proxyUrl?: string; + /** Indicates whether to allow end users to export not only the data displayed in the grid, but the selected rows only. */ + allowExportSelectedData?: boolean; + /** Contains options that specify texts for the export-related commands and hints. */ + texts?: { + /** Specifies text for the Export button when this button invokes a dropdown menu so you can choose the required export format. */ + exportTo?: string; + /** Specifies text for the Export button when this button exports to the XSLX format. */ + exportToExcel?: string; + /** Specifies text for the item in the Export dropdown menu that exports grid data to Excel. */ + excelFormat?: string; + /** Specifies text for the option in the Export dropdown menu that allows you to choose whether to export all the grid data or the selected rows only. */ + selectedRows?: string; + } + }; + /** Specifies the keys of the records that must appear selected initially. */ + selectedRowKeys?: Array; + /** Specifies options of runtime selection. */ + selection?: { + /** Specifies whether the user can select all grid records at once. */ + allowSelectAll?: boolean; + /** Specifies the selection mode. */ + mode?: string; + }; + selectionChanged?: (e: { + currentSelectedRowKeys: Array; + currentDeselectedRowKeys: Array; + selectedRowKeys: Array; + selectedRowsData: Array; + }) => void; + /** A handler for the dataErrorOccured event. */ + onDataErrorOccurred?: (e: { error: Error }) => void; + /** A handler for the selectionChanged event. */ + onSelectionChanged?: (e: { + currentSelectedRowKeys: Array; + currentDeselectedRowKeys: Array; + selectedRowKeys: Array; + selectedRowsData: Array; + }) => void; + /** A handler for the exporting event. */ + onExporting?: (e: { + fileName: string; + format: string; + cancel: boolean; + }) => void; + /** A handler for the exported event. */ + onExported?: (e: Object) => void; + /** A handler for the keyDown event. */ + onKeyDown?: (e: Object) => void; + /** A handler for the rowExpanding event. */ + onRowExpanding?: (e: Object) => void; + /** A handler for the rowExpanded event. */ + onRowExpanded?: (e: Object) => void; + /** A handler for the rowCollapsing event. */ + onRowCollapsing?: (e: Object) => void; + /** A handler for the rowCollapsed event. */ + onRowCollapsed?: (e: Object) => void; + /** Specifies whether column headers are visible or not. */ + showColumnHeaders?: boolean; + /** Specifies whether or not vertical lines separating one grid column from another are visible. */ + showColumnLines?: boolean; + /** Specifies whether or not horizontal lines separating one grid row from another are visible. */ + showRowLines?: boolean; + /** Specifies options of runtime sorting. */ + sorting?: { + /** Specifies text for the context menu item that sets an ascending sort order in a column. */ + ascendingText?: string; + /** Specifies text for the context menu item that resets sorting settings for a column. */ + clearText?: string; + /** Specifies text for the context menu item that sets a descending sort order in a column. */ + descendingText?: string; + /** Specifies the runtime sorting mode. */ + mode?: string; + }; + /** Specifies options of state storing. */ + stateStoring?: { + /** Specifies a callback function that performs specific actions on state loading. */ + customLoad?: () => JQueryPromise; + /** Specifies a callback function that performs specific actions on state saving. */ + customSave?: (gridState: Object) => void; + /** Specifies whether or not a grid saves its state. */ + enabled?: boolean; + /** Specifies the delay between the last change of a grid state and the operation of saving this state in milliseconds. */ + savingTimeout?: number; + /** Specifies a unique key to be used for storing the grid state. */ + storageKey?: string; + /** Specifies the type of storage to be used for state storing. */ + type?: string; + }; + /** Specifies the options of the grid summary. */ + summary?: { + /** Contains options that specify text patterns for summary items. */ + texts?: { + /** Specifies a pattern for the 'sum' summary items when they are displayed in the parent column. */ + sum?: string; + /** Specifies a pattern for the 'sum' summary items displayed in a group row or in any other column rather than the parent one. */ + sumOtherColumn?: string; + /** Specifies a pattern for the 'min' summary items when they are displayed in the parent column. */ + min?: string; + /** Specifies a pattern for the 'min' summary items displayed in a group row or in any other column rather than the parent one. */ + minOtherColumn?: string; + /** Specifies a pattern for the 'max' summary items when they are displayed in the parent column. */ + max?: string; + /** Specifies a pattern for the 'max' summary items displayed in a group row or in any other column rather than the parent one. */ + maxOtherColumn?: string; + /** Specifies a pattern for the 'avg' summary items when they are displayed in the parent column. */ + avg?: string; + /** Specifies a pattern for the 'avg' summary items displayed in a group row or in any other column rather than the parent one. */ + avgOtherColumn?: string; + /** Specifies a pattern for the 'count' summary items. */ + count?: string; + }; + /** Specifies items of the group summary. */ + groupItems?: Array<{ + /** Specifies the identifier of a summary item. */ + name?: string; + /** Specifies the column that provides data for a group summary item. */ + column?: string; + /** Customizes the text to be displayed in the summary item. */ + customizeText?: (itemInfo: { + value: any; + valueText: string; + }) => string; + /** Specifies a pattern for the summary item text. */ + displayFormat?: string; + /** Specifies a precision for the summary item value of a numeric format. */ + precision?: number; + /** Specifies whether or not a summary item must be displayed in the group footer. */ + showInGroupFooter?: boolean; + /** Indicates whether to display group summary items in brackets of the group row header or to align them by the corresponding columns within the group row. */ + alignByColumn?: boolean; + /** Specifies the column that must hold the summary item when this item is displayed in the group footer or aligned by a column in the group row. */ + showInColumn?: string; + /** Specifies how to aggregate data for a summary item. */ + summaryType?: string; + /** Specifies a format for the summary item value. */ + valueFormat?: string; + }>; + /** Specifies items of the total summary. */ + totalItems?: Array<{ + /** Specifies the identifier of a summary item. */ + name?: string; + /** Specifies the alignment of a summary item. */ + alignment?: string; + /** Specifies the column that provides data for a summary item. */ + column?: string; + /** Specifies a CSS class to be applied to a summary item. */ + cssClass?: string; + /** Customizes the text to be displayed in the summary item. */ + customizeText?: (itemInfo: { + value: any; + valueText: string; + }) => string; + /** Specifies a pattern for the summary item text. */ + displayFormat?: string; + /** Specifies a precision for the summary item value of a numeric format. */ + precision?: number; + /** Specifies the column that must hold the summary item. */ + showInColumn?: string; + /** Specifies how to aggregate data for a summary item. */ + summaryType?: string; + /** Specifies a format for the summary item value. */ + valueFormat?: string; + }>; + /** Allows you to use a custom aggregate function to calculate the value of a summary item. */ + calculateCustomSummary?: (options: { + component: dxDataGrid; + name?: string; + value: any; + totalValue: any; + summaryProcess: string + }) => void; + }; + /** Specifies whether text that does not fit into a column should be wrapped. */ + wordWrapEnabled?: boolean; + } + /** A data grid widget. */ + export class dxDataGrid extends Widget { + constructor(element: JQuery, options?: dxDataGridOptions); + constructor(element: Element, options?: dxDataGridOptions); + /** Ungroups grid records. */ + clearGrouping(): void; + /** Clears sorting settings of all grid columns at once. */ + clearSorting(): void; + /** Allows you to obtain a cell by its row index and the data field of its column. */ + getCellElement(rowIndex: number, dataField: string): any; + /** Allows you to obtain a cell by its row index and the visible index of its column. */ + getCellElement(rowIndex: number, visibleColumnIndex: number): any; + /** Returns the current state of the grid. */ + state(): Object; + /** Sets the grid state. */ + state(state: Object): void; + /** Allows you to obtain the row index by a data key. */ + getRowIndexByKey(key: any): number; + /** Allows you to obtain the data key by a row index. */ + getKeyByRowIndex(rowIndex: number): any; + /** Adds a new column to a grid. */ + addColumn(columnOptions: dxDataGridColumn): void; + /** Displays the load panel. */ + beginCustomLoading(messageText: string): void; + /** Discards changes made in a grid. */ + cancelEditData(): void; + /** Clears all the filters of a specific type applied to grid records. */ + clearFilter(): void; + /** Deselects all grid records. */ + clearSelection(): void; + /** Draws the cell being edited from the editing state. Use this method when the edit mode is batch. */ + closeEditCell(): void; + /** Collapses groups or master rows in a grid. */ + collapseAll(groupIndex?: number): void; + /** Returns the number of data columns in a grid. */ + columnCount(): number; + /** Returns the value of a specific column option. */ + columnOption(id: number, optionName: string): any; + /** Sets an option of a specific column. */ + columnOption(id: number, optionName: string, optionValue: any): void; + /** Returns the options of a column by an identifier. */ + columnOption(id: any): Object; + /** Sets several options of a column at once. */ + columnOption(id: any, options: Object): void; + /** Sets a specific cell into the editing state. */ + editCell(rowIndex: number, columnIndex: number): void; + /** Sets a specific row into the editing state. */ + editRow(rowIndex: number): void; + /** Hides the load panel. */ + endCustomLoading(): void; + /** Expands groups or master rows in a grid. */ + expandAll(groupIndex: number): void; + /** Allows you to find out whether a specific group or master row is expanded or collapsed. */ + isRowExpanded(key: any): boolean; + /** Allows you to expand a specific group or master row by its key. */ + expandRow(key: any): void; + /** Allows you to collapse a specific group or master row by its key. */ + collapseRow(key: any): void; + /** Applies a filter to the grid's data source. */ + filter(filterExpr?: any): void; + /** Returns a filter expression applied to the grid's data source using the filter(filterExpr) method. */ + filter(): any; + /** Returns a filter expression applied to the grid using all possible scenarious. */ + getCombinedFilter(): any; + /** Gets the keys of currently selected grid records. */ + getSelectedRowKeys(): Array; + /** Gets the data objects of currently selected grid records. */ + getSelectedRowsData(): Array; + /** Hides the column chooser panel. */ + hideColumnChooser(): void; + /** Adds a new data row to a grid. */ + insertRow(): void; + /** Returns the key corresponding to the passed data object. */ + keyOf(obj: Object): any; + /** Switches a grid to a specified page. */ + pageIndex(newIndex: number): void; + /** Gets the index of the current page. */ + pageIndex(): number; + /** Sets the page size. */ + pageSize(value: number): void; + /** Gets the current page size. */ + pageSize(): number; + /** Refreshes grid data. */ + refresh(): void; + /** Removes a specific row from a grid. */ + removeRow(rowIndex: number): void; + /** Saves changes made in a grid. */ + saveEditData(): void; + /** +Searches grid records by a search string. + */ + searchByText(text: string): void; + /** Selects all grid records. */ + selectAll(): void; + /** Deselects the rows that are currently selected within the applied filter. */ + deselectAll(): void; + /** Selects specific grid records. */ + selectRows(keys: Array, preserve: boolean): void; + /** Deselects specific grid records. */ + deselectRows(keys: Array): void; + /** Selects grid rows by indexes. */ + selectRowsByIndexes(indexes: Array): void; + /** Allows you to find out whether a row is selected or not. */ + isRowSelected(key: any): boolean; + /** Invokes the column chooser panel. */ + showColumnChooser(): void; + startSelectionWithCheckboxes(): boolean; + /** Returns the number of records currently held by a grid. */ + totalCount(): number; + /** Recovers a row deleted in the batch edit mode. */ + undeleteRow(rowIndex: number): void; + /** Allows you to obtain a data object by its key. */ + byKey(key: any): JQueryPromise; + /** Gets the value of a total summary item. */ + getTotalSummaryValue(summaryItemName: string): any; + /** Exports grid data to Excel. */ + exportToExcel(selectionOnly: boolean): void; + /** Updates the grid to the size of its content. */ + updateDimensions(): void; + /** Focuses the specified cell element in the grid. */ + focus(element?: JQuery): void; + } + export interface dxPivotGridOptions extends WidgetOptions { + onContentReady?: Function; + /** Specifies a data source for the pivot grid. */ + dataSource?: any; + /** Specifies whether or not the widget uses native scrolling. */ + useNativeScrolling?: any; + /** Allows an end-user to change sorting options. */ + allowSorting?: boolean; + /** Allows an end-user to sort columns by summary values. */ + allowSortingBySummary?: boolean; + /** Allows an end-user to change filtering options. */ + allowFiltering?: boolean; + /** Allows an end-user to expand/collapse all header items within a header level. */ + allowExpandAll?: boolean; + /** Specifies whether to display the Total rows. */ + showRowTotals?: boolean; + /** Specifies whether to display the Grand Total row. */ + showRowGrandTotals?: boolean; + /** Specifies whether to display the Total columns. */ + showColumnTotals?: boolean; + /** Specifies whether to display the Grand Total column. */ + showColumnGrandTotals?: boolean; + /** The Field Chooser configuration options. */ + fieldChooser?: { + /** Enables or disables the field chooser. */ + enabled?: boolean; + /** Specifies the field chooser layout. */ + layout?: number; + /** Specifies the text to display as a title of the field chooser popup window. */ + title?: string; + /** Specifies the field chooser width. */ + width?: number; + /** Specifies the field chooser height. */ + height?: number; + /** Strings that can be changed or localized in the pivot grid's integrated Field Chooser. */ + texts?: { + /** The string to display instead of Row Fields. */ + rowFields?: string; + /** The string to display instead of Column Fields. */ + columnFields?: string; + /** The string to display instead of Data Fields. */ + dataFields?: string; + /** The string to display instead of Filter Fields. */ + filterFields?: string; + /** The string to display instead of All Fields. */ + allFields?: string; + }; + } + /** Strings that can be changed or localized in the dxPivotGrid widget. */ + texts?: { + /** The string to display as a header of the Grand Total row and column. */ + grandTotal?: string; + /** The string to display as a header of the Total row and column. */ + total?: string; + /** Specifies the text displayed when a pivot grid does not contain any fields. */ + noData?: string; + /** The string to display as a Show Field Chooser context menu item. */ + showFieldChooser?: string; + /** The string to display as an Expand All context menu item. */ + expandAll?: string; + /** The string to display as a Collapse All context menu item. */ + collapseAll?: string; + /** The string to display as a Sort Column by Summary Value context menu item. */ + sortColumnBySummary?: string; + /** The string to display as a Sort Row by Summary Value context menu item. */ + sortRowBySummary?: string; + /** The string to display as a Remove All Sorting context menu item. */ + removeAllSorting?: string; + }; + /** The Load panel configuration options. */ + loadPanel?: { + /** Enables or disables the load panel. */ + enabled?: boolean; + /** Specifies the height of the load panel. */ + height?: number; + /** Specifies the URL pointing to an image that will be used as a load indicator. */ + indicatorSrc?: string; + /** Specifies whether or not to show a load indicator. */ + showIndicator?: boolean; + /** Specifies whether or not to show load panel background. */ + showPane?: boolean; + /** Specifies the text to display inside a load panel. */ + text?: string; + /** Specifies the width of the load panel. */ + width?: number; + }; + /** A handler for the cellClick event. */ + onCellClick?: (e: any) => void; + /** A handler for the cellPrepared event. */ + onCellPrepared?: (e: any) => void; + /** A handler for the contextMenuPreparing event. */ + onContextMenuPreparing?: (e: Object) => void; + } + /** A data summarization widget for multi-dimensional data analysis and data mining. */ + export class dxPivotGrid extends Widget { + constructor(element: JQuery, options?: dxPivotGridOptions); + constructor(element: Element, options?: dxPivotGridOptions); + /** Gets the PivotGridDataSource instance. */ + getDataSource(): DevExpress.data.PivotGridDataSource; + /** Updates the widget to the size of its content. */ + updateDimensions(): void; + } + export interface dxPivotGridFieldChooserOptions extends WidgetOptions { + /** Specifies the field chooser layout. */ + layout?: number; + /** The data source of a dxPivotGrid widget. */ + dataSource?: DevExpress.data.PivotGridDataSource; + onContentReady?: Function; + /** Strings that can be changed or localized in the dxPivotGridFieldChooser widget. */ + texts?: { + /** The string to display instead of Row Fields. */ + rowFields?: string; + /** The string to display instead of Column Fields. */ + columnFields?: string; + /** The string to display instead of Data Fields. */ + dataFields?: string; + /** The string to display instead of Filter Fields. */ + filterFields?: string; + /** The string to display instead of All Fields. */ + allFields?: string; + }; + } + /** A complementary widget for dxPivotGrid that allows you to manage data displayed in the dxPivotGrid. */ + export class dxPivotGridFieldChooser extends Widget { + constructor(element: JQuery, options?: dxPivotGridFieldChooserOptions); + constructor(element: Element, options?: dxPivotGridFieldChooserOptions); + /** Updates the widget to the size of its content. */ + updateDimensions(): void; + } +} +interface JQuery { + dxTreeView(): JQuery; + dxTreeView(options: "instance"): DevExpress.ui.dxTreeView; + dxTreeView(options: string): any; + dxTreeView(options: string, ...params: any[]): any; + dxTreeView(options: DevExpress.ui.dxTreeViewOptions): JQuery; + dxMenuBase(): JQuery; + dxMenuBase(options: "instance"): DevExpress.ui.dxMenuBase; + dxMenuBase(options: string): any; + dxMenuBase(options: string, ...params: any[]): any; + dxMenuBase(options: DevExpress.ui.dxMenuBaseOptions): JQuery; + dxMenu(): JQuery; + dxMenu(options: "instance"): DevExpress.ui.dxMenu; + dxMenu(options: string): any; + dxMenu(options: string, ...params: any[]): any; + dxMenu(options: DevExpress.ui.dxMenuOptions): JQuery; + dxContextMenu(): JQuery; + dxContextMenu(options: "instance"): DevExpress.ui.dxContextMenu; + dxContextMenu(options: string): any; + dxContextMenu(options: string, ...params: any[]): any; + dxContextMenu(options: DevExpress.ui.dxContextMenuOptions): JQuery; + dxColorBox(): JQuery; + dxColorBox(options: "instance"): DevExpress.ui.dxColorBox; + dxColorBox(options: string): any; + dxColorBox(options: string, ...params: any[]): any; + dxColorBox(options: DevExpress.ui.dxColorBoxOptions): JQuery; + dxDataGrid(): JQuery; + dxDataGrid(options: "instance"): DevExpress.ui.dxDataGrid; + dxDataGrid(options: string): any; + dxDataGrid(options: string, ...params: any[]): any; + dxDataGrid(options: DevExpress.ui.dxDataGridOptions): JQuery; + dxPivotGrid(): JQuery; + dxPivotGrid(options: "instance"): DevExpress.ui.dxPivotGrid; + dxPivotGrid(options: string): any; + dxPivotGrid(options: string, ...params: any[]): any; + dxPivotGrid(options: DevExpress.ui.dxPivotGridOptions): JQuery; + dxPivotGridFieldChooser(): JQuery; + dxPivotGridFieldChooser(options: "instance"): DevExpress.ui.dxPivotGridFieldChooser; + dxPivotGridFieldChooser(options: string): any; + dxPivotGridFieldChooser(options: string, ...params: any[]): any; + dxPivotGridFieldChooser(options: DevExpress.ui.dxPivotGridFieldChooserOptions): JQuery; + dxScheduler(): JQuery; + dxScheduler(options: "instance"): DevExpress.ui.dxScheduler; + dxScheduler(options: string): any; + dxScheduler(options: string, ...params: any[]): any; + dxScheduler(options: DevExpress.ui.dxSchedulerOptions): JQuery; +} +declare module DevExpress.framework { + /** An object used to store information on the views displayed in an application. */ + export class ViewCache { + viewRemoved: JQueryCallback; + /** Removes all the viewInfo objects from the cache. */ + clear(): void; + /** Obtains a viewInfo object from the cache by the specified key. */ + getView(key: string): Object; + /** Checks whether or not a viewInfo object is contained in the view cache under the specified key. */ + hasView(key: string): boolean; + /** Removes a viewInfo object from the cache by the specified key. */ + removeView(key: string): Object; + /** Adds the specified viewInfo object to the cache under the specified key. */ + setView(key: string, viewInfo: Object): void; + } + export interface dxCommandOptions extends DOMComponentOptions { + action?: any; + /** Specifies an action performed when the execute() method of the command is called. */ + onExecute?: any; + /** Indicates whether or not the widget that displays this command is disabled. */ + disabled?: boolean; + /** Specifies the name of the icon shown inside the widget associated with this command. */ + icon?: string; + iconSrc?: string; + /** The identifier of the command. */ + id?: string; + /** Specifies the title of the widget associated with this command. */ + title?: string; + /** Specifies the type of the button, if the command is rendered as a dxButton widget. */ + type?: string; + /** A Boolean value specifying whether or not the widget associated with this command is visible. */ + visible?: boolean; + } + /** A markup component used to define markup options for a command. */ + export class dxCommand extends DOMComponent { + constructor(element: JQuery, options: dxCommandOptions); + constructor(options: dxCommandOptions); + /** Executes the action associated with this command. */ + execute(): void; + } + /** An object responsible for routing. */ + export class Router { + /** Adds a routing rule to the list of registered rules. */ + register(pattern: string, defaults?: Object, constraints?: Object): void; + /** Decodes the specified URI to an object using the registered routing rules. */ + parse(uri: string): Object; + /** Formats an object to a URI. */ + format(obj: Object): string; + } + export interface StateManagerOptions { + /** A storage to which the state manager saves the application state. */ + storage?: Object; + } + /** An object used to store the current application state. */ + export class StateManager { + constructor(options?: StateManagerOptions); + /** Adds an object that implements an interface of a state source to the state manager's collection of state sources. */ + addStateSource(stateSource: Object): void; + /** Removes a specified state source from the state manager's collection of state sources. */ + removeStateSource(stateSource: Object): void; + /** Saves the current application state. */ + saveState(): void; + /** Restores the application state that has been saved by the saveState() method to the state storage. */ + restoreState(): void; + /** Removes the application state that has been saved by the saveState() method to the state storage. */ + clearState(): void; + } + export module html { + export var layoutSets: Array; + export var animationSets: { [animationSetName: string]: AnimationSet }; + export interface AnimationSet { + [animationName: string]: any + } + export interface HtmlApplicationOptions { + /** Specifies where the commands that are defined in the application's views must be displayed. */ + commandMapping?: Object; + /** Specifies whether or not view caching is disabled. */ + disableViewCache?: boolean; + /** An array of layout controllers that should be used to show application views in the current navigation context. */ + layoutSet?: any; + /** Specifies the animation presets that are used to animate different UI elements in the current application. */ + animationSet?: AnimationSet; + /** Specifies whether the current application must behave as a mobile or web application. */ + mode?: string; + /** Specifies the object that represents a root namespace of the application. */ + namespace?: Object; + /** Specifies application behavior when the user navigates to a root view. */ + navigateToRootViewMode?: string; + /** An array of dxCommand configuration objects used to define commands available from the application's global navigation. */ + navigation?: Array; + /** A state manager to be used in the application. */ + stateManager?: StateManager; + /** Specifies the storage to be used by the application's state manager to store the application state. */ + stateStorage?: Object; + /** Indicates whether on not to use the title of the previously displayed view as text on the Back button. */ + useViewTitleAsBackText?: boolean; + /** A custom view cache to be used in the application. */ + viewCache?: Object; + /** Specifies a limit for the views that can be cached. */ + viewCacheSize?: number; + /** Specifies options for the viewport meta tag of a mobile browser. */ + viewPort?: JQuery; + /** A custom router to be used in the application. */ + router?: Router; + } + /** An object used to manage views, as well as control the application life cycle. */ + export class HtmlApplication implements EventsMixin { + constructor(options: HtmlApplicationOptions); + afterViewSetup: JQueryCallback; + beforeViewSetup: JQueryCallback; + initialized: JQueryCallback; + navigating: JQueryCallback; + navigatingBack: JQueryCallback; + resolveLayoutController: JQueryCallback; + viewDisposed: JQueryCallback; + viewDisposing: JQueryCallback; + viewHidden: JQueryCallback; + viewRendered: JQueryCallback; + viewShowing: JQueryCallback; + viewShown: JQueryCallback; + /** Provides access to the ViewCache object. */ + viewCache: ViewCache; + /** An array of dxCommand components that are created based on the application's navigation option value. */ + navigation: Array; + /** Provides access to the StateManager object. */ + stateManager: StateManager; + /** Provides access to the Router object. */ + router: Router; + /** Navigates to the URI preceding the current one in the navigation history. */ + back(): void; + /** Returns a Boolean value indicating whether or not backwards navigation is currently possible. */ + canBack(): boolean; + /** Calls the clearState() method of the application's StateManager object. */ + clearState(): void; + /** Creates global navigation commands. */ + createNavigation(navigationConfig: Array): void; + /** Returns an HTML template of the specified view. */ + getViewTemplate(viewName: string): JQuery; + /** Returns a configuration object used to create a dxView component for a specified view. */ + getViewTemplateInfo(viewName: string): Object; + /** Adds a specified HTML template to a collection of view or layout templates. */ + loadTemplates(source: any): JQueryPromise; + /** Navigates to the specified URI. */ + navigate(uri?: any, options?: Object): void; + /** Renders navigation commands to the navigation command containers that are located in the layouts used in the application. */ + renderNavigation(): void; + /** Calls the restoreState() method of the application's StateManager object. */ + restoreState(): void; + /** Calls the saveState method of the application's StateManager object. */ + saveState(): void; + /** Provides access to the object that defines the current context to be considered when choosing an appropriate template for a view. */ + templateContext(): Object; + on(eventName: "initialized", eventHandler: () => void): HtmlApplication; + on(eventName: "afterViewSetup", eventHandler: (e: { + viewInfo: Object; + }) => void): HtmlApplication; + on(eventName: "beforeViewSetup", eventHandler: (e: { + viewInfo: Object; + }) => void): HtmlApplication; + on(eventName: "navigating", eventHandler: (e: { + currentUri: string; + uri: string; + cancel: boolean; + options: { + root: boolean; + target: string; + direction: string; + rootInDetailPane: boolean; + modal: boolean; + }; + }) => void): HtmlApplication; + on(eventName: "navigatingBack", eventHandler: (e: { + cancel: boolean; + isHardwareButton: boolean; + }) => void): HtmlApplication; + on(eventName: "resolveLayoutController", eventHandler: (e: { + viewInfo: Object; + layoutController: Object; + availableLayoutControllers: Array; + }) => void): HtmlApplication; + on(eventName: "viewDisposed", eventHandler: (e: { + viewInfo: Object; + }) => void): HtmlApplication; + on(eventName: "viewDisposing", eventHandler: (e: { + viewInfo: Object; + }) => void): HtmlApplication; + on(eventName: "viewHidden", eventHandler: (e: { + viewInfo: Object; + }) => void): HtmlApplication; + on(eventName: "viewRendered", eventHandler: (e: { + viewInfo: Object; + }) => void): HtmlApplication; + on(eventName: "viewShowing", eventHandler: (e: { + viewInfo: Object; + direction: string; + }) => void): HtmlApplication; + on(eventName: "viewShown", eventHandler: (e: { + viewInfo: Object; + direction: string; + }) => void): HtmlApplication; + on(eventName: string, eventHandler: Function): HtmlApplication; + on(events: { [eventName: string]: Function; }): HtmlApplication; + off(eventName: "initialized"): HtmlApplication; + off(eventName: "afterViewSetup"): HtmlApplication; + off(eventName: "beforeViewSetup"): HtmlApplication; + off(eventName: "navigating"): HtmlApplication; + off(eventName: "navigatingBack"): HtmlApplication; + off(eventName: "resolveLayoutController"): HtmlApplication; + off(eventName: "viewDisposed"): HtmlApplication; + off(eventName: "viewDisposing"): HtmlApplication; + off(eventName: "viewHidden"): HtmlApplication; + off(eventName: "viewRendered"): HtmlApplication; + off(eventName: "viewShowing"): HtmlApplication; + off(eventName: "viewShown"): HtmlApplication; + off(eventName: string): HtmlApplication; + off(eventName: "initialized", eventHandler: () => void): HtmlApplication; + off(eventName: "afterViewSetup", eventHandler: (e: { + viewInfo: Object; + }) => void): HtmlApplication; + off(eventName: "beforeViewSetup", eventHandler: (e: { + viewInfo: Object; + }) => void): HtmlApplication; + off(eventName: "navigating", eventHandler: (e: { + currentUri: string; + uri: string; + cancel: boolean; + options: { + root: boolean; + target: string; + direction: string; + rootInDetailPane: boolean; + modal: boolean; + }; + }) => void): HtmlApplication; + off(eventName: "navigatingBack", eventHandler: (e: { + cancel: boolean; + isHardwareButton: boolean; + }) => void): HtmlApplication; + off(eventName: "resolveLayoutController", eventHandler: (e: { + viewInfo: Object; + layoutController: Object; + availableLayoutControllers: Array; + }) => void): HtmlApplication; + off(eventName: "viewDisposed", eventHandler: (e: { + viewInfo: Object; + }) => void): HtmlApplication; + off(eventName: "viewDisposing", eventHandler: (e: { + viewInfo: Object; + }) => void): HtmlApplication; + off(eventName: "viewHidden", eventHandler: (e: { + viewInfo: Object; + }) => void): HtmlApplication; + off(eventName: "viewRendered", eventHandler: (e: { + viewInfo: Object; + }) => void): HtmlApplication; + off(eventName: "viewShowing", eventHandler: (e: { + viewInfo: Object; + direction: string; + }) => void): HtmlApplication; + off(eventName: "viewShown", eventHandler: (e: { + viewInfo: Object; + direction: string; + }) => void): HtmlApplication; + off(eventName: string, eventHandler: Function): HtmlApplication; + } + } +} +declare module DevExpress.viz.core { + export interface Border { + /** Sets a border color for a selected series. */ + color?: string; + /** Sets border visibility for a selected series. */ + visible?: boolean; + /** Sets a border width for a selected series. */ + width?: number; + } + export interface DashedBorder extends Border { + /** Specifies a dash style for the border of a selected series point. */ + dashStyle?: string; + } + export interface DashedBorderWithOpacity extends DashedBorder { + /** Specifies the opacity of the tooltip's border. */ + opacity?: number; + } + export interface Font { + /** Specifies the font color for a strip label. */ + color?: string; + /** Specifies the font family for a strip label. */ + family?: string; + /** Specifies the font opacity for a strip label. */ + opacity?: number; + /** Specifies the font size for a strip label. */ + size?: any; + /** Specifies the font weight for the text displayed in strips. */ + weight?: number; + } + export interface Hatching { + /** Specifies how to apply hatching to highlight a selected series. */ + direction?: string; + /** Specifies the opacity of hatching lines. */ + opacity?: number; + /** Specifies the distance between hatching lines in pixels. */ + step?: number; + /** Specifies the width of hatching lines in pixels. */ + width?: number; + } + export interface Margins { + /** Specifies the legend's bottom margin in pixels. */ + bottom?: number; + /** Specifies the legend's left margin in pixels. */ + left?: number; + /** Specifies the legend's right margin in pixels. */ + right?: number; + /** Specifies the legend's bottom margin in pixels. */ + top?: number; + } + export interface Size { + /** Specifies the width of the widget. */ + width?: number; + /** Specifies the height of the widget. */ + height?: number; + } + export interface Tooltip { + /** Specifies the length of the tooltip's arrow in pixels. */ + arrowLength?: number; + /** Specifies the appearance of the tooltip's border. */ + border?: viz.core.DashedBorderWithOpacity; + /** Specifies a color for the tooltip. */ + color?: string; + /** Specifies the z-index for tooltips. */ + zIndex?: number; + /** Specifies text and appearance of a set of tooltips. */ + customizeTooltip?: (arg: Object) => { color?: string; text?: string }; + /** Specifies whether or not the tooltip is enabled. */ + enabled?: boolean; + /** Specifies font options for the text displayed by the tooltip. */ + font?: Font; + /** Specifies a format for the text displayed by the tooltip. */ + format?: string; + /** Specifies the opacity of a tooltip. */ + opacity?: number; + /** Specifies a distance from the tooltip's left/right boundaries to the inner text in pixels. */ + paddingLeftRight?: number; + /** Specifies a distance from the tooltip's top/bottom boundaries to the inner text in pixels. */ + paddingTopBottom?: number; + /** Specifies a precision for formatted values displayed by the tooltip. */ + precision?: number; + /** Specifies options of the tooltip's shadow. */ + shadow?: { + /** Specifies the blur distance of the tooltip's shadow. */ + blur?: number; + /** Specifies the color of the tooltip's shadow. */ + color?: string; + /** Specifies the horizontal offset of the tooltip's shadow relative to the tooltip in pixels. */ + offsetX?: number; + /** Specifies the vertical offset of the tooltip's shadow relative to the tooltip in pixels. */ + offsetY?: number; + /** Specifies the opacity of the tooltip's shadow. */ + opacity?: number; + }; + } + export interface Animation { + /** Determines how long animation runs. */ + duration?: number; + /** Specifies the animation easing mode. */ + easing?: string; + /** Indicates whether or not animation is enabled. */ + enabled?: boolean; + } + export interface LoadingIndicator { + /** Specifies a color for the loading indicator background. */ + backgroundColor?: string; + /** Specifies font options for the loading indicator text. */ + font?: viz.core.Font; + /** Specifies whether to show the loading indicator or not. */ + show?: boolean; + /** Specifies a text to be displayed by the loading indicator. */ + text?: string; + } + export interface LegendBorder extends viz.core.DashedBorderWithOpacity { + /** Specifies a radius for the corners of the legend border. */ + cornerRadius?: number; + } + export interface BaseLegend { + /** Specifies the color of the legend's background. */ + backgroundColor?: string; + /** Specifies legend border settings. */ + border?: viz.core.LegendBorder; + /** Specifies how many columns must be taken to arrange legend items. */ + columnCount?: number; + /** Specifies the spacing between a pair of neighboring legend columns in pixels. */ + columnItemSpacing?: number; + /** Specifies font options for legend items. */ + font?: viz.core.Font; + /** Specifies the legend's position on the map. */ + horizontalAlignment?: string; + /** Specifies the alignment of legend items. */ + itemsAlignment?: string; + /** Specifies the position of text relative to the item marker. */ + itemTextPosition?: string; + /** Specifies the distance between the legend and the container borders in pixels. */ + margin?: viz.core.Margins; + /** Specifies the size of item markers in the legend in pixels. */ + markerSize?: number; + /** Specifies whether to arrange legend items horizontally or vertically. */ + orientation?: string; + /** Specifies the spacing between the legend left/right border and legend items in pixels. */ + paddingLeftRight?: number; + /** Specifies the spacing between the legend top/bottom border and legend items in pixels. */ + paddingTopBottom?: number; + /** Specifies how many rows must be taken to arrange legend items. */ + rowCount?: number; + /** Specifies the spacing between a pair of neighboring legend rows in pixels. */ + rowItemSpacing?: number; + /** Specifies the legend's position on the map. */ + verticalAlignment?: string; + /** Specifies whether or not the legend is visible on the map. */ + visible?: boolean; + } + export interface BaseWidgetOptions { + drawn?: (widget: Object) => void; + /** A handler for the drawn event. */ + onDrawn?: (e: { + component: BaseWidget; + element: Element; + }) => void; + incidentOccured?: (incidentInfo: { + id: string; + type: string; + args: any; + text: string; + widget: string; + version: string; + }) => void; + /** A handler for the incidentOccurred event. */ + onIncidentOccurred?: ( + component: BaseWidget, + element: Element, + target: { + id: string; + type: string; + args: any; + text: string; + widget: string; + version: string; + } + ) => void; + /** Notifies a widget that it is embedded into an HTML page that uses a path modifier. */ + pathModified?: boolean; + /** Specifies whether or not the widget supports right-to-left representation. */ + rtlEnabled?: boolean; + /** Sets the name of the theme to be used in the widget. */ + theme?: string; + } + /** This section describes options and methods that are common to all widgets. */ + export class BaseWidget extends DOMComponent { + /** Returns the widget's SVG markup. */ + svg(): string; + } +} +declare module DevExpress.viz.charts { + /** This section describes the fields and methods that can be used in code to manipulate the Series object. */ + export interface BaseSeries { + /** Provides information about the state of the series object. */ + fullState: number; + /** Returns the type of the series. */ + type: string; + /** Unselects all the selected points of the series. The points are displayed in an initial style. */ + clearSelection(): void; + /** Gets the color of a particular series. */ + getColor(): string; + /** + * Gets a point from the series point collection based on the specified argument. + * @deprecated getPointsByArg(pointArg).md + */ + getPointByArg(pointArg: any): Object; + /** Gets points from the series point collection based on the specified argument. */ + getPointsByArg(pointArg: any): Array; + /** Gets a point from the series point collection based on the specified point position. */ + getPointByPos(positionIndex: number): Object; + /** Selects the series. The series is displayed in a 'selected' style until another series is selected or the current series is deselected programmatically. */ + select(): void; + /** Selects the specified point. The point is displayed in a 'selected' style. */ + selectPoint(point: BasePoint): void; + /** Deselects the specified point. The point is displayed in an initial style. */ + deselectPoint(point: BasePoint): void; + /** Returns an array of all points in the series. */ + getAllPoints(): Array; + /** Returns visible series points. */ + getVisiblePoints(): Array; + } + /** This section describes the methods that can be used in code to manipulate the Point object. */ + export interface BasePoint { + /** Provides information about the state of the point object. */ + fullState: number; + /** Returns the point's argument value that was set in the data source. */ + originalArgument: any; + /** Returns the point's value that was set in the data source. */ + originalValue: any; + /** Returns the tag of the point. */ + tag: string; + /** Deselects the point. */ + clearSelection(): void; + /** Gets the color of a particular point. */ + getColor(): string; + /** Hides the tooltip of the point. */ + hideTooltip(): void; + /** Provides information about the hover state of a point. */ + isHovered(): any; + /** Provides information about the selection state of a point. */ + isSelected(): any; + /** Selects the point. The point is displayed in a 'selected' style until another point is selected or the current point is deselected programmatically. */ + select(): void; + /** Shows the tooltip of the point. */ + showTooltip(): void; + /** Allows you to obtain the label of a series point. */ + getLabel(): any; + /** Returns the series object to which the point belongs. */ + series: BaseSeries; + } + /** This section describes the fields and methods that can be used in code to manipulate the Series object. */ + export interface ChartSeries extends BaseSeries { + /** Returns the name of the series pane. */ + pane: string; + /** Returns the name of the value axis of the series. */ + axis: string; + /** Returns the name of the series. */ + name: string; + /** Returns the tag of the series. */ + tag: string; + /** Hides a series. */ + hide(): void; + /** Provides information about the hover state of a series. */ + isHovered(): any; + /** Provides information about the selection state of a series. */ + isSelected(): any; + /** Provides information about the visibility state of a series. */ + isVisible(): boolean; + /** Makes a particular series visible. */ + show(): void; + selectPoint(point: ChartPoint): void; + deselectPoint(point: ChartPoint): void; + getAllPoints(): Array; + getVisiblePoints(): Array; + } + /** This section describes the methods that can be used in code to manipulate the Point object. */ + export interface ChartPoint extends BasePoint { + /** Contains the close value of the point. This field is useful for points belonging to a series of the candle stick or stock type only. */ + originalCloseValue: any; + /** Contains the high value of the point. This field is useful for points belonging to a series of the candle stick or stock type only. */ + originalHighValue: any; + /** Contains the low value of the point. This field is useful for points belonging to a series of the candle stick or stock type only. */ + originalLowValue: any; + /** Contains the first value of the point. This field is useful for points belonging to a series of the range area or range bar type only. */ + originalMinValue: any; + /** Contains the open value of the point. This field is useful for points belonging to a series of the candle stick or stock type only. */ + originalOpenValue: any; + /** Contains the size of the bubble as it was set in the data source. This field is useful for points belonging to a series of the bubble type only. */ + size: any; + /** Gets the parameters of the point's minimum bounding rectangle (MBR). */ + getBoundingRect(): { x: number; y: number; width: number; height: number; }; + series: ChartSeries; + } + /** This section describes the methods that can be used in code to manipulate the Label object. */ + export interface Label { + /** Gets the parameters of the label's minimum bounding rectangle (MBR). */ + getBoundingRect(): { x: number; y: number; width: number; height: number; }; + /** Hides the point label. */ + hide(): void; + /** Shows the point label. */ + show(): void; + } + export interface PieSeries extends BaseSeries { + selectPoint(point: PiePoint): void; + deselectPoint(point: PiePoint): void; + getAllPoints(): Array; + getVisiblePoints(): Array; + } + /** This section describes the methods that can be used in code to manipulate the Point object. */ + export interface PiePoint extends BasePoint { + /** Gets the percentage value of the specific point. */ + percent: any; + /** Provides information about the visibility state of a point. */ + isVisible(): boolean; + /** Makes a specific point visible. */ + show(): void; + /** Hides a specific point. */ + hide(): void; + series: PieSeries; + } + /** This section describes the fields and methods that can be used in code to manipulate the Series object. */ + export interface PolarSeries extends BaseSeries { + /** Returns the name of the value axis of the series. */ + axis: string; + /** Returns the name of the series. */ + name: string; + /** Returns the tag of the series. */ + tag: string; + /** Hides a series. */ + hide(): void; + /** Provides information about the hover state of a series. */ + isHovered(): any; + /** Provides information about the selection state of a series. */ + isSelected(): any; + /** Provides information about the visibility state of a series. */ + isVisible(): boolean; + /** Makes a particular series visible. */ + show(): void; + selectPoint(point: PolarPoint): void; + deselectPoint(point: PolarPoint): void; + getAllPoints(): Array; + getVisiblePoints(): Array; + } + /** This section describes the methods that can be used in code to manipulate the Point object. */ + export interface PolarPoint extends BasePoint { + series: PolarSeries; + } + export interface Strip { + /** Specifies a color for a strip. */ + color?: string; + /** An object that defines the label configuration options of a strip. */ + label?: { + /** Specifies the text displayed in a strip. */ + text?: string; + }; + /** Specifies a start value for a strip. */ + startValue?: any; + /** Specifies an end value for a strip. */ + endValue?: any; + } + export interface BaseSeriesConfigLabel { + /** Specifies a format for arguments displayed by point labels. */ + argumentFormat?: string; + /** Specifies a precision for formatted point arguments displayed in point labels. */ + argumentPrecision?: number; + /** Specifies a background color for point labels. */ + backgroundColor?: string; + /** Specifies border options for point labels. */ + border?: viz.core.DashedBorder; + /** Specifies connector options for series point labels. */ + connector?: { + /** Specifies the color of label connectors. */ + color?: string; + /** Indicates whether or not label connectors are visible. */ + visible?: boolean; + /** Specifies the width of label connectors. */ + width?: number; + }; + /** Specifies a callback function that returns the text to be displayed by point labels. */ + customizeText?: (pointInfo: Object) => string; + /** Specifies font options for the text displayed in point labels. */ + font?: viz.core.Font; + /** Specifies a format for the text displayed by point labels. */ + format?: string; + position?: string; + /** Specifies a precision for formatted point values displayed in point labels. */ + precision?: number; + /** Specifies the angle used to rotate point labels from their initial position. */ + rotationAngle?: number; + /** Specifies the visibility of point labels. */ + visible?: boolean; + } + export interface SeriesConfigLabel extends BaseSeriesConfigLabel { + /** Specifies whether or not to show a label when the point has a zero value. */ + showForZeroValues?: boolean; + } + export interface ChartSeriesConfigLabel extends SeriesConfigLabel { + /** Specifies how to align point labels relative to the corresponding data points that they represent. */ + alignment?: string; + /** Specifies how to shift point labels horizontally from their initial positions. */ + horizontalOffset?: number; + /** Specifies how to shift point labels vertically from their initial positions. */ + verticalOffset?: number; + /** Specifies a precision for the percentage values displayed in the labels of a full-stacked-like series. */ + percentPrecision?: number; + } + export interface BaseCommonSeriesConfig { + /** Specifies the data source field that provides arguments for series points. */ + argumentField?: string; + axis?: string; + /** An object defining the label configuration options for a series in the dxChart widget. */ + label?: ChartSeriesConfigLabel; + /** Specifies border options for point labels. */ + border?: viz.core.DashedBorder; + /** Specifies a series color. */ + color?: string; + /** Specifies the dash style of the series' line. */ + dashStyle?: string; + hoverMode?: string; + /** An object defining configuration options for a hovered series. */ + hoverStyle?: { + /** An object defining the border options for a hovered series. */ + border?: viz.core.DashedBorder; + /**

      Sets a color for a series when it is hovered over.

      */ + color?: string; + /** Specifies the dash style for the line in a hovered series. */ + dashStyle?: string; + /** Specifies the hatching options to be applied when a series is hovered over. */ + hatching?: viz.core.Hatching; + /** Specifies the width of a line in a hovered series. */ + width?: number; + }; + /** Specifies whether a chart ignores null data points or not. */ + ignoreEmptyPoints?: boolean; + /** Specifies how many points are acceptable to be in a series to display all labels for these points. Otherwise, the labels will not be displayed. */ + maxLabelCount?: number; + /** Specifies the minimal length of a displayed bar in pixels. */ + minBarSize?: number; + /** Specifies opacity for a series. */ + opacity?: number; + /** Specifies the series elements to highlight when the series is selected. */ + selectionMode?: string; + /** An object defining configuration options for a selected series. */ + selectionStyle?: { + /** An object defining the border options for a selected series. */ + border?: viz.core.DashedBorder; + /** Sets a color for a series when it is selected. */ + color?: string; + /** Specifies the dash style for the line in a selected series. */ + dashStyle?: string; + /** Specifies the hatching options to be applied when a series is selected. */ + hatching?: viz.core.Hatching; + /** Specifies the width of a line in a selected series. */ + width?: number; + }; + /** Specifies whether or not to show the series in the chart's legend. */ + showInLegend?: boolean; + /** Specifies the name of the stack where the values of the _stackedBar_ series must be located. */ + stack?: string; + /** Specifies the name of the data source field that provides data about a point. */ + tagField?: string; + /** Specifies the data source field that provides values for series points. */ + valueField?: string; + /** Specifies the visibility of a series. */ + visible?: boolean; + /** Specifies a line width. */ + width?: number; + /** Configures error bars. */ + valueErrorBar?: { + /** Specifies whether error bars must be displayed in full or partially. */ + displayMode?: string; + /** Specifies the data field that provides data for low error values. */ + lowValueField?: string; + /** Specifies the data field that provides data for high error values. */ + highValueField?: string; + /** Specifies how error bar values must be calculated. */ + type?: string; + /** Specifies the value to be used for generating error bars. */ + value?: number; + /** Specifies the color of error bars. */ + color?: string; + /** Specifies the opacity of error bars. */ + opacity?: number; + /** Specifies the length of the lines that indicate the error bar edges. */ + edgeLength?: number; + /** Specifies the width of the error bar line. */ + lineWidth?: number; + }; + } + export interface CommonPointOptions { + /** Specifies border options for points in the line and area series. */ + border?: viz.core.Border; + /** Specifies the points color. */ + color?: string; + /** Specifies what series points to highlight when a point is hovered over. */ + hoverMode?: string; + /** An object defining configuration options for a hovered point. */ + hoverStyle?: { + /** An object defining the border options for a hovered point. */ + border?: viz.core.Border; + /** Sets a color for a point when it is hovered over. */ + color?: string; + /** Specifies the diameter of a hovered point in the series that represents data points as symbols (not as bars for instance). */ + size?: number; + }; + /** Specifies what series points to highlight when a point is selected. */ + selectionMode?: string; + /** An object defining configuration options for a selected point. */ + selectionStyle?: { + /** An object defining the border options for a selected point. */ + border?: viz.core.Border; + /**

      Sets a color for a point when it is selected.

      */ + color?: string; + /** Specifies the diameter of a selected point in the series that represents data points as symbols (not as bars for instance). */ + size?: number; + }; + /** Specifies the point diameter in pixels for those series that represent data points as symbols (not as bars for instance). */ + size?: number; + /** Specifies a symbol for presenting points of the line and area series. */ + symbol?: string; + visible?: boolean; + } + export interface ChartCommonPointOptions extends CommonPointOptions { + /** An object specifying the parameters of an image that is used as a point marker. */ + image?: { + /** Specifies the height of an image that is used as a point marker. */ + height?: any; + /** Specifies a URL leading to the image to be used as a point marker. */ + url?: any; + /** Specifies the width of an image that is used as a point marker. */ + width?: any; + }; + } + export interface PolarCommonPointOptions extends CommonPointOptions { + /** An object specifying the parameters of an image that is used as a point marker. */ + image?: { + /** Specifies the height of an image that is used as a point marker. */ + height?: number; + /** Specifies a URL leading to the image to be used as a point marker. */ + url?: string; + /** Specifies the width of an image that is used as a point marker. */ + width?: number; + }; + } + /** An object that defines configuration options for chart series. */ + export interface CommonSeriesConfig extends BaseCommonSeriesConfig { + /** Specifies the data source field that provides a 'close' value for a _candleStick_ or _stock_ series. */ + closeValueField?: string; + /** Specifies a radius for bar corners. */ + cornerRadius?: number; + /** Specifies the data source field that provides a 'high' value for a _candleStick_ or _stock_ series. */ + highValueField?: string; + /** Specifies the color for the body (rectangle) of a _candleStick_ series. */ + innerColor?: string; + /** Specifies the data source field that provides a 'low' value for a _candleStick_ or _stock_ series. */ + lowValueField?: string; + /** Specifies the data source field that provides an 'open' value for a _candleStick_ or _stock_ series. */ + openValueField?: string; + /** Specifies the pane that will be used to display a series. */ + pane?: string; + /** An object defining configuration options for points in line-, scatter- and area-like series. */ + point?: ChartCommonPointOptions; + /** Specifies the data source field that provides values for one end of a range series. To set the data source field for the other end of the range series, use the rangeValue2Field property. */ + rangeValue1Field?: string; + /** Specifies the data source field that provides values for the second end of a range series. To set the data source field for the other end of the range series, use the rangeValue1Field property. */ + rangeValue2Field?: string; + /** Specifies reduction options for the stock or candleStick series. */ + reduction?: { + /** Specifies a color for the points whose reduction level price is lower in comparison to the value in the previous point. */ + color?: string; + /** Specifies for which price level (open, high, low or close) to enable reduction options in the series. */ + level?: string; + }; + /** Specifies the data source field that defines the size of bubbles. */ + sizeField?: string; + } + export interface CommonSeriesSettings extends CommonSeriesConfig { + /**

      An object that specifies configuration options for all series of the area type in the chart.

      */ + area?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the _bar_ type in the chart. */ + bar?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the bubble type in the chart. */ + bubble?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the _candleStick_ type in the chart. */ + candlestick?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the _fullStackedArea_ type in the chart. */ + fullstackedarea?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the Full-Stacked Spline Area type in the chart. */ + fullstackedsplinearea?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the _fullStackedBar_ type in the chart. */ + fullstackedbar?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the _fullStackedLine_ type in the chart. */ + fullstackedline?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the Full-Stacked Spline type in the chart. */ + fullstackedspline?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the _line_ type in the chart. */ + line?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the _rangeArea_ type in the chart. */ + rangearea?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the _rangeBar_ type in the chart. */ + rangebar?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the _scatter_ type in the chart. */ + scatter?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the _spline_ type in the chart. */ + spline?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the _splineArea_ type in the chart. */ + splinearea?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the _stackedArea_ type in the chart. */ + stackedarea?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the Stacked Spline Area type in the chart. */ + stackedsplinearea?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the _stackedBar_ type in the chart. */ + stackedbar?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the _stackedLine_ type in the chart. */ + stackedline?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the Stacked Spline type in the chart. */ + stackedspline?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the _stepArea_ type in the chart. */ + steparea?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the _stepLine_ type in the chart. */ + stepline?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the _stock_ type in the chart. */ + stock?: CommonSeriesConfig; + /** Sets a series type. */ + type?: string; + } + export interface SeriesConfig extends CommonSeriesConfig { + /** Specifies the name that identifies the series. */ + name?: string; + /** Specifies data about a series. */ + tag?: any; + /** Sets the series type. */ + type?: string; + } + /** An object that defines configuration options for polar chart series. */ + export interface CommonPolarSeriesConfig extends BaseCommonSeriesConfig { + /** Specifies whether or not to close the chart by joining the end point with the first point. */ + closed?: boolean; + label?: SeriesConfigLabel; + point?: PolarCommonPointOptions; + } + export interface CommonPolarSeriesSettings extends CommonPolarSeriesConfig { + /** An object that specifies configuration options for all series of the area type in the chart. */ + area?: CommonPolarSeriesConfig; + /** An object that specifies configuration options for all series of the _bar_ type in the chart. */ + bar?: CommonPolarSeriesConfig; + /** An object that specifies configuration options for all series of the _line_ type in the chart. */ + line?: CommonPolarSeriesConfig; + /** An object that specifies configuration options for all series of the _scatter_ type in the chart. */ + scatter?: CommonPolarSeriesConfig; + /** An object that specifies configuration options for all series of the _stackedBar_ type in the chart. */ + stackedbar?: CommonPolarSeriesConfig; + /** Sets a series type. */ + type?: string; + } + export interface PolarSeriesConfig extends CommonPolarSeriesConfig { + /** Specifies the name that identifies the series. */ + name?: string; + /** Specifies data about a series. */ + tag?: any; + /** Sets the series type. */ + type?: string; + } + export interface PieSeriesConfigLabel extends BaseSeriesConfigLabel { + /** Specifies how to shift labels from their initial position in a radial direction in pixels. */ + radialOffset?: number; + /** Specifies a precision for the percentage values displayed in labels. */ + percentPrecision?: number; + } + /** An object that defines configuration options for chart series. */ + export interface CommonPieSeriesConfig { + /** Specifies the data source field that provides arguments for series points. */ + argumentField?: string; + /** Specifies the required type for series arguments. */ + argumentType?: string; + /** An object defining the series border configuration options. */ + border?: viz.core.DashedBorder; + /** Specifies a series color. */ + color?: string; + /** Specifies the chart elements to highlight when a series is hovered over. */ + hoverMode?: string; + /** An object defining configuration options for a hovered series. */ + hoverStyle?: { + /** An object defining the border options for a hovered series. */ + border?: viz.core.DashedBorder; + /** Sets a color for the series when it is hovered over. */ + color?: string; + /** Specifies the hatching options to be applied when a point is hovered over. */ + hatching?: viz.core.Hatching; + }; + /** Specifies the fraction of the inner radius relative to the total radius in the series of the 'doughnut' type. */ + innerRadius?: number; + /** An object defining the label configuration options. */ + label?: PieSeriesConfigLabel; + /** Specifies how many points are acceptable to be in a series to display all labels for these points. Otherwise, the labels will not be displayed. */ + maxLabelCount?: number; + /** Specifies a minimal size of a displayed pie segment. */ + minSegmentSize?: number; + /** Specifies the direction in which the dxPieChart's series points are located. */ + segmentsDirection?: string; + /**

      Specifies the chart elements to highlight when the series is selected.

      */ + selectionMode?: string; + /** An object defining configuration options for the series when it is selected. */ + selectionStyle?: { + /** An object defining the border options for a selected series. */ + border?: viz.core.DashedBorder; + /** Sets a color for a series when it is selected. */ + color?: string; + /** Specifies the hatching options to be applied when a point is selected. */ + hatching?: viz.core.Hatching; + }; + /** Specifies chart segment grouping options. */ + smallValuesGrouping?: { + /** Specifies the name of the grouped chart segment. This name represents the segment in the chart legend. */ + groupName?: string; + /** Specifies the segment grouping mode. */ + mode?: string; + /** Specifies a threshold for segment values. */ + threshold?: number; + /** Specifies how many segments must not be grouped. */ + topCount?: number; + }; + /** Specifies a start angle for a pie chart in arc degrees. */ + startAngle?: number; + /**

      Specifies the name of the data source field that provides data about a point.

      */ + tagField?: string; + /** Specifies the data source field that provides values for series points. */ + valueField?: string; + } + export interface PieSeriesConfig extends CommonPieSeriesConfig { + /** Sets the series type. */ + type?: string; + } + export interface SeriesTemplate { + /** Specifies a callback function that returns a series object with individual series settings. */ + customizeSeries?: (seriesName: string) => SeriesConfig; + /** Specifies a data source field that represents the series name. */ + nameField?: string; + } + export interface PolarSeriesTemplate { + /** Specifies a callback function that returns a series object with individual series settings. */ + customizeSeries?: (seriesName: string) => PolarSeriesConfig; + /** Specifies a data source field that represents the series name. */ + nameField?: string; + } + export interface ChartCommonConstantLineLabel { + /** Specifies font options for a constant line label. */ + font?: viz.core.Font; + /** Specifies the position of the constant line label relative to the chart plot. */ + position?: string; + /** Indicates whether or not to display labels for the axis constant lines. */ + visible?: boolean; + } + export interface PolarCommonConstantLineLabel { + /** Indicates whether or not to display labels for the axis constant lines. */ + visible?: boolean; + /** Specifies font options for a constant line label. */ + font?: viz.core.Font; + } + export interface ConstantLineStyle { + /** Specifies a color for a constant line. */ + color?: string; + /** Specifies a dash style for a constant line. */ + dashStyle?: string; + /** Specifies a constant line width in pixels. */ + width?: number; + } + export interface ChartCommonConstantLineStyle extends ConstantLineStyle { + /** An object defining constant line label options. */ + label?: ChartCommonConstantLineLabel; + /** Specifies the space between the constant line label and the left/right side of the constant line. */ + paddingLeftRight?: number; + /** Specifies the space between the constant line label and the top/bottom side of the constant line. */ + paddingTopBottom?: number; + } + export interface PolarCommonConstantLineStyle extends ConstantLineStyle { + /** An object defining constant line label options. */ + label?: PolarCommonConstantLineLabel; + } + export interface CommonAxisLabel { + /** Specifies font options for axis labels. */ + font?: viz.core.Font; + /** Specifies the spacing between an axis and its labels in pixels. */ + indentFromAxis?: number; + /** Indicates whether or not axis labels are visible. */ + visible?: boolean; + } + export interface ChartCommonAxisLabel extends CommonAxisLabel { + /** Specifies the label's position relative to the tick (grid line). */ + alignment?: string; + /** Specifies the overlap resolving algorithm to be applied to axis labels. */ + overlappingBehavior?: { + /** Specifies how to arrange axis labels. */ + mode?: string; + /** Specifies the angle used to rotate axis labels. */ + rotationAngle?: number; + /** Specifies the spacing that must be set between staggered rows when the 'stagger' algorithm is applied. */ + staggeringSpacing?: number; + }; + } + export interface PolarCommonAxisLabel extends CommonAxisLabel { + /** Specifies the overlap resolving algorithm to be applied to axis labels. */ + overlappingBehavior?: string; + } + export interface CommonAxisTitle { + /** Specifies font options for an axis title. */ + font?: viz.core.Font; + /** Specifies a margin for an axis title in pixels. */ + margin?: number; + } + export interface BaseCommonAxisSettings { + /** Specifies the color of the line that represents an axis. */ + color?: string; + /** Specifies whether ticks/grid lines of a discrete axis are located between labels or cross the labels. */ + discreteAxisDivisionMode?: string; + /** An object defining the configuration options for the grid lines of an axis in the dxPolarChart widget. */ + grid?: { + /** Specifies a color for grid lines. */ + color?: string; + /** Specifies an opacity for grid lines. */ + opacity?: number; + /** Indicates whether or not the grid lines of an axis are visible. */ + visible?: boolean; + /** Specifies the width of grid lines. */ + width?: number; + }; + /** Specifies the options of the minor grid. */ + minorGrid?: { + /** Specifies a color for the lines of the minor grid. */ + color?: string; + /** Specifies an opacity for the lines of the minor grid. */ + opacity?: number; + /** Indicates whether the minor grid is visible or not. */ + visible?: boolean; + /** Specifies a width for the lines of the minor grid. */ + width?: number; + }; + /** Indicates whether or not an axis is inverted. */ + inverted?: boolean; + /** Specifies the opacity of the line that represents an axis. */ + opacity?: number; + /** Indicates whether or not to set ticks/grid lines of a continuous axis of the 'date-time' type at the beginning of each date-time interval. */ + setTicksAtUnitBeginning?: boolean; + /** An object defining the configuration options for axis ticks. */ + tick?: { + /** Specifies ticks color. */ + color?: string; + /** Specifies tick opacity. */ + opacity?: number; + /** Indicates whether or not ticks are visible on an axis. */ + visible?: boolean; + }; + /** Specifies the options of the minor ticks. */ + minorTick?: { + /** Specifies a color for the minor ticks. */ + color?: string; + /** Specifies an opacity for the minor ticks. */ + opacity?: number; + /** Indicates whether or not the minor ticks are displayed on an axis. */ + visible?: boolean; + }; + /** Indicates whether or not the line that represents an axis in a chart is visible. */ + visible?: boolean; + /** Specifies the width of the line that represents an axis in the chart. */ + width?: number; + } + export interface ChartCommonAxisSettings extends BaseCommonAxisSettings { + /** Specifies the appearance of all the widget's constant lines. */ + constantLineStyle?: ChartCommonConstantLineStyle; + /** An object defining the label configuration options that are common for all axes in the dxChart widget. */ + label?: ChartCommonAxisLabel; + /** Specifies a coefficient that determines the spacing between the maximum series point and the axis. */ + maxValueMargin?: number; + /** Specifies a coefficient that determines the spacing between the minimum series point and the axis. */ + minValueMargin?: number; + /** Specifies, in pixels, the space reserved for an axis. */ + placeholderSize?: number; + /** An object defining configuration options for strip style. */ + stripStyle?: { + /** An object defining the configuration options for a strip label style. */ + label?: { + /** Specifies font options for a strip label. */ + font?: viz.core.Font; + /** Specifies the label's position on a strip. */ + horizontalAlignment?: string; + /** Specifies a label's position on a strip. */ + verticalAlignment?: string; + }; + /** Specifies the spacing, in pixels, between the left/right strip border and the strip label. */ + paddingLeftRight?: number; + /** Specifies the spacing, in pixels, between the top/bottom strip borders and the strip label. */ + paddingTopBottom?: number; + }; + /** An object defining the title configuration options that are common for all axes in the dxChart widget. */ + title?: CommonAxisTitle; + /** Indicates whether or not to display series with indents from axis boundaries. */ + valueMarginsEnabled?: boolean; + } + export interface PolarCommonAxisSettings extends BaseCommonAxisSettings { + /** Specifies the appearance of all the widget's constant lines. */ + constantLineStyle?: PolarCommonConstantLineStyle; + /** An object defining the label configuration options that are common for all axes in the dxPolarChart widget. */ + label?: PolarCommonAxisLabel; + /** An object defining configuration options for strip style. */ + stripStyle?: { + /** An object defining the configuration options for a strip label style. */ + label?: { + /** Specifies font options for a strip label. */ + font?: viz.core.Font; + }; + }; + } + export interface ChartConstantLineLabel extends ChartCommonConstantLineLabel { + /** Specifies the horizontal alignment of a constant line label. */ + horizontalAlignment?: string; + /** Specifies the vertical alignment of a constant line label. */ + verticalAlignment?: string; + /** Specifies the text to be displayed in a constant line label. */ + text?: string; + } + export interface PolarConstantLineLabel extends PolarCommonConstantLineLabel { + /** Specifies the text to be displayed in a constant line label. */ + text?: string; + } + export interface AxisLabel { + /** Specifies the text for a hint that appears when a user hovers the mouse pointer over a label on the value axis. */ + customizeHint?: (argument: { value: any; valueText: string }) => string; + /** Specifies a callback function that returns the text to be displayed in value axis labels. */ + customizeText?: (argument: { value: any; valueText: string }) => string; + /** Specifies a format for the text displayed by axis labels. */ + format?: string; + /** Specifies a precision for the formatted value displayed in the axis labels. */ + precision?: number; + } + export interface ChartAxisLabel extends ChartCommonAxisLabel, AxisLabel {} + export interface PolarAxisLabel extends PolarCommonAxisLabel, AxisLabel {} + export interface AxisTitle extends CommonAxisTitle { + /** Specifies the text for the value axis title. */ + text?: string; + } + export interface ChartConstantLineStyle extends ChartCommonConstantLineStyle { + /** An object defining constant line label options. */ + label?: ChartConstantLineLabel; + } + export interface ChartConstantLine extends ChartConstantLineStyle { + /** An object defining constant line label options. */ + label?: ChartConstantLineLabel; + /** Specifies a value to be displayed by a constant line. */ + value?: any; + } + export interface PolarConstantLine extends PolarCommonConstantLineStyle { + /** An object defining constant line label options. */ + label?: PolarConstantLineLabel; + /** Specifies a value to be displayed by a constant line. */ + value?: any; + } + export interface Axis { + /** Specifies a coefficient for dividing the value axis. */ + axisDivisionFactor?: number; + /** Specifies the order in which discrete values are arranged on the value axis. */ + categories?: Array; + /** Specifies the value to be raised to a power when generating ticks for a logarithmic axis. */ + logarithmBase?: number; + /** Specifies an interval between axis ticks/grid lines. */ + tickInterval?: any; + /** Specifies the interval between minor ticks. */ + minorTickInterval?: any; + /** Specifies the number of minor ticks between two neighboring major ticks. */ + minorTickCount?: number; + /** Specifies the required type of the value axis. */ + type?: string; + /** Specifies the pane on which the current value axis will be displayed. */ + pane?: string; + /** Specifies options for value axis strips. */ + strips?: Array; + } + export interface ChartAxis extends ChartCommonAxisSettings, Axis { + /** Defines an array of the value axis constant lines. */ + constantLines?: Array; + /** Specifies the appearance options for the constant lines of the value axis. */ + constantLineStyle?: ChartCommonConstantLineStyle; + /** Specifies options for value axis labels. */ + label?: ChartAxisLabel; + /** Specifies the maximum value on the value axis. */ + max?: any; + /** Specifies the minimum value on the value axis. */ + min?: any; + /** Specifies the position of the value axis on a chart. */ + position?: string; + /** Specifies the title for a value axis. */ + title?: AxisTitle; + } + export interface PolarAxis extends PolarCommonAxisSettings, Axis { + /** Defines an array of the value axis constant lines. */ + constantLines?: Array; + /** Specifies options for value axis labels. */ + label?: PolarAxisLabel; + } + export interface ArgumentAxis { + /** Specifies the desired type of axis values. */ + argumentType?: string; + /** Specifies the elements that will be highlighted when the argument axis is hovered over. */ + hoverMode?: string; + } + export interface ChartArgumentAxis extends ChartAxis, ArgumentAxis {} + export interface PolarArgumentAxis extends PolarAxis, ArgumentAxis { + /** Specifies a start angle for the argument axis in degrees. */ + startAngle?: number; + /** Specifies whether or not to display the first point at the angle specified by the startAngle option. */ + firstPointOnStartAngle?: boolean; + /** Specifies the period of the argument values in the data source. */ + period?: number; + } + export interface ValueAxis { + /** Specifies the name of the value axis. */ + name?: string; + /** Specifies whether or not to indicate a zero value on the value axis. */ + showZero?: boolean; + /** Specifies the desired type of axis values. */ + valueType?: string; + } + export interface ChartValueAxis extends ChartAxis, ValueAxis { + /** Specifies the spacing, in pixels, between multiple value axes in a chart. */ + multipleAxesSpacing?: number; + /** Specifies the value by which the chart's value axes are synchronized. */ + synchronizedValue?: number; + } + export interface PolarValueAxis extends PolarAxis, ValueAxis { + /** Indicates whether to display series with indents from axis boundaries. */ + valueMarginsEnabled?: boolean; + /** Specifies a coefficient that determines the spacing between the maximum series point and the axis. */ + maxValueMargin?: number; + /** Specifies a coefficient that determines the spacing between the minimum series point and the axis. */ + minValueMargin?: number; + tick?: { + visible?: boolean; + } + } + export interface CommonPane { + /** Specifies a background color in a pane. */ + backgroundColor?: string; + /** Specifies the border options of a chart's pane. */ + border?: PaneBorder; + } + export interface Pane extends CommonPane { + /** Specifies the name of a pane. */ + name?: string; + } + export interface PaneBorder extends viz.core.DashedBorderWithOpacity { + /** Specifies the bottom border's visibility state in a pane. */ + bottom?: boolean; + /** Specifies the left border's visibility state in a pane. */ + left?: boolean; + /** Specifies the right border's visibility state in a pane. */ + right?: boolean; + /** Specifies the top border's visibility state in a pane. */ + top?: boolean; + } + export interface ChartAnimation extends viz.core.Animation { + /** Specifies the maximum series point count in the chart that the animation supports. */ + maxPointCountSupported?: number; + } + export interface BaseChartTooltip extends viz.core.Tooltip { + /** Specifies a format for arguments of the chart's series points. */ + argumentFormat?: string; + /** Specifies a precision for formatted arguments displayed in tooltips. */ + argumentPrecision?: number; + /** Specifies a precision for a percent value displayed in tooltips for stacked series and dxPieChart series. */ + percentPrecision?: number; + } + export interface BaseChartOptions extends viz.core.BaseWidgetOptions { + /** Specifies adaptive layout options. */ + adaptiveLayout?: { + /** Specifies the width of the widget container that is small enough for the layout to begin adapting. */ + width?: number; + /** Specifies the height of the widget container that is small enough for the layout to begin adapting. */ + height?: number; + /** Specifies whether or not point labels can be hidden when the layout is adapting. */ + keepLabels?: boolean; + }; + /** Specifies animation options. */ + animation?: ChartAnimation; + /** Specifies a callback function that returns an object with options for a specific point label. */ + customizeLabel?: (labelInfo: Object) => Object; + /** Specifies a callback function that returns an object with options for a specific point. */ + customizePoint?: (pointInfo: Object) => Object; + /** Specifies a data source for the chart. */ + dataSource?: any; + done?: Function; + /** Specifies the appearance of the loading indicator. */ + loadingIndicator?: viz.core.LoadingIndicator; + /** Specifies options of a dxChart's (dxPieChart's) legend. */ + legend?: core.BaseLegend; + /** Specifies the blank space between the chart's extreme elements and the boundaries of the area provided for the widget (see size) in pixels. */ + margin?: viz.core.Margins; + /** Sets the name of the palette to be used in the chart. Alternatively, an array of colors can be set as a custom palette to be used within this chart. */ + palette?: any; + /** A handler for the done event. */ + onDone?: (e: { + component: BaseChart; + element: Element; + }) => void; + /** A handler for the pointClick event. */ + onPointClick?: any; + pointClick?: any; + /** A handler for the pointHoverChanged event. */ + onPointHoverChanged?: (e: { + component: BaseChart; + element: Element; + target: TPoint; + }) => void; + pointHoverChanged?: (point: TPoint) => void; + /** A handler for the pointSelectionChanged event. */ + onPointSelectionChanged?: (e: { + component: BaseChart; + element: Element; + target: TPoint; + }) => void; + pointSelectionChanged?: (point: TPoint) => void; + /** Specifies whether a single point or multiple points can be selected in the chart. */ + pointSelectionMode?: string; + /** Specifies whether to redraw the widget when the size of the parent browser window changes or a mobile device rotates. */ + redrawOnResize?: boolean; + /** Specifies options for the dxChart and dxPieChart widget series. */ + series?: any; + /** Specifies the size of the widget in pixels. */ + size?: viz.core.Size; + /** Specifies a title for the chart. */ + title?: { + /** Specifies font options for the title. */ + font?: viz.core.Font; + /** Specifies the title's horizontal position in the chart. */ + horizontalAlignment?: string; + /** Specifies a title's position on the chart in the vertical direction. */ + verticalAlignment?: string; + /** Specifies the distance between the title and surrounding chart elements in pixels. */ + margin?: viz.core.Margins; + /** Specifies the height of the space reserved for the title. */ + placeholderSize?: number; + /** Specifies a text for the chart's title. */ + text?: string; + }; + /** Specifies tooltip options. */ + tooltip?: BaseChartTooltip; + /** A handler for the tooltipShown event. */ + onTooltipShown?: (e: { + component: BaseChart; + element: Element; + target: BasePoint; + }) => void; + /** A handler for the tooltipHidden event. */ + onTooltipHidden?: (e: { + component: BaseChart; + element: Element; + target: BasePoint; + }) => void; + tooltipHidden?: (point: TPoint) => void; + tooltipShown?: (point: TPoint) => void; + } + /** A base class for all chart widgets included in the ChartJS library. */ + export class BaseChart extends viz.core.BaseWidget { + /** Deselects the chart's selected series. The series is displayed in an initial style. */ + clearSelection(): void; + /** Gets the current size of the widget. */ + getSize(): { width: number; height: number }; + /** Displays the loading indicator. */ + showLoadingIndicator(): void; + /** Conceals the loading indicator. */ + hideLoadingIndicator(): void; + /** Hides all widget tooltips. */ + hideTooltip(): void; + /** Redraws a widget. */ + render(renderOptions?: { + force?: boolean; + animate?: boolean; + asyncSeriesRendering?: boolean; + }): void; + } + export interface AdvancedLegend extends core.BaseLegend { + /** Specifies the text for a hint that appears when a user hovers the mouse pointer over a legend item. */ + customizeHint?: (seriesInfo: { seriesName: string; seriesIndex: number; seriesColor: string; }) => string; + /**

      Specifies a callback function that returns the text to be displayed by legend items.

      */ + customizeText?: (seriesInfo: { seriesName: string; seriesIndex: number; seriesColor: string; }) => string; + /** Specifies what series elements to highlight when a corresponding item in the legend is hovered over. */ + hoverMode?: string; + } + export interface AdvancedOptions extends BaseChartOptions { + /** A handler for the argumentAxisClick event. */ + onArgumentAxisClick?: any; + /** Specifies the color of the parent page element. */ + containerBackgroundColor?: string; + /** An object providing options for managing data from a data source. */ + dataPrepareSettings?: { + /** Specifies whether or not to validate the values from a data source. */ + checkTypeForAllData?: boolean; + /** Specifies whether or not to convert the values from a data source into the data type of an axis. */ + convertToAxisDataType?: boolean; + /** Specifies how to sort the series points. */ + sortingMethod?: any; + }; + /** A handler for the legendClick event. */ + onLegendClick?: any; + /** A handler for the seriesClick event. */ + onSeriesClick?: any; + /** A handler for the seriesHoverChanged event. */ + onSeriesHoverChanged?: (e: { + component: BaseChart; + element: Element; + target: TSeries; + }) => void; + /** A handler for the seriesSelectionChanged event. */ + onSeriesSelectionChanged?: (e: { + component: BaseChart; + element: Element; + target: TSeries; + }) => void; + /** Specifies whether a single series or multiple series can be selected in the chart. */ + seriesSelectionMode?: string; + /** Specifies how the chart must behave when series point labels overlap. */ + resolveLabelOverlapping?: string; + } + export interface Legend extends AdvancedLegend { + /** Specifies whether the legend is located outside or inside the chart's plot. */ + position?: string; + } + export interface ChartTooltip extends BaseChartTooltip { + /** Specifies whether the tooltip must be located in the center of a bar or on its edge. Applies only to the Bar series. */ + location?: string; + /** Specifies the kind of information to display in a tooltip. */ + shared?: boolean; + } + export interface dxChartOptions extends AdvancedOptions { + /** Specifies a value indicating whether all bars in a series must have the same width, or may have different widths if any points in other series are missing. */ + equalBarWidth?: any; + adaptiveLayout?: { + keepLabels?: boolean; + }; + /** Indicates whether or not to synchronize value axes when they are displayed on a single pane. */ + synchronizeMultiAxes?: boolean; + /** Specifies whether or not to filter the series points depending on their quantity. */ + useAggregation?: boolean; + /** Indicates whether or not to adjust a value axis to the current minimum and maximum values of a zoomed chart. */ + adjustOnZoom?: boolean; + /** Specifies argument axis options for the dxChart widget. */ + argumentAxis?: ChartArgumentAxis; + argumentAxisClick?: any; + /** An object defining the configuration options that are common for all axes of the dxChart widget. */ + commonAxisSettings?: ChartCommonAxisSettings; + /** An object defining the configuration options that are common for all panes in the dxChart widget. */ + commonPaneSettings?: CommonPane; + /** An object defining the configuration options that are common for all series of the dxChart widget. */ + commonSeriesSettings?: CommonSeriesSettings; + /** An object that specifies the appearance options of the chart crosshair. */ + crosshair?: { + /** Specifies a color for the crosshair lines. */ + color?: string; + /** Specifies a dash style for the crosshair lines. */ + dashStyle?: string; + /** Specifies whether to enable the crosshair or not. */ + enabled?: boolean; + /** Specifies the opacity of the crosshair lines. */ + opacity?: number; + /** Specifies the width of the crosshair lines. */ + width?: number; + /** Specifies the appearance of the horizontal crosshair line. */ + horizontalLine?: CrosshaierWithLabel; + /** Specifies the appearance of the vertical crosshair line. */ + verticalLine?: CrosshaierWithLabel; + /** Specifies the options of the crosshair labels. */ + label?: { + /** Specifies a color for the background of the crosshair labels. */ + backgroundColor?: string; + /** Specifies whether the crosshair labels are visible or not. */ + visible?: boolean; + /** Specifies font options for the text of the crosshair labels. */ + font?: viz.core.Font; + } + }; + /** Specifies a default pane for the chart's series. */ + defaultPane?: string; + /** Specifies a coefficient determining the diameter of the largest bubble. */ + maxBubbleSize?: number; + /** Specifies the diameter of the smallest bubble measured in pixels. */ + minBubbleSize?: number; + /** Defines the dxChart widget's pane(s). */ + panes?: Array; + /** Swaps the axes round so that the value axis becomes horizontal and the argument axes becomes vertical. */ + rotated?: boolean; + /** Specifies the options of a chart's legend. */ + legend?: Legend; + /** Specifies options for dxChart widget series. */ + series?: Array; + legendClick?: any; + seriesClick?: any; + seriesHoverChanged?: (series: ChartSeries) => void; + seriesSelectionChanged?: (series: ChartSeries) => void; + /** Defines options for the series template. */ + seriesTemplate?: SeriesTemplate; + /** Specifies tooltip options. */ + tooltip?: ChartTooltip; + /** Specifies value axis options for the dxChart widget. */ + valueAxis?: Array; + /** Enables scrolling in your chart. */ + scrollingMode?: string; + /** Enables zooming in your chart. */ + zoomingMode?: string; + /** Specifies the settings of the scroll bar. */ + scrollBar?: { + /** Specifies whether the scroll bar is visible or not. */ + visible?: boolean; + /** Specifies the spacing between the scroll bar and the chart's plot in pixels. */ + offset?: number; + /** Specifies the color of the scroll bar. */ + color?: string; + /** Specifies the width of the scroll bar in pixels. */ + width?: number; + /** Specifies the opacity of the scroll bar. */ + opacity?: number; + /** Specifies the position of the scroll bar in the chart. */ + position?: string; + }; + } + /** A widget used to embed charts into HTML JS applications. */ + export class dxChart extends BaseChart { + constructor(element: JQuery, options?: dxChartOptions); + constructor(element: Element, options?: dxChartOptions); + /** Returns an array of all series in the chart. */ + getAllSeries(): Array; + /** Gets a series within the chart's series collection by the specified name (see the name option). */ + getSeriesByName(seriesName: string): ChartSeries; + /** Gets a series within the chart's series collection by its position number. */ + getSeriesByPos(seriesIndex: number): ChartSeries; + /** Sets the specified start and end values for the chart's argument axis. */ + zoomArgument(startValue: any, endValue: any): void; + } + interface CrosshaierWithLabel extends viz.core.DashedBorderWithOpacity { + /** Configures the label that belongs to the horizontal crosshair line. */ + label?: { + /** Specifies a color for the background of the label that belongs to the horizontal crosshair line. */ + backgroundColor?: string; + /** Specifies whether the label of the horizontal crosshair line is visible or not. */ + visible?: boolean; + /** Specifies font options for the text of the label that belongs to the horizontal crosshair line. */ + font?: viz.core.Font; + } + } + export interface PolarChartTooltip extends BaseChartTooltip { + /** Specifies the kind of information to display in a tooltip. */ + shared?: boolean; + } + export interface dxPolarChartOptions extends AdvancedOptions { + /** Specifies a value indicating whether all bars in a series must have the same angle, or may have different angles if any points in other series are missing. */ + equalBarWidth?: boolean; + /** Specifies adaptive layout options. */ + adaptiveLayout?: { + width?: number; + height?: number; + /** Specifies whether or not point labels can be hidden when the layout is adapting. */ + keepLabels?: boolean; + }; + /** Indicates whether or not to display a "spider web". */ + useSpiderWeb?: boolean; + /** Specifies argument axis options for the dxPolarChart widget. */ + argumentAxis?: PolarArgumentAxis; + /** An object defining the configuration options that are common for all axes of the dxPolarChart widget. */ + commonAxisSettings?: PolarCommonAxisSettings; + /** An object defining the configuration options that are common for all series of the dxPolarChart widget. */ + commonSeriesSettings?: CommonPolarSeriesSettings; + /** Specifies the options of a chart's legend. */ + legend?: AdvancedLegend; + /** Specifies options for dxPolarChart widget series. */ + series?: Array; + /** Defines options for the series template. */ + seriesTemplate?: PolarSeriesTemplate; + /** Specifies tooltip options. */ + tooltip?: PolarChartTooltip; + /** Specifies value axis options for the dxPolarChart widget. */ + valueAxis?: PolarValueAxis; + } + /** A chart widget displaying data in a polar coordinate system. */ + export class dxPolarChart extends BaseChart { + constructor(element: JQuery, options?: dxPolarChartOptions); + constructor(element: Element, options?: dxPolarChartOptions); + /** Returns an array of all series in the chart. */ + getAllSeries(): Array; + /** Gets a series within the chart's series collection by the specified name (see the name option). */ + getSeriesByName(seriesName: string): PolarSeries; + /** Gets a series within the chart's series collection by its position number. */ + getSeriesByPos(seriesIndex: number): PolarSeries; + } + export interface PieLegend extends core.BaseLegend { + /** Specifies what chart elements to highlight when a corresponding item in the legend is hovered over. */ + hoverMode?: string; + /** Specifies the text for a hint that appears when a user hovers the mouse pointer over a legend item. */ + customizeHint?: (pointInfo: { pointName: string; pointIndex: number; pointColor: string; }) => string; + /** Specifies a callback function that returns the text to be displayed by a legend item. */ + customizeText?: (pointInfo: { pointName: string; pointIndex: number; pointColor: string; }) => string; + } + export interface dxPieChartOptions extends BaseChartOptions { + /** Specifies adaptive layout options. */ + adaptiveLayout?: { + /** Specifies whether or not point labels can be hidden when the layout is adapting. */ + keepLabels?: boolean; + }; + /** Specifies dxPieChart legend options. */ + legend?: PieLegend; + /** Specifies options for the series of the dxPieChart widget. */ + series?: Array; + /** Specifies the diameter of the pie. */ + diameter?: number; + /** A handler for the legendClick event. */ + onLegendClick?: any; + legendClick?: any; + /** Specifies how the chart must behave when series point labels overlap. */ + resolveLabelOverlapping?: string; + } + /** A circular chart widget for HTML JS applications. */ + export class dxPieChart extends BaseChart { + constructor(element: JQuery, options?: dxPieChartOptions); + constructor(element: Element, options?: dxPieChartOptions); + /** Provides access to the dxPieChart series. */ + getSeries(): PieSeries; + } +} +interface JQuery { + dxChart(options?: DevExpress.viz.charts.dxChartOptions): JQuery; + dxChart(methodName: string, ...params: any[]): any; + dxChart(methodName: "instance"): DevExpress.viz.charts.dxChart; + dxPieChart(options?: DevExpress.viz.charts.dxPieChartOptions): JQuery; + dxPieChart(methodName: string, ...params: any[]): any; + dxPieChart(methodName: "instance"): DevExpress.viz.charts.dxPieChart; + dxPolarChart(options?: DevExpress.viz.charts.dxPolarChartOptions): JQuery; + dxPolarChart(methodName: string, ...params: any[]): any; + dxPolarChart(methodName: "instance"): DevExpress.viz.charts.dxPolarChart; +} +declare module DevExpress.viz.gauges { + export interface BaseRangeContainer { + /** Specifies a range container's background color. */ + backgroundColor?: string; + /** Specifies the offset of the range container from an invisible scale line in pixels. */ + offset?: number; + /** Sets the name of the palette or an array of colors to be used for coloring the gauge range container. */ + palette?: any; + /** An array of objects representing ranges contained in the range container. */ + ranges?: Array<{ startValue: number; endValue: number; color: string }>; + /** Specifies a color of a range. */ + color?: string; + /** Specifies an end value of a range. */ + endValue?: number; + /** Specifies a start value of a range. */ + startValue?: number; + } + export interface ScaleTick { + /** Specifies the color of the scale's minor ticks. */ + color?: string; + /** Specifies an array of custom minor ticks. */ + customTickValues?: Array; + /** Specifies the length of the scale's minor ticks. */ + length?: number; + /** Indicates whether automatically calculated minor ticks are visible or not. */ + showCalculatedTicks?: boolean; + /** Specifies an interval between minor ticks. */ + tickInterval?: number; + /** Indicates whether scale minor ticks are visible or not. */ + visible?: boolean; + /** Specifies the width of the scale's minor ticks. */ + width?: number; + } + export interface ScaleMajorTick extends ScaleTick { + /** Specifies whether or not to expand the current major tick interval if labels overlap each other. */ + useTicksAutoArrangement?: boolean; + } + export interface BaseScaleLabel { + /** Specifies whether or not scale labels should be colored similarly to their corresponding ranges in the range container. */ + useRangeColors?: boolean; + /** Specifies a callback function that returns the text to be displayed in scale labels. */ + customizeText?: (scaleValue: { value: number; valueText: string }) => string; + /** Specifies font options for the text displayed in the scale labels of the gauge. */ + font?: viz.core.Font; + /** Specifies a format for the text displayed in scale labels. */ + format?: string; + /** Specifies a precision for the formatted value displayed in the scale labels. */ + precision?: number; + /** Specifies whether or not scale labels are visible on the gauge. */ + visible?: boolean; + } + export interface BaseScale { + /** Specifies the end value for the scale of the gauge. */ + endValue?: number; + /** Specifies whether or not to hide the first scale label. */ + hideFirstLabel?: boolean; + /** Specifies whether or not to hide the first major tick on the scale. */ + hideFirstTick?: boolean; + /** Specifies whether or not to hide the last scale label. */ + hideLastLabel?: boolean; + /** Specifies whether or not to hide the last major tick on the scale. */ + hideLastTick?: boolean; + /** Specifies common options for scale labels. */ + label?: BaseScaleLabel; + /** Specifies options of the gauge's major ticks. */ + majorTick?: ScaleMajorTick; + /** Specifies options of the gauge's minor ticks. */ + minorTick?: ScaleTick; + /** Specifies the start value for the scale of the gauge. */ + startValue?: number; + } + export interface BaseValueIndicator { + /** Specifies the type of subvalue indicators. */ + type?: string; + /** Specifies the background color for the indicator of the rangeBar type. */ + backgroundColor?: string; + /** Specifies the base value for the indicator of the rangeBar type. */ + baseValue?: number; + /** Specifies a color of the indicator. */ + color?: string; + /** Specifies the range bar size for an indicator of the rangeBar type. */ + size?: number; + text?: { + /** Specifies a callback function that returns the text to be displayed in an indicator. */ + customizeText?: (indicatedValue: { value: number; valueText: string }) => string; + font?: viz.core.Font; + /** Specifies a format for the text displayed in an indicator. */ + format?: string; + /** Specifies the range bar's label indent in pixels. */ + indent?: number; + /** Specifies a precision for the formatted value displayed by an indicator. */ + precision?: number; + }; + offset?: number; + length?: number; + width?: number; + /** Specifies the length of an arrow for the indicator of the textCloud type in pixels. */ + arrowLength?: number; + /** Sets the array of colors to be used for coloring subvalue indicators. */ + palette?: Array; + /** Specifies the distance between the needle and the center of a gauge for the indicator of a needle-like type. */ + indentFromCenter?: number; + /** Specifies the second color for the indicator of the twoColorNeedle type. */ + secondColor?: string; + /** Specifies the length of a twoNeedleColor type indicator tip as a percentage. */ + secondFraction?: number; + /** Specifies the spindle's diameter in pixels for the indicator of a needle-like type. */ + spindleSize?: number; + /** Specifies the inner diameter in pixels, so that the spindle has the shape of a ring. */ + spindleGapSize?: number; + /** Specifies the orientation of the rangeBar indicator on a vertically oriented dxLinearGauge widget. */ + horizontalOrientation?: string; + /** Specifies the orientation of the rangeBar indicator on a horizontally oriented dxLinearGauge widget. */ + verticalOrientation?: string; + } + export interface SharedGaugeOptions { + /** Specifies animation options. */ + animation?: viz.core.Animation; + /** Specifies the appearance of the loading indicator. */ + loadingIndicator?: viz.core.LoadingIndicator; + /** Specifies whether to redraw the widget when the size of the parent browser window changes or a mobile device rotates. */ + redrawOnResize?: boolean; + /** Specifies the size of the widget in pixels. */ + size?: viz.core.Size; + /** Specifies a subtitle for a gauge. */ + subtitle?: { + /** Specifies font options for the subtitle. */ + font?: viz.core.Font; + /** Specifies a text for the subtitle. */ + text?: string; + }; + /** Specifies a title for a gauge. */ + title?: { + /** Specifies font options for the title. */ + font?: viz.core.Font; + /** Specifies a title's position on the gauge. */ + position?: string; + /** Specifies a text for the title. */ + text?: string; + }; + /** Specifies options for gauge tooltips. */ + tooltip?: viz.core.Tooltip; + /** A handler for the tooltipShown event. */ + onTooltipShown?: (e: { + component: dxBaseGauge; + element: Element; + target: {}; + }) => void; + /** A handler for the tooltipHidden event. */ + onTooltipHidden?: (e: { + component: dxBaseGauge; + element: Element; + target: {}; + }) => void; + } + export interface BaseGaugeOptions extends viz.core.BaseWidgetOptions, SharedGaugeOptions { + /** Specifies the color of the parent page element. */ + containerBackgroundColor?: string; + /** Specifies the blank space in pixels between the widget's extreme elements and the boundaries of the area provided for the widget (see the size option). */ + margin?: viz.core.Margins; + /** Specifies options of the gauge's range container. */ + rangeContainer?: BaseRangeContainer; + /** Specifies a gauge's scale options. */ + scale?: BaseScale; + /** Specifies the appearance options of subvalue indicators. */ + subvalueIndicator?: BaseValueIndicator; + /** Specifies a set of subvalues to be designated by the subvalue indicators. */ + subvalues?: Array; + /** Specifies the main value on a gauge. */ + value?: number; + /** Specifies the appearance options of the value indicator. */ + valueIndicator?: BaseValueIndicator; + } + /** A gauge widget. */ + export class dxBaseGauge extends viz.core.BaseWidget { + /** Displays the loading indicator. */ + showLoadingIndicator(): void; + /** Conceals the loading indicator. */ + hideLoadingIndicator(): void; + /** Redraws a widget. */ + render(): void; + /** Returns the main gauge value. */ + value(): number; + /** Updates a gauge value. */ + value(value: number): void; + /** Returns an array of gauge subvalues. */ + subvalues(): Array; + /** Updates gauge subvalues. */ + subvalues(subvalues: Array): void; + } + export interface LinearRangeContainer extends BaseRangeContainer { + /** Specifies the orientation of the range container on a vertically oriented dxLinearGauge widget. */ + horizontalOrientation?: string; + /** Specifies the orientation of a range container on a horizontally oriented dxLinearGauge widget. */ + verticalOrientation?: string; + /** Specifies the width of the range container's start and end boundaries in the dxLinearGauge widget. */ + width?: any; + /** Specifies an end width of a range container. */ + end?: number; + /** Specifies a start width of a range container. */ + start?: number; + } + export interface LinearScaleLabel extends BaseScaleLabel { + /** Specifies the spacing between scale labels and ticks. */ + indentFromTick?: number; + } + export interface LinearScale extends BaseScale { + /** Specifies the orientation of scale ticks on a vertically oriented dxLinearGauge widget. */ + horizontalOrientation?: string; + label?: LinearScaleLabel; + /** Specifies the orientation of scale ticks on a horizontally oriented dxLinearGauge widget. */ + verticalOrientation?: string; + } + export interface dxLinearGaugeOptions extends BaseGaugeOptions { + /** Specifies the options required to set the geometry of the dxLinearGauge widget. */ + geometry?: { + /** Indicates whether to display the dxLinearGauge widget vertically or horizontally. */ + orientation?: string; + }; + /** Specifies gauge range container options. */ + rangeContainer?: LinearRangeContainer; + scale?: LinearScale; + } + /** A widget that represents a gauge with a linear scale. */ + export class dxLinearGauge extends dxBaseGauge { + constructor(element: JQuery, options?: dxLinearGaugeOptions); + constructor(element: Element, options?: dxLinearGaugeOptions); + } + export interface CircularRangeContainer extends BaseRangeContainer { + /** Specifies the orientation of the range container in the dxCircularGauge widget. */ + orientation?: string; + /** Specifies the range container's width in pixels. */ + width?: number; + } + export interface CircularScaleLabel extends BaseScaleLabel { + /** Specifies the spacing between scale labels and ticks. */ + indentFromTick?: number; + } + export interface CircularScale extends BaseScale { + label?: CircularScaleLabel; + /** Specifies the orientation of scale ticks. */ + orientation?: string; + } + export interface dxCircularGaugeOptions extends BaseGaugeOptions { + /** Specifies the options required to set the geometry of the dxCircularGauge widget. */ + geometry?: { + /** Specifies the end angle of the circular gauge's arc. */ + endAngle?: number; + /** Specifies the start angle of the circular gauge's arc. */ + startAngle?: number; + }; + /** Specifies gauge range container options. */ + rangeContainer?: CircularRangeContainer; + scale?: CircularScale; + } + /** A widget that represents a gauge with a circular scale. */ + export class dxCircularGauge extends dxBaseGauge { + constructor(element: JQuery, options?: dxCircularGaugeOptions); + constructor(element: Element, options?: dxCircularGaugeOptions); + } + export interface dxBarGaugeOptions extends viz.core.BaseWidgetOptions, SharedGaugeOptions { + /** Specifies a color for the remaining segment of the bar's track. */ + backgroundColor?: string; + /** Specifies a distance between bars in pixels. */ + barSpacing?: number; + /** Specifies a base value for bars. */ + baseValue?: number; + /** Specifies an end value for the gauge's invisible scale. */ + endValue?: number; + /** Defines the shape of the gauge's arc. */ + geometry?: { + /** Specifies the end angle of the bar gauge's arc. */ + endAngle?: number; + /** Specifies the start angle of the bar gauge's arc. */ + startAngle?: number; + }; + /** Specifies the options of the labels that accompany gauge bars. */ + label?: { + /** Specifies a color for the label connector text. */ + connectorColor?: string; + /** Specifies the width of the label connector in pixels. */ + connectorWidth?: number; + /** Specifies a callback function that returns a text for labels. */ + customizeText?: (barValue: { value: number; valueText: string }) => string; + /** Specifies font options for bar labels. */ + font?: viz.core.Font; + /** Specifies a format for bar labels. */ + format?: string; + /** Specifies the distance between the upper bar and bar labels in pixels. */ + indent?: number; + /** Specifies a precision for the formatted value displayed by labels. */ + precision?: number; + /** Specifies whether bar labels appear on a gauge or not. */ + visible?: boolean; + }; + /** Sets the name of the palette or an array of colors to be used for coloring the gauge range container. */ + palette?: string; + /** Defines the radius of the bar that is closest to the center relatively to the radius of the topmost bar. */ + relativeInnerRadius?: number; + /** Specifies a start value for the gauge's invisible scale. */ + startValue?: number; + /** Specifies the array of values to be indicated on a bar gauge. */ + values?: Array; + } + /** A circular bar widget. */ + export class dxBarGauge extends viz.core.BaseWidget { + constructor(element: JQuery, options?: dxBarGaugeOptions); + constructor(element: Element, options?: dxBarGaugeOptions); + /** Displays the loading indicator. */ + showLoadingIndicator(): void; + /** Conceals the loading indicator. */ + hideLoadingIndicator(): void; + /** Redraws the widget. */ + render(): void; + /** Returns an array of gauge values. */ + values(): Array; + /** Updates the values displayed by a gauge. */ + values(values: Array): void; + } +} +interface JQuery { + dxLinearGauge(options?: DevExpress.viz.gauges.dxLinearGaugeOptions): JQuery; + dxLinearGauge(methodName: string, ...params: any[]): any; + dxLinearGauge(methodName: "instance"): DevExpress.viz.gauges.dxLinearGauge; + dxCircularGauge(options?: DevExpress.viz.gauges.dxCircularGaugeOptions): JQuery; + dxCircularGauge(methodName: string, ...params: any[]): any; + dxCircularGauge(methodName: "instance"): DevExpress.viz.gauges.dxCircularGauge; + dxBarGauge(options?: DevExpress.viz.gauges.dxBarGaugeOptions): JQuery; + dxBarGauge(methodName: string, ...params: any[]): any; + dxBarGauge(methodName: "instance"): DevExpress.viz.gauges.dxBarGauge; +} +declare module DevExpress.viz.rangeSelector { + export interface dxRangeSelectorOptions extends viz.core.BaseWidgetOptions { + /** Specifies the options for the range selector's background. */ + background?: { + /** Specifies the background color for the dxRangeSelector. */ + color?: string; + /** Specifies image options. */ + image?: { + /** Specifies a location for the image in the background of a range selector. */ + location?: string; + /** Specifies the image's URL. */ + url?: string; + }; + /** Indicates whether or not the background (background color and/or image) is visible. */ + visible?: boolean; + }; + /** Specifies the dxRangeSelector's behavior options. */ + behavior?: { + /** Indicates whether or not you can swap sliders. */ + allowSlidersSwap?: boolean; + /** +Indicates whether or not animation is enabled. + */ + animationEnabled?: boolean; + /** Specifies when to call the onSelectedRangeChanged function. */ + callSelectedRangeChanged?: string; + /** Indicates whether or not an end user can specify the range using a mouse, without the use of sliders. */ + manualRangeSelectionEnabled?: boolean; + /** Indicates whether or not an end user can shift the selected range to the required location on a scale by clicking. */ + moveSelectedRangeByClick?: boolean; + /** Indicates whether to snap a slider to ticks. */ + snapToTicks?: boolean; + }; + /** Specifies the options required to display a chart as the range selector's background. */ + chart?: { + /** Specifies a coefficient for determining an indent from the bottom background boundary to the lowest chart point. */ + bottomIndent?: number; + /** An object defining the common configuration options for the chart’s series. */ + commonSeriesSettings?: viz.charts.CommonSeriesSettings; + /** An object providing options for managing data from a data source. */ + dataPrepareSettings?: { + /** Specifies whether or not to validate values from a data source. */ + checkTypeForAllData?: boolean; + /** Specifies whether or not to convert the values from a data source into the data type of an axis. */ + convertToAxisDataType?: boolean; + /** Specifies how to sort series points. */ + sortingMethod?: any; + }; + /** Specifies a value indicating whether all bars in a series must have the same width, or may have different widths if any points in other series are missing. */ + equalBarWidth?: any; + /** An object defining the chart’s series. */ + series?: Array; + /** Defines options for the series template. */ + seriesTemplate?: viz.charts.SeriesTemplate; + /** Specifies a coefficient for determining an indent from the background's top boundary to the topmost chart point. */ + topIndent?: number; + /** Specifies whether or not to filter the series points depending on their quantity. */ + useAggregation?: boolean; + /** Specifies options for the chart's value axis. */ + valueAxis?: { + /** Indicates whether or not the chart's value axis must be inverted. */ + inverted?: boolean; + /** Specifies the value to be raised to a power when generating ticks for a logarithmic value axis. */ + logarithmBase?: number; + /** Specifies the maximum value of the chart's value axis. */ + max?: number; + /** Specifies the minimum value of the chart's value axis. */ + min?: number; + /** Specifies the type of the value axis. */ + type?: string; + /** Specifies the desired type of axis values. */ + valueType?: string; + }; + }; + /** Specifies the color of the parent page element. */ + containerBackgroundColor?: string; + /** Specifies a data source for the scale values and for the chart at the background. */ + dataSource?: any; + /** Specifies the data source field that provides data for the scale. */ + dataSourceField?: string; + /** Specifies the appearance of the loading indicator. */ + loadingIndicator?: viz.core.LoadingIndicator; + /** Specifies the blank space in pixels between the dxRangeSelector widget's extreme elements and the boundaries of the area provided for the widget (see size). */ + margin?: viz.core.Margins; + /** Specifies whether to redraw the widget when the size of the parent browser window changes or a mobile device rotates. */ + redrawOnResize?: boolean; + /** Specifies options of the range selector's scale. */ + scale?: { + /** Specifies the scale's end value. */ + endValue?: any; + /** Specifies common options for scale labels. */ + label?: { + /** Specifies a callback function that returns the text to be displayed in scale labels. */ + customizeText?: (scaleValue: { value: any; valueText: string; }) => string; + /** Specifies font options for the text displayed in the range selector's scale labels. */ + font?: viz.core.Font; + /** Specifies a format for the text displayed in scale labels. */ + format?: string; + /** Specifies a precision for the formatted value displayed in the scale labels. */ + precision?: number; + /** Specifies a spacing between scale labels and the background bottom edge. */ + topIndent?: number; + /** Specifies whether or not the scale's labels are visible. */ + visible?: boolean; + }; + /** Specifies the value to be raised to a power when generating ticks for a logarithmic scale. */ + logarithmBase?: number; + /** Specifies an interval between major ticks. */ + majorTickInterval?: any; + /** Specifies options for the date-time scale's markers. */ + marker?: { + /** Defines the options that can be set for the text that is displayed by the scale markers. */ + label?: { + /** Specifies a callback function that returns the text to be displayed in scale markers. */ + customizeText?: (markerValue: { value: any; valueText: string }) => string; + /** Specifies a format for the text displayed in scale markers. */ + format?: string; + }; + /** Specifies the height of the marker's separator. */ + separatorHeight?: number; + /** Specifies the space between the marker label and the marker separator. */ + textLeftIndent?: number; + /** Specifies the space between the marker's label and the top edge of the marker's separator. */ + textTopIndent?: number; + /** Specified the indent between the marker and the scale lables. */ + topIndent?: number; + /** Indicates whether scale markers are visible. */ + visible?: boolean; + }; + /** Specifies the maximum range that can be selected. */ + maxRange?: any; + /** Specifies the number of minor ticks between neighboring major ticks. */ + minorTickCount?: number; + /** +Specifies an interval between minor ticks. + */ + minorTickInterval?: any; + /** Specifies the minimum range that can be selected. */ + minRange?: any; + /** Specifies the height of the space reserved for the scale in pixels. */ + placeholderHeight?: number; + /** Indicates whether or not to set ticks of a date-time scale at the beginning of each date-time interval. */ + setTicksAtUnitBeginning?: boolean; + /** Specifies whether or not to show ticks for the boundary scale values, when neither major ticks nor minor ticks are created for these values. */ + showCustomBoundaryTicks?: boolean; + /** Indicates whether or not to show minor ticks on the scale. */ + showMinorTicks?: boolean; + /** Specifies the scale's start value. */ + startValue?: any; + /** Specifies options defining the appearance of scale ticks. */ + tick?: { + /** Specifies the color of scale ticks (both major and minor ticks). */ + color?: string; + /** Specifies the opacity of scale ticks (both major and minor ticks). */ + opacity?: number; + /** Specifies the width of the scale's ticks (both major and minor ticks). */ + width?: number; + }; + /** Specifies the type of the scale. */ + type?: string; + /** Specifies whether or not to expand the current tick interval if labels overlap each other. */ + useTicksAutoArrangement?: boolean; + /** Specifies the type of values on the scale. */ + valueType?: string; + /** Specifies the order of arguments on a discrete scale. */ + categories?: Array; + }; + /** Specifies the range to be selected when displaying the dxRangeSelector. */ + selectedRange?: { + /** Specifies the start value of the range to be selected when displaying the dxRangeSelector widget on a page. */ + startValue?: any; + /** Specifies the end value of the range to be selected when displaying the dxRangeSelector widget on a page. */ + endValue?: any; + }; + /** Specifies the color of the selected range. */ + selectedRangeColor?: string; + /** Range selector's indent options. */ + indent?: { + /** Specifies range selector's left indent. */ + left?: number; + /** Specifies range selector's right indent. */ + right?: number; + }; + selectedRangeChanged?: (selectedRange: { startValue: any; endValue: any; }) => void; + /** A handler for the selectedRangeChanged event. */ + onSelectedRangeChanged?: (e: { + startValue: any; + endValue: any; + component: dxRangeSelector; + element: Element; + }) => void; + /** Specifies range selector shutter options. */ + shutter?: { + /** Specifies shutter color. */ + color?: string; + /** Specifies the opacity of the color of shutters. */ + opacity?: number; + }; + /** Specifies in pixels the size of the dxRangeSelector widget. */ + size?: viz.core.Size; + /** Specifies the appearance of the range selector's slider handles. */ + sliderHandle?: { + /** Specifies the color of the slider handles. */ + color?: string; + /** Specifies the opacity of the slider handles. */ + opacity?: number; + /** Specifies the width of the slider handles. */ + width?: number; + }; + /** Defines the options of the range selector slider markers. */ + sliderMarker?: { + /** Specifies the color of the slider markers. */ + color?: string; + /** Specifies a callback function that returns the text to be displayed by slider markers. */ + customizeText?: (scaleValue: { value: any; valueText: any; }) => string; + /** Specifies font options for the text displayed by the range selector slider markers. */ + font?: viz.core.Font; + /** Specifies a format for the text displayed in slider markers. */ + format?: string; + /** Specifies the color used for the slider marker text when the currently selected range does not match the minRange and maxRange values. */ + invalidRangeColor?: string; + /** + * Specifies the empty space between the marker's border and the marker’s text. + * @deprecated Use the 'paddingTopBottom' and 'paddingLeftRight' options instead + */ + padding?: number; + /** Specifies the empty space between the marker's top and bottom borders and the marker's text. */ + paddingTopBottom?: number; + /** Specifies the empty space between the marker's left and right borders and the marker's text. */ + paddingLeftRight?: number; + /** Specifies the placeholder height of the slider marker. */ + placeholderHeight?: number; + /** + * Specifies in pixels the height and width of the space reserved for the range selector slider markers. + * @deprecated Use the 'placeholderHeight' and 'indent' options instead + */ + placeholderSize?: { + /** Specifies the height of the placeholder for the left and right slider markers. */ + height?: number; + /** Specifies the width of the placeholder for the left and right slider markers. */ + width?: { + /** Specifies the width of the left slider marker's placeholder. */ + left?: number; + /** Specifies the width of the right slider marker's placeholder. */ + right?: number; + }; + }; + /** Specifies a precision for the formatted value displayed in slider markers. */ + precision?: number; + /** Indicates whether or not the slider markers are visible. */ + visible?: boolean; + }; + } + /** A widget that allows end users to select a range of values on a scale. */ + export class dxRangeSelector extends viz.core.BaseWidget { + constructor(element: JQuery, options?: dxRangeSelectorOptions); + constructor(element: Element, options?: dxRangeSelectorOptions); + /** Displays the loading indicator. */ + showLoadingIndicator(): void; + /** Conceals the loading indicator. */ + hideLoadingIndicator(): void; + /** Redraws a widget. */ + render(skipChartAnimation?: boolean): void; + /** Returns the currently selected range. */ + getSelectedRange(): { startValue: any; endValue: any; }; + /** Sets a specified range. */ + setSelectedRange(selectedRange: { startValue: any; endValue: any; }): void; + } +} +interface JQuery { + dxRangeSelector(options?: DevExpress.viz.rangeSelector.dxRangeSelectorOptions): JQuery; + dxRangeSelector(methodName: string, ...params: any[]): any; + dxRangeSelector(methodName: "instance"): DevExpress.viz.rangeSelector.dxRangeSelector; +} +declare module DevExpress.viz.map { + /** This section describes the fields and methods that can be used in code to manipulate the Area object. */ + export interface Area { + /** Contains the element type. */ + type: string; + /** Return the value of an attribute. */ + attribute(name: string): any; + /** Provides information about the selection state of an area. */ + selected(): boolean; + /** Sets a new selection state for an area. */ + selected(state: boolean): void; + /** Applies the area settings specified as a parameter and updates the area appearance. */ + applySettings(settings: any): void; + } + /** This section describes the fields and methods that can be used in code to manipulate the Markers object. */ + export interface Marker { + /** Contains the descriptive text accompanying the map marker. */ + text: string; + /** Contains the type of the element. */ + type: string; + /** Contains the URL of an image map marker. */ + url: string; + /** Contains the value of a bubble map marker. */ + value: number; + /** Contains the values of a pie map marker. */ + values: Array; + /** Returns the value of an attribute. */ + attribute(name: string): any; + /** Returns the coordinates of a specific marker. */ + coordinates(): Array; + /** Provides information about the selection state of a marker. */ + selected(): boolean; + /** Sets a new selection state for a marker. */ + selected(state: boolean): void; + /** Applies the marker settings specified as a parameter and updates the marker appearance. */ + applySettings(settings: any): void; + } + export interface AreaSettings { + /** Specifies the width of the area border in pixels. */ + borderWidth?: number; + /** Specifies a color for the area border. */ + borderColor?: string; + click?: any; + /** Specifies a color for an area. */ + color?: string; + /** Specifies the function that customizes each area individually. */ + customize?: (areaInfo: Area) => AreaSettings; + /** Specifies a color for the area border when the area is hovered over. */ + hoveredBorderColor?: string; + /** Specifies the pixel-measured width of the area border when the area is hovered over. */ + hoveredBorderWidth?: number; + /** Specifies a color for an area when this area is hovered over. */ + hoveredColor?: string; + /** Specifies whether or not to change the appearance of an area when it is hovered over. */ + hoverEnabled?: boolean; + /** Configures area labels. */ + label?: { + /** Specifies the data field that provides data for area labels. */ + dataField?: string; + /** Enables area labels. */ + enabled?: boolean; + /** Specifies font options for area labels. */ + font?: viz.core.Font; + }; + /** Specifies the name of the palette or a custom range of colors to be used for coloring a map. */ + palette?: any; + /** Specifies the number of colors in a palette. */ + paletteSize?: number; + /** Allows you to paint areas with similar attributes in the same color. */ + colorGroups?: Array; + /** Specifies the field that provides data to be used for coloring areas. */ + colorGroupingField?: string; + /** Specifies a color for the area border when the area is selected. */ + selectedBorderColor?: string; + /** Specifies a color for an area when this area is selected. */ + selectedColor?: string; + /** Specifies the pixel-measured width of the area border when the area is selected. */ + selectedBorderWidth?: number; + selectionChanged?: (area: Area) => void; + /** Specifies whether single or multiple areas can be selected on a vector map. */ + selectionMode?: string; + } + export interface MarkerSettings { + /** Specifies a color for the marker border. */ + borderColor?: string; + /** Specifies the width of the marker border in pixels. */ + borderWidth?: number; + click?: any; + /** Specifies a color for a marker of the dot or bubble type. */ + color?: string; + /** Specifies the function that customizes each marker individually. */ + customize?: (markerInfo: Marker) => MarkerSettings; + font?: Object; + /** Specifies the pixel-measured width of the marker border when the marker is hovered over. */ + hoveredBorderWidth?: number; + /** Specifies a color for the marker border when the marker is hovered over. */ + hoveredBorderColor?: string; + /** Specifies a color for a marker of the dot or bubble type when this marker is hovered over. */ + hoveredColor?: string; + /** Specifies whether or not to change the appearance of a marker when it is hovered over. */ + hoverEnabled?: boolean; + /** Specifies marker label options. */ + label?: { + /** Enables marker labels. */ + enabled?: boolean; + /** Specifies font options for marker labels. */ + font?: viz.core.Font; + }; + /** Specifies the pixel-measured diameter of the marker that represents the biggest value. Setting this option makes sense only if you use markers of the bubble type. */ + maxSize?: number; + /** Specifies the pixel-measured diameter of the marker that represents the smallest value. Setting this option makes sense only if you use markers of the bubble type. */ + minSize?: number; + /** Specifies the opacity of markers. Setting this option makes sense only if you use markers of the bubble type. */ + opacity?: number; + /** Specifies the pixel-measured width of the marker border when the marker is selected. */ + selectedBorderWidth?: number; + /** Specifies a color for the marker border when the marker is selected. */ + selectedBorderColor?: string; + /** Specifies a color for a marker of the dot or bubble type when this marker is selected. */ + selectedColor?: string; + selectionChanged?: (marker: Marker) => void; + /** Specifies whether a single or multiple markers can be selected on a vector map. */ + selectionMode?: string; + /** Specifies the size of markers. Setting this option makes sense for any type of marker except bubble. */ + size?: number; + /** Specifies the type of markers to be used on the map. */ + type?: string; + /** Specifies the name of a palette or a custom set of colors to be used for coloring markers of the pie type. */ + palette?: any; + /** Allows you to paint markers with similar attributes in the same color. */ + colorGroups?: Array; + /** Specifies the field that provides data to be used for coloring markers. */ + colorGroupingField?: string; + /** Allows you to display bubbles with similar attributes in the same size. */ + sizeGroups?: Array; + /** Specifies the field that provides data to be used for sizing bubble markers. */ + sizeGroupingField?: string; + } + export interface dxVectorMapOptions extends viz.core.BaseWidgetOptions { + /** An object specifying options for the map areas. */ + areaSettings?: AreaSettings; + /** Specifies the options for the map background. */ + background?: { + /** Specifies a color for the background border. */ + borderColor?: string; + /** Specifies a color for the background. */ + color?: string; + }; + /** Specifies the positioning of a map in geographical coordinates. */ + bounds?: Array; + /** Specifies the options of the control bar. */ + controlBar?: { + /** Specifies a color for the outline of the control bar elements. */ + borderColor?: string; + /** Specifies a color for the inner area of the control bar elements. */ + color?: string; + /** Specifies whether or not to display the control bar. */ + enabled?: boolean; + /** Specifies the margin of the control bar in pixels. */ + margin?: number; + /** Specifies the position of the control bar. */ + horizontalAlignment?: string; + /** Specifies the position of the control bar. */ + verticalAlignment?: string; + /** Specifies the opacity of the Control_Bar. */ + opacity?: number; + }; + /** Specifies the appearance of the loading indicator. */ + loadingIndicator?: viz.core.LoadingIndicator; + /** Specifies a data source for the map area. */ + mapData?: any; + /** Specifies a data source for the map markers. */ + markers?: any; + /** An object specifying options for the map markers. */ + markerSettings?: MarkerSettings; + /** Specifies the size of the dxVectorMap widget. */ + size?: viz.core.Size; + /** Specifies tooltip options. */ + tooltip?: viz.core.Tooltip; + /** Configures map legends. */ + legends?: Array; + /** Specifies whether or not the map should respond when a user rolls the mouse wheel. */ + wheelEnabled?: boolean; + /** Specifies whether the map should respond to touch gestures. */ + touchEnabled?: boolean; + /** Disables the zooming capability. */ + zoomingEnabled?: boolean; + /** Specifies the geographical coordinates of the center for a map. */ + center?: Array; + centerChanged?: (center: Array) => void; + /** A handler for the centerChanged event. */ + onCenterChanged?: (e: { + center: Array; + component: dxVectorMap; + element: Element; + }) => void; + /** A handler for the tooltipShown event. */ + onTooltipShown?: (e: { + component: dxVectorMap; + element: Element; + target: {}; + }) => void; + /** A handler for the tooltipHidden event. */ + onTooltipHidden?: (e: { + component: dxVectorMap; + element: Element; + target: {}; + }) => void; + /** Specifies a number that is used to zoom a map initially. */ + zoomFactor?: number; + /** Specifies a map's maximum zoom factor. */ + maxZoomFactor?: number; + zoomFactorChanged?: (zoomFactor: number) => void; + /** A handler for the zoomFactorChanged event. */ + onZoomFactorChanged?: (e: { + zoomFactor: number; + component: dxVectorMap; + element: Element; + }) => void; + click?: any; + /** A handler for the click event. */ + onClick?: any; + /** A handler for the areaClick event. */ + onAreaClick?: any; + /** A handler for the areaSelectionChanged event. */ + onAreaSelectionChanged?: (e: { + target: Area; + component: dxVectorMap; + element: Element; + }) => void; + /** A handler for the markerClick event. */ + onMarkerClick?: any; + /** A handler for the markerSelectionChanged event. */ + onMarkerSelectionChanged?: (e: { + target: Marker; + component: dxVectorMap; + element: Element; + }) => void; + /** Disables the panning capability. */ + panningEnabled?: boolean; + } + export interface Legend extends viz.core.BaseLegend { + /** Specifies text for legend items. */ + customizeText?: (itemInfo: { start: number; end: number; index: number; color: string; size: number; }) => string; + /** Specifies text for a hint that appears when a user hovers the mouse pointer over the text of a legend item. */ + customizeHint?: (itemInfo: { start: number; end: number; index: number; color: string; size: number }) => string; + /** Specifies the source of data for the legend. */ + source?: string; + } + /** A vector map widget. */ + export class dxVectorMap extends viz.core.BaseWidget { + constructor(element: JQuery, options?: dxVectorMapOptions); + constructor(element: Element, options?: dxVectorMapOptions); + /** Displays the loading indicator. */ + showLoadingIndicator(): void; + /** Conceals the loading indicator. */ + hideLoadingIndicator(): void; + /** Redraws a widget. */ + render(): void; + /** Gets the current coordinates of the map center. */ + center(): Array; + /** Sets the coordinates of the map center. */ + center(centerCoordinates: Array): void; + /** Deselects all the selected areas on a map. The areas are displayed in their initial style after. */ + clearAreaSelection(): void; + /** Deselects all the selected markers on a map. The markers are displayed in their initial style after. */ + clearMarkerSelection(): void; + /** Deselects all the selected area and markers on a map at once. The areas and markers are displayed in their initial style after. */ + clearSelection(): void; + /** Converts client area coordinates into map coordinates. */ + convertCoordinates(x: number, y: number): Array; + /** Returns an array with all the map areas. */ + getAreas(): Array; + /** Returns an array with all the map markers. */ + getMarkers(): Array; + /** Gets the current coordinates of the map viewport. */ + viewport(): Array; + /** Sets the coordinates of the map viewport. */ + viewport(viewportCoordinates: Array): void; + /** Gets the current value of the map zoom factor. */ + zoomFactor(): number; + /** Sets the value of the map zoom factor. */ + zoomFactor(zoomFactor: number): void; + } +} +interface JQuery { + dxVectorMap(options?: DevExpress.viz.map.dxVectorMapOptions): JQuery; + dxVectorMap(methodName: string, ...params: any[]): any; + dxVectorMap(methodName: "instance"): DevExpress.viz.map.dxVectorMap; +} +declare module DevExpress.viz.sparklines { + export interface SparklineTooltip extends viz.core.Tooltip { + /** + * Specifies how a tooltip is horizontally aligned relative to the graph. + * @deprecated Tooltip alignment is no more available. + */ + horizontalAlignment?: string; + /** + * Specifies how a tooltip is vertically aligned relative to the graph. + * @deprecated Tooltip alignment is no more available. + */ + verticalAlignment?: string; + } + export interface BaseSparklineOptions extends viz.core.BaseWidgetOptions { + /** Specifies the blank space between the widget's extreme elements and the boundaries of the area provided for the widget in pixels. */ + margin?: viz.core.Margins; + /** Specifies the size of the widget. */ + size?: viz.core.Size; + /** Specifies tooltip options. */ + tooltip?: SparklineTooltip; + /** A handler for the tooltipShown event. */ + onTooltipShown?: (e: { + component: BaseSparkline; + element: Element; + }) => void; + /** A handler for the tooltipHidden event. */ + onTooltipHidden?: (e: { + component: BaseSparkline; + element: Element; + }) => void; + } + /** Overridden by descriptions for particular widgets. */ + export class BaseSparkline extends viz.core.BaseWidget { + /** Redraws a widget. */ + render(): void; + } + export interface dxBulletOptions extends BaseSparkline { + /** Specifies a color for the bullet bar. */ + color?: string; + /** Specifies an end value for the invisible scale. */ + endScaleValue?: number; + /** Specifies whether or not to show the target line. */ + showTarget?: boolean; + /** Specifies whether or not to show the line indicating zero on the invisible scale. */ + showZeroLevel?: boolean; + /** Specifies a start value for the invisible scale. */ + startScaleValue?: number; + /** Specifies the value indicated by the target line. */ + target?: number; + /** Specifies a color for both the target and zero level lines. */ + targetColor?: string; + /** Specifies the width of the target line. */ + targetWidth?: number; + /** Specifies the primary value indicated by the bullet bar. */ + value?: number; + } + /** A bullet graph widget. */ + export class dxBullet extends BaseSparkline { + constructor(element: JQuery, options?: dxBulletOptions); + constructor(element: Element, options?: dxBulletOptions); + } + export interface dxSparklineOptions extends BaseSparklineOptions { + /** Specifies the data source field that provides arguments for a sparkline. */ + argumentField?: string; + /** Sets a color for the bars indicating negative values. Available for a sparkline of the bar type only. */ + barNegativeColor?: string; + /** Sets a color for the bars indicating positive values. Available for a sparkline of the bar type only. */ + barPositiveColor?: string; + /** Specifies a data source for the sparkline. */ + dataSource?: Array; + /** Sets a color for the boundary of both the first and last points on a sparkline. */ + firstLastColor?: string; + /** Specifies whether a sparkline ignores null data points or not. */ + ignoreEmptyPoints?: boolean; + /** Sets a color for a line on a sparkline. Available for the sparklines of the line- and area-like types. */ + lineColor?: string; + /** Specifies a width for a line on a sparkline. Available for the sparklines of the line- and area-like types. */ + lineWidth?: number; + /** Sets a color for the bars indicating the values that are less than the winloss threshold. Available for a sparkline of the winloss type only. */ + lossColor?: string; + /** Sets a color for the boundary of the maximum point on a sparkline. */ + maxColor?: string; + /** Sets a color for the boundary of the minimum point on a sparkline. */ + minColor?: string; + /** Sets a color for points on a sparkline. Available for the sparklines of the line- and area-like types. */ + pointColor?: string; + /** Specifies the diameter of sparkline points in pixels. Available for the sparklines of line- and area-like types. */ + pointSize?: number; + /** Specifies a symbol to use as a point marker on a sparkline. Available for the sparklines of the line- and area-like types. */ + pointSymbol?: string; + /** Specifies whether or not to indicate both the first and last values on a sparkline. */ + showFirstLast?: boolean; + /** Specifies whether or not to indicate both the minimum and maximum values on a sparkline. */ + showMinMax?: boolean; + /** Determines the type of a sparkline. */ + type?: string; + /** Specifies the data source field that provides values for a sparkline. */ + valueField?: string; + /** Sets a color for the bars indicating the values greater than a winloss threshold. Available for a sparkline of the winloss type only. */ + winColor?: string; + /** Specifies a value that serves as a threshold for the sparkline of the winloss type. */ + winlossThreshold?: number; + /** Specifies the minimum value of the sparkline value axis. */ + minValue?: number; + /** Specifies the maximum value of the sparkline's value axis. */ + maxValue?: number; + } + /** A sparkline widget. */ + export class dxSparkline extends BaseSparkline { + constructor(element: JQuery, options?: dxSparklineOptions); + constructor(element: Element, options?: dxSparklineOptions); + } +} +interface JQuery { + dxBullet(options?: DevExpress.viz.sparklines.dxBulletOptions): JQuery; + dxBullet(methodName: string, ...params: any[]): any; + dxBullet(methodName: "instance"): DevExpress.viz.sparklines.dxBullet; + dxSparkline(options?: DevExpress.viz.sparklines.dxSparklineOptions): JQuery; + dxSparkline(methodName: string, ...params: any[]): any; + dxSparkline(methodName: "instance"): DevExpress.viz.sparklines.dxSparkline; +} diff --git a/devextreme/dx.devextreme.d.ts b/devextreme/dx.devextreme.d.ts index aff710888..d0a345a04 100644 --- a/devextreme/dx.devextreme.d.ts +++ b/devextreme/dx.devextreme.d.ts @@ -1,4 +1,4 @@ -// Type definitions for DevExtreme 15.1.5 +// Type definitions for DevExtreme 15.1.6 // Project: http://js.devexpress.com/ // Definitions by: DevExpress Inc. // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -63,7 +63,7 @@ declare module DevExpress { export function processHardwareBackButton(): void; /** Specifies whether or not the entire application/site supports right-to-left representation. */ export var rtlEnabled: boolean; - /** Registers a new component in the DevExpress.ui namespace, and a jQuery plugin and Knockout binding for the required component. */ + /** Registers a new component in the DevExpress.ui namespace as a jQuery plugin, Angular directive and Knockout binding. */ export function registerComponent(name: string, componentClass: Object): void; /** Registers a new component in the specified namespace as a jQuery plugin, Angular directive and Knockout binding. */ export function registerComponent(name: string, namespace: Object, componentClass: Object): void; @@ -323,7 +323,7 @@ declare module DevExpress { key(): any; /** Returns the key of the Store item that matches the specified object. */ keyOf(obj: Object): any; - /** Starts loading the data. */ + /** Starts loading data. */ load(obj?: LoadOptions): JQueryPromise; /** Removes the data item specified by the key. */ remove(key: any): JQueryPromise; @@ -427,6 +427,8 @@ declare module DevExpress { select?: Object; /** An array of the strings that represent the names of the navigation properties to be loaded simultaneously with the OData store's entity. */ expand?: Object; + /** Specifies whether or not the DataSource instance requests the total count of items available in the storage. */ + requireTotalCount?: boolean; /** Specifies the initial sort option value. */ sort?: Object; /** Specifies the underlying Store instance used to access data. */ @@ -496,6 +498,10 @@ declare module DevExpress { select(): Object; /** Sets the select option value. */ select(expr: Object): void; + /** Returns the current requireTotalCount option value. */ + requireTotalCount(): boolean; + /** Sets the requireTotalCount option value. */ + requireTotalCount(value: boolean): void; /** Returns the current sort option value. */ sort(): Object; /** Sets the sort option value. */ @@ -817,11 +823,26 @@ declare module DevExpress { export function setTemplateEngine(name: string): void; /** Sets a custom template engine defined via custom compile and render functions. */ export function setTemplateEngine(options: Object): void; - /** An object that serves as a namespace for utility methods that can be helpful when working with the DevExtreme framework and UI widgets. */ - export var utils: { - /** Sets parameters for the viewport meta tag. */ - initMobileViewport(options: { allowZoom?: boolean; allowPan?: boolean; allowSelection?: boolean }): void; - }; + } + /** An object that serves as a namespace for utility methods that can be helpful when working with the DevExtreme framework and UI widgets. */ + export var utils: { + /** Sets parameters for the viewport meta tag. */ + initMobileViewport(options: { allowZoom?: boolean; allowPan?: boolean; allowSelection?: boolean }): void; + }; + /** An object that serves as a namespace for DevExtreme Data Visualization Widgets. */ + export module viz { + /** Applies a theme for the entire page with several DevExtreme visualization widgets. */ + export function currentTheme(theme: string): void; + /** Applies a new theme (with the color scheme defined separately) for the entire page with several DevExtreme visualization widgets. */ + export function currentTheme(platform: string, colorScheme: string): void; + /** Registers a new theme based on the existing one. */ + export function registerTheme(customTheme: Object, baseTheme: string): void; + /** Applies a predefined or registered custom palette to all visualization widgets at once. */ + export function currentPalette(paletteName: string): void; + /** Obtains the color sets of a predefined or registered palette. */ + export function getPalette(paletteName: string): Object; + /** Registers a new palette. */ + export function registerPalette(paletteName: string, palette: Object): void; } } declare module DevExpress.ui { @@ -894,7 +915,7 @@ declare module DevExpress.ui { constructor(element: JQuery, options?: dxTooltipOptions); constructor(element: Element, options?: dxTooltipOptions); } - export interface dxDropDownListOptions extends dxDropDownEditorOptions { + export interface dxDropDownListOptions extends dxDropDownEditorOptions, DataExpressionMixinOptions { /** Returns the value currently displayed by the widget. */ displayValue?: string; /** The minimum number of characters that must be entered into the text box to begin a search. */ @@ -1191,7 +1212,7 @@ declare module DevExpress.ui { /** Updates the dimensions of the scrollable contents. */ update(): void; } - export interface dxRadioGroupOptions extends CollectionWidgetOptions { + export interface dxRadioGroupOptions extends CollectionWidgetOptions, DataExpressionMixinOptions { /** Specifies the radio group layout. */ layout?: string; } @@ -1747,9 +1768,9 @@ declare module DevExpress.ui { /** A Globalize format string specifying the date display format. */ formatString?: string; /** The last date that can be selected within the widget. */ - max?: Date; + max?: any; /** The minimum date that can be selected within the widget. */ - min?: Date; + min?: any; /** The text displayed by the widget when the widget value is not yet specified. This text is also used as a title of the date picker. */ placeholder?: string; /** @@ -1757,8 +1778,8 @@ declare module DevExpress.ui { * @deprecated Use 'pickerType' option instead. */ useCalendar?: boolean; - /** A Date object specifying the date and time currently selected using the date box. */ - value?: Date; + /** An object or a value, specifying the date and time currently selected using the date box. */ + value?: any; /** * Specifies whether or not the widget uses the native HTML input element. * @deprecated Use 'pickerType' option instead. @@ -2661,6 +2682,8 @@ declare module DevExpress.ui { updateAppointment(target: Object, appointment: Object): void; /** Deletes the appointment defined by the parameter from the the data associated with the widget. */ deleteAppointment(appointment: Object): void; + /** Scrolls the scheduler work space to the specified time. */ + scrollToTime(hours: number, minutes: number): void; } export interface dxColorBoxOptions extends dxDropDownEditorOptions { /** Specifies the text displayed on the button that applies changes and closes the drop-down editor. */ @@ -2735,6 +2758,10 @@ declare module DevExpress.ui { onItemExpanded?: Function; /** A handler for the itemCollapsed event. */ onItemCollapsed?: Function; + onItemClick?: Function; + onItemContextMenu?: Function; + onItemRendered?: Function; + onItemHold?: Function; hoverStateEnabled?: boolean; focusStateEnabled?: boolean; } @@ -3795,6 +3822,8 @@ declare module DevExpress.framework { onExecute?: any; /** Indicates whether or not the widget that displays this command is disabled. */ disabled?: boolean; + /** Specifies whether the current command should is rendered when a view is being rendered, or after a view has been shown. */ + renderStage?: string; /** Specifies the name of the icon shown inside the widget associated with this command. */ icon?: string; iconSrc?: string; @@ -4042,6 +4071,36 @@ declare module DevExpress.framework { } } declare module DevExpress.viz.core { + /** + * Applies a theme for the entire page with several DevExtreme visualization widgets. + * @deprecated Use the DevExpress.viz.currentTheme(theme) method instead. + */ + export function currentTheme(theme: string): void; + /** + * Applies a new theme (with the color scheme defined separately) for the entire page with several DevExtreme visualization widgets. + * @deprecated Use the DevExpress.viz.currentTheme(platform, colorScheme) method instead. + */ + export function currentTheme(platform: string, colorScheme: string): void; + /** + * Registers a new theme based on the existing one. + * @deprecated Use the DevExpress.viz.registerTheme(customTheme, baseTheme) method instead. + */ + export function registerTheme(customTheme: Object, baseTheme: string): void; + /** + * Applies a predefined or registered custom palette to all visualization widgets at once. + * @deprecated Use the DevExpress.viz.currentPalette(paletteName) method instead. + */ + export function currentPalette(paletteName: string): void; + /** + * Obtains the color sets of a predefined or registered palette. + * @deprecated Use the DevExpress.viz.getPalette(paletteName) method instead. + */ + export function getPalette(paletteName: string): Object; + /** + * Registers a new palette. + * @deprecated Use the DevExpress.viz.registerPalette(paletteName, palette) method instead. + */ + export function registerPalette(paletteName: string, palette: Object): void; export interface Border { /** Sets a border color for a selected series. */ color?: string; @@ -5270,7 +5329,7 @@ declare module DevExpress.viz.charts { position?: string; } export interface ChartTooltip extends BaseChartTooltip { - /** Specifies whether the tooltip must be located in the center of a bar or on its edge. Applies only to the Bar series. */ + /** Specifies whether the tooltip must be located in the center of a bar or on its edge. Applies to the Bar and Bubble series. */ location?: string; /** Specifies the kind of information to display in a tooltip. */ shared?: boolean; @@ -5860,6 +5919,8 @@ Indicates whether or not animation is enabled. }; /** Specifies a value indicating whether all bars in a series must have the same width, or may have different widths if any points in other series are missing. */ equalBarWidth?: any; + /** Sets the name of the palette to be used in the range selector's chart. Alternatively, an array of colors can be set as a custom palette to be used within this chart. */ + palette?: any; /** An object defining the chart’s series. */ series?: Array; /** Defines options for the series template. */ From 329f39b8da64bea4f7a7e5fa530220a8439e9853 Mon Sep 17 00:00:00 2001 From: Matt Gibbs Date: Wed, 19 Aug 2015 10:46:48 -0400 Subject: [PATCH 154/794] Correcting typings on Tour Buttons --- tether-shepherd/tether-shepherd.d.ts | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/tether-shepherd/tether-shepherd.d.ts b/tether-shepherd/tether-shepherd.d.ts index b632fb771..eeee87104 100644 --- a/tether-shepherd/tether-shepherd.d.ts +++ b/tether-shepherd/tether-shepherd.d.ts @@ -143,7 +143,7 @@ declare module TetherShepherd { title?: string; attachTo?: any; beforeShowPromise?: any; - classes?: any; + classes?: string; buttons?: IShepherdTourButton[]; advanceOn?: any; showCancelLink?: boolean; @@ -156,9 +156,13 @@ declare module TetherShepherd { interface IShepherdTourButton { text: string; - classes: string[]; - action?: any; - events?: any; + classes?: string; + action?: Function; + events?: IShepherdTourButtonEventHash; + } + + interface IShepherdTourButtonEventHash { + [Key: string]: Function; } interface IShepherdTourAttachProperties { From 0ac23ee1fb12c3c3d849deb8f1cd50353a5e9839 Mon Sep 17 00:00:00 2001 From: Matt Gibbs Date: Wed, 19 Aug 2015 11:22:40 -0400 Subject: [PATCH 155/794] Creating more robust test case. --- tether-shepherd/tether-shepherd-tests.ts | 46 ++++++++++++++++++++++-- 1 file changed, 44 insertions(+), 2 deletions(-) diff --git a/tether-shepherd/tether-shepherd-tests.ts b/tether-shepherd/tether-shepherd-tests.ts index 48bef675b..7325a8464 100644 --- a/tether-shepherd/tether-shepherd-tests.ts +++ b/tether-shepherd/tether-shepherd-tests.ts @@ -6,11 +6,53 @@ var tour = new Shepherd.Tour({ } }); -tour.addStep('test-step', { +var step1Options: TetherShepherd.IShepherdTourStepOptions = { text: 'This is a test step being added to the test tour', title: 'Test Step Title', attachTo: { element: '#button', on: 'right' + }, + buttons: [ + { + text: 'Continue', + action: tour.next + }, + { + text: 'Cancel', + action: tour.cancel + } + ] +}; + +tour.addStep('test-step', step1Options); + +var step2Options: TetherShepherd.IShepherdTourStepOptions = { + text: 'This is the next step being added to the test tour', + title: 'Test Step Title 2 - Electric Boogaloo', + attachTo: '#anotherButton right', + buttons: [ + { + text: 'Done', + action: tour.next, + events: { + 'mouseover': () => { + console.log('I did not feel like making a function body that pretended to do something else'); + } + } + } + ], + when: { + destroy: () => { + console.log('Destroyed the Step 2'); + } } -}); +}; + +tour.addStep('test-step-2', step2Options); + +var queriedStep = tour.getById('test-step-2'); + +queriedStep.destroy(); + +tour.start(); \ No newline at end of file From 132ed07af75076dfbc7643533e043d9a7eda652f Mon Sep 17 00:00:00 2001 From: Demian Gemperli Date: Wed, 19 Aug 2015 18:16:23 +0200 Subject: [PATCH 156/794] Fix cordova file transfer download --- cordova/cordova-tests.ts | 8 ++++++-- cordova/plugins/FileTransfer.d.ts | 8 ++++---- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/cordova/cordova-tests.ts b/cordova/cordova-tests.ts index d162b1ab6..491b49773 100644 --- a/cordova/cordova-tests.ts +++ b/cordova/cordova-tests.ts @@ -176,8 +176,12 @@ file.download('http://some.server.com/download.php', console.error('Failed with exception ' + err.exception); } }, - { headers: null }, - true); + true, + { + headers: { + "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA==" + } + }); file.upload('cdvfile://localhost/persistent/path/to/downloads/', 'http://some.server.com/download.php', diff --git a/cordova/plugins/FileTransfer.d.ts b/cordova/plugins/FileTransfer.d.ts index d0c023ae8..7cbde5322 100644 --- a/cordova/plugins/FileTransfer.d.ts +++ b/cordova/plugins/FileTransfer.d.ts @@ -53,8 +53,8 @@ interface FileTransfer { target: string, successCallback: (fileEntry: FileEntry) => void, errorCallback: (error: FileTransferError) => void, - options?: FileDownloadOptions, - trustAllHosts?: boolean): void; + trustAllHosts?: boolean, + options?: FileDownloadOptions): void; /** * Aborts an in-progress transfer. The onerror callback is passed a FileTransferError object * which has an error code of FileTransferError.ABORT_ERR. @@ -98,8 +98,8 @@ interface FileUploadOptions { /** Optional parameters for download method. */ interface FileDownloadOptions { - /** A map of header name/header values. Use an array to specify more than one value. */ - headers?: Object[]; + /** A map of header name/header values. */ + headers?: {}; } /** A FileTransferError object is passed to an error callback when an error occurs. */ From b316f99df4612d7f11b1fb8f4e3ab4024f8a604a Mon Sep 17 00:00:00 2001 From: Stepan Mikhaylyuk Date: Wed, 19 Aug 2015 19:42:30 +0300 Subject: [PATCH 157/794] updated to 1.0.5 version added jsdocs. es6 import added module lscache for es6 import --- lscache/lscache.d.ts | 41 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 38 insertions(+), 3 deletions(-) diff --git a/lscache/lscache.d.ts b/lscache/lscache.d.ts index 24c34bd8d..340d54b76 100644 --- a/lscache/lscache.d.ts +++ b/lscache/lscache.d.ts @@ -1,13 +1,48 @@ -// Type definitions for lscache v1.0.2 +// Type definitions for lscache v1.0.5 // Project: https://github.com/pamelafox/lscache // Definitions by: Chris Martinez // Definitions: https://github.com/borisyankov/DefinitelyTyped interface LSCache { + /** + * Stores the value in localStorage. Expires after specified number of minutes. + * @param {string} key + * @param {Object|string} value + * @param {number} time + */ set(key: string, value: any, time?: number): void; + /** + * Retrieves specified value from localStorage, if not expired. + * @param {string} key + * @return {string|Object} + */ get(key: string): any; + /** + * Removes a value from localStorage. + * Equivalent to 'delete' in memcache, but that's a keyword in JS. + * @param {string} key + */ remove(key: string): void; + /** + * Flushes all lscache items and expiry markers without affecting rest of localStorage + */ + flush(): void; + /** + * Flushes expired lscache items and expiry markers without affecting rest of localStorage + */ + flushExpired(): void; + /** + * Appends CACHE_PREFIX so lscache will partition data in to different buckets. + * @param {string} bucket + */ + setBucket(bucket: string); + /** + * Resets the string being appended to CACHE_PREFIX so lscache will use the default storage behavior. + */ + resetBucket(): void; +} +declare module 'lscache' { + var lscache: LSCache; + export = lscache; } - -declare var lscache: LSCache; \ No newline at end of file From 35afc7dc2c61c0ea91b07bf7859488b61d83714b Mon Sep 17 00:00:00 2001 From: Stepan Mikhaylyuk Date: Wed, 19 Aug 2015 19:46:47 +0300 Subject: [PATCH 158/794] minor fix --- lscache/lscache.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lscache/lscache.d.ts b/lscache/lscache.d.ts index 340d54b76..ed5d133a5 100644 --- a/lscache/lscache.d.ts +++ b/lscache/lscache.d.ts @@ -36,12 +36,13 @@ interface LSCache { * Appends CACHE_PREFIX so lscache will partition data in to different buckets. * @param {string} bucket */ - setBucket(bucket: string); + setBucket(bucket: string):void; /** * Resets the string being appended to CACHE_PREFIX so lscache will use the default storage behavior. */ resetBucket(): void; } +declare var lscache:LSCache; declare module 'lscache' { var lscache: LSCache; export = lscache; From cb2b22f81a17658943fbcb06f15c0bde4e60e79c Mon Sep 17 00:00:00 2001 From: Marcin Porebski Date: Wed, 19 Aug 2015 18:48:48 +0200 Subject: [PATCH 159/794] string score definitions --- string_score/string_score-tests.ts | 8 ++++++++ string_score/string_score.d.ts | 8 ++++++++ 2 files changed, 16 insertions(+) create mode 100644 string_score/string_score-tests.ts create mode 100644 string_score/string_score.d.ts diff --git a/string_score/string_score-tests.ts b/string_score/string_score-tests.ts new file mode 100644 index 000000000..8a7399603 --- /dev/null +++ b/string_score/string_score-tests.ts @@ -0,0 +1,8 @@ +/// + +import string_score = require('string_score'); + +var a = 'abc'; +var b = 'xyz'; + +console.log(a.score(b).toString()); diff --git a/string_score/string_score.d.ts b/string_score/string_score.d.ts new file mode 100644 index 000000000..2d901ba39 --- /dev/null +++ b/string_score/string_score.d.ts @@ -0,0 +1,8 @@ +// Type definitions for url-template 0.1.22 +// Project: https://github.com/joshaven/string_score +// Definitions by: Marcin Porębski +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface String { + score: (word: string, fuzzy?: number) => number; +} From cd2e71bb1f0459197e733be66fdeafaec600514d Mon Sep 17 00:00:00 2001 From: Igor Minar Date: Wed, 19 Aug 2015 09:48:00 -0700 Subject: [PATCH 160/794] Update angular2 definitions to 2.0.0-alpha.35 --- angular2/angular2-2.0.0-alpha.35.d.ts | 5775 +++++++++++++++++++++++++ angular2/angular2.d.ts | 2593 ++++------- angular2/router-2.0.0-alpha.35.d.ts | 689 +++ angular2/router.d.ts | 282 +- 4 files changed, 7617 insertions(+), 1722 deletions(-) create mode 100644 angular2/angular2-2.0.0-alpha.35.d.ts create mode 100644 angular2/router-2.0.0-alpha.35.d.ts diff --git a/angular2/angular2-2.0.0-alpha.35.d.ts b/angular2/angular2-2.0.0-alpha.35.d.ts new file mode 100644 index 000000000..4c9c2aea2 --- /dev/null +++ b/angular2/angular2-2.0.0-alpha.35.d.ts @@ -0,0 +1,5775 @@ +// Type definitions for Angular v2.0.0-alpha.35 +// Project: http://angular.io/ +// Definitions by: angular team +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// *********************************************************** +// This file is generated by the Angular build process. +// Please do not create manual edits or send pull requests +// modifying this file. +// *********************************************************** + +// angular2/angular2 depends transitively on these libraries. +// If you don't have them installed you can install them using TSD +// https://github.com/DefinitelyTyped/tsd + +/// +/// + + +interface List extends Array {} +interface Map {} +interface StringMap extends Map {} + +declare module ng { + // See https://github.com/Microsoft/TypeScript/issues/1168 + class BaseException /* extends Error */ { + message: string; + stack: string; + toString(): string; + } + interface InjectableReference {} +} + + + + +/** + * The `angular2` is the single place to import all of the individual types. + */ +declare module ng { + + /** + * Declare reusable UI building blocks for an application. + * + * Each Angular component requires a single `@Component` and at least one `@View` annotation. The + * `@Component` + * annotation specifies when a component is instantiated, and which properties and hostListeners it + * binds to. + * + * When a component is instantiated, Angular + * - creates a shadow DOM for the component. + * - loads the selected template into the shadow DOM. + * - creates all the injectable objects configured with `bindings` and `viewBindings`. + * + * All template expressions and statements are then evaluated against the component instance. + * + * For details on the `@View` annotation, see {@link ViewMetadata}. + * + * ## Example + * + * ``` + * @Component({ + * selector: 'greet' + * }) + * @View({ + * template: 'Hello {{name}}!' + * }) + * class Greet { + * name: string; + * + * constructor() { + * this.name = 'World'; + * } + * } + * ``` + */ + class ComponentMetadata extends DirectiveMetadata { + + + /** + * Defines the used change detection strategy. + * + * When a component is instantiated, Angular creates a change detector, which is responsible for + * propagating + * the component's bindings. + * + * The `changeDetection` property defines, whether the change detection will be checked every time + * or only when the component + * tells it to do so. + */ + changeDetection: string; + + + /** + * Defines the set of injectable objects that are visible to its view dom children. + * + * ## Simple Example + * + * Here is an example of a class that can be injected: + * + * ``` + * class Greeter { + * greet(name:string) { + * return 'Hello ' + name + '!'; + * } + * } + * + * @Directive({ + * selector: 'needs-greeter' + * }) + * class NeedsGreeter { + * greeter:Greeter; + * + * constructor(greeter:Greeter) { + * this.greeter = greeter; + * } + * } + * + * @Component({ + * selector: 'greet', + * viewBindings: [ + * Greeter + * ] + * }) + * @View({ + * template: ``, + * directives: [NeedsGreeter] + * }) + * class HelloWorld { + * } + * + * ``` + */ + viewBindings: List; + } + + + /** + * Directives allow you to attach behavior to elements in the DOM. + * + * {@link DirectiveMetadata}s with an embedded view are called {@link ComponentMetadata}s. + * + * A directive consists of a single directive annotation and a controller class. When the + * directive's `selector` matches + * elements in the DOM, the following steps occur: + * + * 1. For each directive, the `ElementInjector` attempts to resolve the directive's constructor + * arguments. + * 2. Angular instantiates directives for each matched element using `ElementInjector` in a + * depth-first order, + * as declared in the HTML. + * + * ## Understanding How Injection Works + * + * There are three stages of injection resolution. + * - *Pre-existing Injectors*: + * - The terminal {@link Injector} cannot resolve dependencies. It either throws an error or, if + * the dependency was + * specified as `@Optional`, returns `null`. + * - The platform injector resolves browser singleton resources, such as: cookies, title, + * location, and others. + * - *Component Injectors*: Each component instance has its own {@link Injector}, and they follow + * the same parent-child hierarchy + * as the component instances in the DOM. + * - *Element Injectors*: Each component instance has a Shadow DOM. Within the Shadow DOM each + * element has an `ElementInjector` + * which follow the same parent-child hierarchy as the DOM elements themselves. + * + * When a template is instantiated, it also must instantiate the corresponding directives in a + * depth-first order. The + * current `ElementInjector` resolves the constructor dependencies for each directive. + * + * Angular then resolves dependencies as follows, according to the order in which they appear in the + * {@link ViewMetadata}: + * + * 1. Dependencies on the current element + * 2. Dependencies on element injectors and their parents until it encounters a Shadow DOM boundary + * 3. Dependencies on component injectors and their parents until it encounters the root component + * 4. Dependencies on pre-existing injectors + * + * + * The `ElementInjector` can inject other directives, element-specific special objects, or it can + * delegate to the parent + * injector. + * + * To inject other directives, declare the constructor parameter as: + * - `directive:DirectiveType`: a directive on the current element only + * - `@Host() directive:DirectiveType`: any directive that matches the type between the current + * element and the + * Shadow DOM root. + * - `@Query(DirectiveType) query:QueryList`: A live collection of direct child + * directives. + * - `@QueryDescendants(DirectiveType) query:QueryList`: A live collection of any + * child directives. + * + * To inject element-specific special objects, declare the constructor parameter as: + * - `element: ElementRef` to obtain a reference to logical element in the view. + * - `viewContainer: ViewContainerRef` to control child template instantiation, for + * {@link DirectiveMetadata} directives only + * - `bindingPropagation: BindingPropagation` to control change detection in a more granular way. + * + * ## Example + * + * The following example demonstrates how dependency injection resolves constructor arguments in + * practice. + * + * + * Assume this HTML template: + * + * ``` + *
      + *
      + *
      + *
      + *
      + *
      + *
      + *
      + *
      + *
      + * ``` + * + * With the following `dependency` decorator and `SomeService` injectable class. + * + * ``` + * @Injectable() + * class SomeService { + * } + * + * @Directive({ + * selector: '[dependency]', + * properties: [ + * 'id: dependency' + * ] + * }) + * class Dependency { + * id:string; + * } + * ``` + * + * Let's step through the different ways in which `MyDirective` could be declared... + * + * + * ### No injection + * + * Here the constructor is declared with no arguments, therefore nothing is injected into + * `MyDirective`. + * + * ``` + * @Directive({ selector: '[my-directive]' }) + * class MyDirective { + * constructor() { + * } + * } + * ``` + * + * This directive would be instantiated with no dependencies. + * + * + * ### Component-level injection + * + * Directives can inject any injectable instance from the closest component injector or any of its + * parents. + * + * Here, the constructor declares a parameter, `someService`, and injects the `SomeService` type + * from the parent + * component's injector. + * ``` + * @Directive({ selector: '[my-directive]' }) + * class MyDirective { + * constructor(someService: SomeService) { + * } + * } + * ``` + * + * This directive would be instantiated with a dependency on `SomeService`. + * + * + * ### Injecting a directive from the current element + * + * Directives can inject other directives declared on the current element. + * + * ``` + * @Directive({ selector: '[my-directive]' }) + * class MyDirective { + * constructor(dependency: Dependency) { + * expect(dependency.id).toEqual(3); + * } + * } + * ``` + * This directive would be instantiated with `Dependency` declared at the same element, in this case + * `dependency="3"`. + * + * ### Injecting a directive from any ancestor elements + * + * Directives can inject other directives declared on any ancestor element (in the current Shadow + * DOM), i.e. on the current element, the + * parent element, or its parents. + * ``` + * @Directive({ selector: '[my-directive]' }) + * class MyDirective { + * constructor(@Host() dependency: Dependency) { + * expect(dependency.id).toEqual(2); + * } + * } + * ``` + * + * `@Host` checks the current element, the parent, as well as its parents recursively. If + * `dependency="2"` didn't + * exist on the direct parent, this injection would + * have returned + * `dependency="1"`. + * + * + * ### Injecting a live collection of direct child directives + * + * + * A directive can also query for other child directives. Since parent directives are instantiated + * before child directives, a directive can't simply inject the list of child directives. Instead, + * the directive injects a {@link QueryList}, which updates its contents as children are added, + * removed, or moved by a directive that uses a {@link ViewContainerRef} such as a `ng-for`, an + * `ng-if`, or an `ng-switch`. + * + * ``` + * @Directive({ selector: '[my-directive]' }) + * class MyDirective { + * constructor(@Query(Dependency) dependencies:QueryList) { + * } + * } + * ``` + * + * This directive would be instantiated with a {@link QueryList} which contains `Dependency` 4 and + * 6. Here, `Dependency` 5 would not be included, because it is not a direct child. + * + * ### Injecting a live collection of descendant directives + * + * By passing the descendant flag to `@Query` above, we can include the children of the child + * elements. + * + * ``` + * @Directive({ selector: '[my-directive]' }) + * class MyDirective { + * constructor(@Query(Dependency, {descendants: true}) dependencies:QueryList) { + * } + * } + * ``` + * + * This directive would be instantiated with a Query which would contain `Dependency` 4, 5 and 6. + * + * ### Optional injection + * + * The normal behavior of directives is to return an error when a specified dependency cannot be + * resolved. If you + * would like to inject `null` on unresolved dependency instead, you can annotate that dependency + * with `@Optional()`. + * This explicitly permits the author of a template to treat some of the surrounding directives as + * optional. + * + * ``` + * @Directive({ selector: '[my-directive]' }) + * class MyDirective { + * constructor(@Optional() dependency:Dependency) { + * } + * } + * ``` + * + * This directive would be instantiated with a `Dependency` directive found on the current element. + * If none can be + * found, the injector supplies `null` instead of throwing an error. + * + * ## Example + * + * Here we use a decorator directive to simply define basic tool-tip behavior. + * + * ``` + * @Directive({ + * selector: '[tooltip]', + * properties: [ + * 'text: tooltip' + * ], + * host: { + * '(mouseenter)': 'onMouseEnter()', + * '(mouseleave)': 'onMouseLeave()' + * } + * }) + * class Tooltip{ + * text:string; + * overlay:Overlay; // NOT YET IMPLEMENTED + * overlayManager:OverlayManager; // NOT YET IMPLEMENTED + * + * constructor(overlayManager:OverlayManager) { + * this.overlay = overlay; + * } + * + * onMouseEnter() { + * // exact signature to be determined + * this.overlay = this.overlayManager.open(text, ...); + * } + * + * onMouseLeave() { + * this.overlay.close(); + * this.overlay = null; + * } + * } + * ``` + * In our HTML template, we can then add this behavior to a `
      ` or any other element with the + * `tooltip` selector, + * like so: + * + * ``` + *
      + * ``` + * + * Directives can also control the instantiation, destruction, and positioning of inline template + * elements: + * + * A directive uses a {@link ViewContainerRef} to instantiate, insert, move, and destroy views at + * runtime. + * The {@link ViewContainerRef} is created as a result of `