From 3ea7cf7889743b5633df96508fa38189361b466c Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Wed, 8 Jul 2015 19:22:36 +0900 Subject: [PATCH 001/173] 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 002/173] 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 003/173] 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 004/173] 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 005/173] 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 006/173] 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 007/173] 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 008/173] 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 009/173] 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 010/173] 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 011/173] 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 012/173] 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 013/173] 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 014/173] 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 015/173] 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 016/173] 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 017/173] 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 018/173] 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 019/173] 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 020/173] 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 021/173] 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 022/173] 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 023/173] 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 1a46ba29e13e1ac1a872ebdae4f3f4b4fc279a0e Mon Sep 17 00:00:00 2001 From: Sascha Thiel Date: Mon, 13 Jul 2015 10:11:18 +0200 Subject: [PATCH 024/173] 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 025/173] 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 026/173] 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 15520b4269d3b372947c0b0eaa6564cd118b96ed Mon Sep 17 00:00:00 2001 From: Sascha Thiel Date: Tue, 21 Jul 2015 13:52:47 +0200 Subject: [PATCH 027/173] added LayoutViewOption because the Layout can have regions in it. --- marionette/marionette.d.ts | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/marionette/marionette.d.ts b/marionette/marionette.d.ts index be684d9a8..c60965c98 100644 --- a/marionette/marionette.d.ts +++ b/marionette/marionette.d.ts @@ -1097,6 +1097,13 @@ declare module Marionette { onRenderCollection(): void; } + interface LayoutViewOptions extends Backbone.ViewOptions { + /** + * The LayoutView takes an additional parameter where you can pass the regions as option on creation. + */ + regions?:any; + } + /** * A LayoutView is a hybrid of an ItemView and a collection of Region objects. * They are ideal for rendering application layouts with multiple sub-regions @@ -1119,7 +1126,12 @@ declare module Marionette { * A hash that can contain a regions hash that allows you to specify regions per * LayoutView instance. */ - constructor(options?: any); + constructor(options?: LayoutViewOptions); + + /** + * Regions hash or a method returning the regions hash that maps regions/selectors to methods on your View. + **/ + regions():any; /** Adds a region to the layout view. */ addRegion(name: string, definition: any): Region; @@ -1129,7 +1141,7 @@ declare module Marionette { */ addRegions(regions: any): any; - /** Returns a region from the layout view */ + /** Returns a region from the layout view */ getRegion(name: string): Region; /** @@ -1147,7 +1159,7 @@ declare module Marionette { * for customized region interactions and business specific * view logic for better control over single regions. */ - getRegionManager(): any; + getRegionManager(): RegionManager; } interface AppRouterOptions extends Backbone.RouterOptions { From c1b2c0c40d6d0ee60677425996e758fb1274c468 Mon Sep 17 00:00:00 2001 From: Dan Lewi Harkestad Date: Tue, 4 Aug 2015 14:04:32 +0200 Subject: [PATCH 028/173] 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 029/173] 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 030/173] 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 031/173] 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 032/173] 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 033/173] Problem with JsonResponseData interface, removed it. --- angularjs/angular-mocks-tests.ts | 2 ++ angularjs/angular-mocks.d.ts | 27 +++++++++------------------ 2 files changed, 11 insertions(+), 18 deletions(-) diff --git a/angularjs/angular-mocks-tests.ts b/angularjs/angular-mocks-tests.ts index 57820af08..63ea220f6 100644 --- a/angularjs/angular-mocks-tests.ts +++ b/angularjs/angular-mocks-tests.ts @@ -384,6 +384,7 @@ requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, { /////////////////////////////////////// // IRequestHandler /////////////////////////////////////// +var expectedData = { key: 'value'}; requestHandler.passThrough(); requestHandler.passThrough().passThrough(); requestHandler.respond((method, url, data, headers) => [404, 'data', { header: 'value' }, 'responseText']); @@ -391,6 +392,7 @@ requestHandler.respond((method, url, data, headers) => [404, 'data', { header: ' requestHandler.respond((method, url, data, headers) => { return [404, { key: 'value' }, { header: 'value' }, 'responseText']; }); requestHandler.respond('data'); requestHandler.respond('data').respond({}); +requestHandler.respond(expectedData); requestHandler.respond({ key: 'value' }); requestHandler.respond({ key: 'value' }, { header: 'value' }); requestHandler.respond({ key: 'value' }, { header: 'value' }, 'responseText'); diff --git a/angularjs/angular-mocks.d.ts b/angularjs/angular-mocks.d.ts index 20aa85f72..7e3806353 100644 --- a/angularjs/angular-mocks.d.ts +++ b/angularjs/angular-mocks.d.ts @@ -265,15 +265,6 @@ declare module angular { } export module mock { - // this interface makes it possible to diferentiate between a function parameter (in the first overload for IRequestHandler) - // and the data: string | Object parameter in the second overload. Since a function is an object, and the first overload - // takes one function param and the second overload takes a data string or Object with the other two parameters being optional, - // there was no type difference between respond((a,b,c,d) => {}) and respond({}). Using the JsonResponseData interface - // as a type creates a difference in the signatures changing data: string | Object to data: string | JsonResponseData - interface JsonResponseData extends Object { - [key: string] : any; - } - // returned interface by the the mocked HttpBackendService expect/when methods interface IRequestHandler { @@ -284,15 +275,6 @@ declare module angular { */ respond(func: ((method: string, url: string, data: string | Object, headers: Object) => [number, string | Object, Object, string])): IRequestHandler; - /** - * Controls the response for a matched request using the HTTP status code 200 and supplied static data to construct the response. - * Returns the RequestHandler object for possible overrides. - * @param data Data to add to the response. - * @param headers Headers object to add to the response. - * @param responseText Response text to add to the response. - */ - respond(data: string | JsonResponseData, headers?: Object, responseText?: string): IRequestHandler; - /** * Controls the response for a matched request using supplied static data to construct the response. * Returns the RequestHandler object for possible overrides. @@ -303,6 +285,15 @@ declare module angular { */ respond(status: number, data: string | Object, headers?: Object, responseText?: string): IRequestHandler; + /** + * Controls the response for a matched request using the HTTP status code 200 and supplied static data to construct the response. + * Returns the RequestHandler object for possible overrides. + * @param data Data to add to the response. + * @param headers Headers object to add to the response. + * @param responseText Response text to add to the response. + */ + respond(data: string | Object, headers?: Object, responseText?: string): IRequestHandler; + // Available when ngMockE2E is loaded /** * Any request matching a backend definition or expectation with passThrough handler will be passed through to the real backend (an XHR request will be made to the server.) From da093877f475389bf0e4b62d29afbf17fbd597a4 Mon Sep 17 00:00:00 2001 From: Ivan Drinchev Date: Thu, 6 Aug 2015 20:06:25 +0200 Subject: [PATCH 034/173] 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 035/173] Fixed tests for sequelize --- sequelize/sequelize-test.ts | 32 ++++++++++++++++---------------- sequelize/sequelize.d.ts | 6 +++--- 2 files changed, 19 insertions(+), 19 deletions(-) diff --git a/sequelize/sequelize-test.ts b/sequelize/sequelize-test.ts index ebc8cc0ce..e5656c76e 100644 --- a/sequelize/sequelize-test.ts +++ b/sequelize/sequelize-test.ts @@ -19,7 +19,7 @@ var Task = s.define( 'task', {} ); var Group = s.define( 'group', {} ); var Comment = s.define( 'comment', {} ); var Post = s.define( 'post', {} ); -var t = null; +var t : Sequelize.Transaction = null; s.transaction().then( ( a ) => t = a ); // @@ -319,11 +319,11 @@ new s.ConnectionTimedOutError( new Error( 'original connection error message' ) // https://github.com/sequelize/sequelize/blob/v3.4.1/test/integration/hooks.test.js // -User.addHook( 'afterCreate', function( instance, options, next ) { next(); } ); -User.addHook( 'afterCreate', 'myHook', function( instance, options, next ) { next(); } ); -s.addHook( 'beforeInit', function( config, options ) { } ); -User.hook( 'afterCreate', 'myHook', function( instance, options, next ) { next(); } ); -User.hook( 'afterCreate', 'myHook', function( instance, options, next ) { next(); } ); +User.addHook( 'afterCreate', function( instance : Sequelize.Instance, options : Object, next : Function ) { next(); } ); +User.addHook( 'afterCreate', 'myHook', function( instance : Sequelize.Instance, options : Object, next : Function) { next(); } ); +s.addHook( 'beforeInit', function( config : Object, options : Object ) { } ); +User.hook( 'afterCreate', 'myHook', function( instance : Sequelize.Instance, options : Object, next : Function) { next(); } ); +User.hook( 'afterCreate', 'myHook', function( instance : Sequelize.Instance, options : Object, next : Function ) { next(); } ); User.removeHook( 'afterCreate', 'myHook' ); @@ -477,10 +477,10 @@ user.update( { username : 'userman' }, { silent : true } ); user.update( { username : 'yolo' }, { logging : function() { } } ); user.update( { username : 'bar' }, { where : { username : 'foo' }, transaction : t } ).then( ( p ) => p ); user.updateAttributes( { a : 3 } ).then( ( p ) => p ); -user.updateAttributes( { a : 3 }, { fields : ['secretValue'], logging : function( sql ) {} } ); +user.updateAttributes( { a : 3 }, { fields : ['secretValue'], logging : function( ) {} } ); user.destroy().then( ( p ) => p ); -user.destroy( { logging : function( sql ) {} } ); +user.destroy( { logging : function( ) {} } ); user.destroy( { transaction : t } ).then( ( p ) => p ); user.restore(); @@ -519,7 +519,7 @@ User.sync( { force : true, logging : function() { } } ); User.drop(); User.schema( 'special' ); -User.schema( 'special' ).create( { age : 3 }, { logging : function( UserSpecial ) {} } ); +User.schema( 'special' ).create( { age : 3 }, { logging : function( ) {} } ); User.getTableName(); @@ -570,7 +570,7 @@ User.findById( 'a string' ); User.findOne( { where : { username : 'foo' } } ); User.findOne( { where : { id : 1 }, attributes : ['id', ['username', 'name']] } ); User.findOne( { where : { id : 1 }, attributes : ['id'] } ); -User.findOne( { where : { username : 'foo' }, logging : function( sql ) { } } ); +User.findOne( { where : { username : 'foo' }, logging : function( ) { } } ); User.findOne( { limit : 10 } ); User.findOne( { include : [1] } ); User.findOne( { where : { title : 'homework' }, include : [User] } ); @@ -601,15 +601,15 @@ User.findAndCountAll( { offset : 5, limit : 1, include : [User, { model : User, User.max( 'age', { transaction : t } ); User.max( 'age' ); -User.max( 'age', { logging : function( sql ) { } } ); +User.max( 'age', { logging : function( ) { } } ); User.min( 'age', { transaction : t } ); User.min( 'age' ); -User.min( 'age', { logging : function( sql ) { } } ); +User.min( 'age', { logging : function( ) { } } ); User.sum( 'order' ); User.sum( 'age', { where : { 'gender' : 'male' } } ); -User.sum( 'age', { logging : function( sql ) { } } ); +User.sum( 'age', { logging : function( ) { } } ); User.build( { username : 'John Wayne' } ).save(); User.build(); @@ -622,7 +622,7 @@ User.create( {}, { returning : true } ); User.create( { intVal : s.literal( 'CAST(1-2 AS' ) } ); User.create( { secretValue : s.fn( 'upper', 'sequelize' ) } ); User.create( { myvals : [1, 2, 3, 4], mystr : ['One', 'Two', 'Three', 'Four'] } ); -User.create( { name : 'Fluffy Bunny', smth : 'else' }, { logging : function( sql ) {} } ); +User.create( { name : 'Fluffy Bunny', smth : 'else' }, { logging : function( ) {} } ); User.create( {}, { fields : [] } ); User.create( { name : 'Yolo Bear', email : 'yolo@bear.com' }, { fields : ['name'] } ); User.create( { title : 'Chair', User : { first_name : 'Mick', last_name : 'Broadstone' } }, { include : [User] } ); @@ -637,7 +637,7 @@ User.findOrInitialize( { where : { username : 'foo' }, defaults : { foo : 'asd' User.findOrCreate( { where : { a : 'b' }, defaults : { json : { a : { b : 'c' }, d : [1, 2, 3] } } } ); User.findOrCreate( { where : { a : 'b' }, defaults : { json : 'a', data : 'b' } } ); User.findOrCreate( { where : { a : 'b' }, transaction : t, lock : t.LOCK.UPDATE } ); -User.findOrCreate( { where : { a : 'b' }, logging : function( sql ) { } } ); +User.findOrCreate( { where : { a : 'b' }, logging : function( ) { } } ); User.findOrCreate( { where : { username : 'Username' }, defaults : { data : 'some data' }, transaction : t } ); User.findOrCreate( { where : { objectId : 'asdasdasd' }, defaults : { username : 'gottlieb' } } ); User.findOrCreate( { where : { id : undefined }, defaults : { name : Math.random().toString() } } ); @@ -790,7 +790,7 @@ s.model( 'pp' ); s.query( '', { raw : true } ); s.query( '' ); s.query( '' ).then( function( res ) {} ); -s.query( '' ).spread( function( a ) {}, function( b ) {} ); +s.query( '' ).spread( function( ) {}, function( b ) {} ); s.query( { query : 'select ? as foo, ? as bar', values : [1, 2] }, { raw : true, replacements : [1, 2] } ); s.query( '', { raw : true, nest : false } ); s.query( 'select ? as foo, ? as bar', { type : this.sequelize.QueryTypes.SELECT, replacements : [1, 2] } ); diff --git a/sequelize/sequelize.d.ts b/sequelize/sequelize.d.ts index a97479d2b..4c2294e6f 100644 --- a/sequelize/sequelize.d.ts +++ b/sequelize/sequelize.d.ts @@ -5,9 +5,9 @@ // Based on original work by: samuelneff -/// -/// -/// +/// +/// +/// declare module "sequelize" { From 52854d5f1c46796481428d3ab7be722b6c47c869 Mon Sep 17 00:00:00 2001 From: Greg Smith Date: Mon, 10 Aug 2015 13:17:20 -0500 Subject: [PATCH 036/173] Update velocity-animate.d.ts for latest Velocity --- velocity-animate/velocity-animate-tests.ts | 59 +++++++++++ velocity-animate/velocity-animate.d.ts | 116 ++++++++++++++------- 2 files changed, 136 insertions(+), 39 deletions(-) diff --git a/velocity-animate/velocity-animate-tests.ts b/velocity-animate/velocity-animate-tests.ts index 96400d365..afcd8b563 100644 --- a/velocity-animate/velocity-animate-tests.ts +++ b/velocity-animate/velocity-animate-tests.ts @@ -293,3 +293,62 @@ function advanced_utility_function () { options: { duration: 1500 } }); } + +function ui_pack_sequence_running() { + var $element1: JQuery; + var $element2: JQuery; + var $element3: JQuery; + + $element1.velocity({ translateX: 100 }, 1000, function() { + $element2.velocity({ translateX: 200 }, 1000, function() { + $element3.velocity({ translateX: 300 }, 1000); + }); + }); + + var mySequence = [ + { e: $element1, p: { translateX: 100 }, o: { duration: 1000 } }, + { e: $element2, p: { translateX: 200 }, o: { duration: 1000 } }, + { e: $element3, p: { translateX: 300 }, o: { duration: 1000 } } + ]; + $.Velocity.RunSequence(mySequence); + + var mySequence2 = [ + { e: $element1, p: { translateX: 100 }, o: { duration: 1000 } }, + /* The call below will run at the same time as the first call. */ + { e: $element2, p: { translateX: 200 }, o: { duration: 1000, sequenceQueue: false } }, + /* As normal, the call below will run once the second call is complete. */ + { e: $element3, p: { translateX: 300 }, o: { duration: 1000 } } + ]; + $.Velocity.RunSequence(mySequence2); +} + +function ui_pack_registration() { + var $element: JQuery; + + $.Velocity.RegisterEffect("callout.pulse", { + defaultDuration: 900, + calls: [ + [ { scaleX: 1.1 }, 0.50 ], + [ { scaleX: 1 }, 0.50 ] + ] + }); + $element.velocity("callout.pulse"); + + $.Velocity + .RegisterEffect("transition.flipXIn", { + defaultDuration: 700, + calls: [ + [ { opacity: 1, rotateY: [ 0, -55 ] } ] + ] + }) + .RegisterEffect("transition.flipXOut", { + defaultDuration: 700, + calls: [ + [ { opacity: 0, rotateY: 55 } ] + ], + reset: { rotateY: 0 } + }); + $element + .velocity("transition.flipXIn") + .velocity("transition.flipXOut", { delay: 1000 }); +} diff --git a/velocity-animate/velocity-animate.d.ts b/velocity-animate/velocity-animate.d.ts index 6946da972..9a1f58aa0 100644 --- a/velocity-animate/velocity-animate.d.ts +++ b/velocity-animate/velocity-animate.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Velocity 0.0.22 +// Type definitions for Velocity 1.2.2 // Project: http://velocityjs.org/ // Definitions by: Greg Smith // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -6,14 +6,13 @@ /// interface JQuery { - velocity(options: {properties: Object; options: jquery.velocity.VelocityOptions}): JQuery; - velocity(properties: Object, options: jquery.velocity.VelocityOptions): JQuery; - velocity(properties: Object, duration?: number, easing?: string, complete?: jquery.velocity.ElementCallback): JQuery; - velocity(properties: Object, duration?: number, easing?: number[], complete?: jquery.velocity.ElementCallback): JQuery; - velocity(properties: Object, duration?: number, complete?: jquery.velocity.ElementCallback): JQuery; - velocity(properties: Object, easing?: string, complete?: jquery.velocity.ElementCallback): JQuery; - velocity(properties: Object, easing?: number[], complete?: jquery.velocity.ElementCallback): JQuery; - velocity(properties: Object, complete?: jquery.velocity.ElementCallback): JQuery; + velocity(name: string, options: jquery.velocity.RegisteredEffectOptions): JQuery; + velocity(options: {properties: jquery.velocity.Properties; options: jquery.velocity.Options}): JQuery; + velocity(properties: jquery.velocity.Properties, options: jquery.velocity.Options): JQuery; + velocity(properties: jquery.velocity.Properties, duration: number, easing: jquery.velocity.Easing, complete?: jquery.velocity.ElementCallback): JQuery; + velocity(properties: jquery.velocity.Properties, duration: number, complete?: jquery.velocity.ElementCallback): JQuery; + velocity(properties: jquery.velocity.Properties, easing: jquery.velocity.Easing, complete?: jquery.velocity.ElementCallback): JQuery; + velocity(properties: jquery.velocity.Properties, complete?: jquery.velocity.ElementCallback): JQuery; } interface JQueryStatic { @@ -21,42 +20,81 @@ interface JQueryStatic { } declare module jquery.velocity { - interface ElementCallback { - (elements: NodeListOf): void; + type Properties = Object; + type Easing = string|number[]; + type ElementCallback = (elements: NodeListOf) => void; + type ProgressCallback = (elements: NodeListOf, percentComplete: number, timeRemaining: number, timeStart: number) => void; + type EffectCall = + [Properties] | + [Properties, number] | + [Properties, EffectCallOptions] | + [Properties, number, EffectCallOptions]; + + interface EffectCallOptions { + delay?: any; + easing?: any; } - interface ProgressCallback { - (elements: NodeListOf, percentComplete: number, timeRemaining: number, timeStart: number): void; + interface Options { + queue?: string|boolean; + duration?: string|number; + easing?: Easing; + begin?: ElementCallback; + complete?: ElementCallback; + progress?: ProgressCallback; + display?: string|boolean; + loop?: number|boolean; + delay?: number|boolean; + mobileHA?: boolean; + _cacheValues?: boolean; + } + + interface RegisterEffectOptions { + defaultDuration?: number; + calls: EffectCall[]; + reset?: Object; + } + + interface RegisteredEffectOptions { + duration?: string|number; + begin?: ElementCallback; + complete?: ElementCallback; + display?: string; + delay?: number; + mobileHA?: boolean; + _cacheValues?: boolean; + stagger?: number; + drag?: boolean; + backwards?: boolean; + } + + interface SequenceCall { + e: HTMLElement|JQuery; + p: Properties; + o: SequenceOptions; + } + + interface SequenceOptions extends Options { + sequenceQueue?: boolean; } interface VelocityStatic { Sequences: any; - animate(options: {elements: NodeListOf; properties: Object; options: VelocityOptions}): void; - animate(elements: NodeListOf, properties: Object, options: VelocityOptions): void; - animate(element: HTMLElement, properties: Object, options: VelocityOptions): void; - /** - * Get a hook value. Hooks are the subvalues of multi-value CSS properties. - * It features the same API as $.css(). - */ - hook(element: HTMLElement|JQuery, cssKey: string): string; - /** - * Set a hook value. Hooks are the subvalues of multi-value CSS properties. - * It features the same API as $.css(). - */ - hook(element: HTMLElement|JQuery, cssKey: string, cssValue: string): void; - } + animate(options: {elements: NodeListOf; properties: Properties; options: Options}): any; + animate(elements: HTMLElement|NodeListOf, properties: Properties, options: Options): any; + RegisterEffect(name: string, options: RegisterEffectOptions): VelocityStatic; + RunSequence(sequence: SequenceCall[]): VelocityStatic; - interface VelocityOptions { - queue?: any; - duration?: any; - easing?: any; - begin?: ElementCallback; - complete?: ElementCallback; - progress?: ProgressCallback; - display?: any; - loop?: any; - delay?: any; - mobileHA?: boolean; - _cacheValues?: boolean; + /** + * Get a hook value. Hooks are the subvalues of multi-value CSS properties. + * It features the same API as $.css(). + */ + hook(element: HTMLElement|JQuery, cssKey: string): string; + + /** + * Set a hook value. Hooks are the subvalues of multi-value CSS properties. + * It features the same API as $.css(). + */ + hook(element: HTMLElement|JQuery, cssKey: string, cssValue: string): void; } } From d874adfcb6391e3345cf2f30088a43138a2aee05 Mon Sep 17 00:00:00 2001 From: almstrand Date: Wed, 12 Aug 2015 17:20:07 -0700 Subject: [PATCH 037/173] 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 d34aa2d731960f59d8fc6ebfd88679582369c2d7 Mon Sep 17 00:00:00 2001 From: rhysd Date: Mon, 17 Aug 2015 16:49:39 +0900 Subject: [PATCH 038/173] 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 039/173] 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 040/173] 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 041/173] 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 042/173] 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 043/173] 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 044/173] 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 045/173] lodash: fix pull, remove, fill, pluck --- lodash/lodash-tests.ts | 1 + lodash/lodash.d.ts | 62 +++++++++++++++++++++--------------------- 2 files changed, 32 insertions(+), 31 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 2cbec6853..34080d18d 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -639,6 +639,7 @@ result = _(stoogesAgesDict).sum('age'); result = _.pluck(stoogesAges, 'name'); result = _(stoogesAges).pluck('name').value(); +result = _.pluck(stoogesAges, ['name']); // _.partition result = _.partition('abcd', (n) => n < 'c'); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index c088f5459..97c02f4b4 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -1092,16 +1092,16 @@ declare module _ { * @param values The values to remove. * @return array. **/ - pull( - array: Array, - ...values: any[]): any[]; + pull( + array: Array, + ...values: T[]): T[]; /** * @see _.pull **/ - pull( - array: List, - ...values: any[]): any[]; + pull( + array: List, + ...values: T[]): T[]; } interface LoDashStatic { @@ -1141,50 +1141,50 @@ declare module _ { * @param thisArg The this binding of callback. * @return A new array of removed elements. **/ - remove( - array: Array, - callback?: ListIterator, - thisArg?: any): any[]; + remove( + array: Array, + callback?: ListIterator, + thisArg?: any): T[]; /** * @see _.remove **/ - remove( - array: List, - callback?: ListIterator, - thisArg?: any): any[]; + remove( + array: List, + callback?: ListIterator, + thisArg?: any): T[]; /** * @see _.remove * @param pluckValue _.pluck style callback **/ - remove( - array: Array, - pluckValue?: string): any[]; + remove( + array: Array, + pluckValue?: string): T[]; /** * @see _.remove * @param pluckValue _.pluck style callback **/ - remove( - array: List, - pluckValue?: string): any[]; + remove( + array: List, + pluckValue?: string): T[]; /** * @see _.remove * @param whereValue _.where style callback **/ - remove( - array: Array, - wherealue?: Dictionary): any[]; + remove( + array: Array, + wherealue?: Dictionary): T[]; /** * @see _.remove * @param whereValue _.where style callback **/ - remove( - array: List, - wherealue?: Dictionary): any[]; + remove( + array: List, + wherealue?: Dictionary): T[]; /** * @see _.remove @@ -2494,7 +2494,7 @@ declare module _ { * @see _.fill */ fill( - value: any, + value: TResult, start?: number, end?: number): LoDashArrayWrapper; } @@ -2504,7 +2504,7 @@ declare module _ { * @see _.fill */ fill( - value: any, + value: TResult, start?: number, end?: number): LoDashObjectWrapper>; } @@ -4069,21 +4069,21 @@ declare module _ { **/ pluck( collection: Array, - property: string): any[]; + property: string|string[]): any[]; /** * @see _.pluck **/ pluck( collection: List, - property: string): any[]; + property: string|string[]): any[]; /** * @see _.pluck **/ pluck( collection: Dictionary, - property: string): any[]; + property: string|string[]): any[]; } interface LoDashArrayWrapper { From 4d0f988e3c906e7a66bbd79dc11443c533038cb5 Mon Sep 17 00:00:00 2001 From: Joe Skeen Date: Mon, 17 Aug 2015 13:27:17 -0600 Subject: [PATCH 046/173] 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 047/173] 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 048/173] add decls for mailparser --- mailparser/mailparser-tests.ts | 69 +++++++++++++++++++++++++++ mailparser/mailparser.d.ts | 86 ++++++++++++++++++++++++++++++++++ 2 files changed, 155 insertions(+) create mode 100644 mailparser/mailparser-tests.ts create mode 100644 mailparser/mailparser.d.ts diff --git a/mailparser/mailparser-tests.ts b/mailparser/mailparser-tests.ts new file mode 100644 index 000000000..51d562788 --- /dev/null +++ b/mailparser/mailparser-tests.ts @@ -0,0 +1,69 @@ +import mailparser_mod = require("mailparser"); +import MailParser = mailparser_mod.MailParser; +import ParsedMail = mailparser_mod.ParsedMail; + + + +var mailparser = new MailParser(); + + +mailparser.on("headers", function(headers){ + console.log(headers.received); +}); + +mailparser.on("end", function(mail){ + mail; // object structure for parsed e-mail +}); + + +// Decode a simple e-mail +// This example decodes an e-mail from a string + +var email = "From: 'Sender Name' \r\n"+ + "To: 'Receiver Name' \r\n"+ + "Subject: Hello world!\r\n"+ + "\r\n"+ + "How are you today?"; + // setup an event listener when the parsing finishes +mailparser.on("end", function(mail_object){ + console.log("From:", mail_object.from); //[{address:'sender@example.com',name:'Sender Name'}] + console.log("Subject:", mail_object.subject); // Hello world! + console.log("Text body:", mail_object.text); // How are you today? +}); + // send the email source to the parser +mailparser.write(email); +mailparser.end(); + + +// Pipe file to MailParser +// This example pipes a readableStream file to MailParser +mailparser = new MailParser(); +import fs = require("fs"); +mailparser.on("end", function(mail_object){ + console.log("Subject:", mail_object.subject); +}); + +fs.createReadStream("email.eml").pipe(mailparser); + + +// Attachments +mailparser.on("end", function(mail_object : ParsedMail){ + mail_object.attachments.forEach(function(attachment){ + console.log(attachment.fileName); + }); +}); + + +// Attachment streaming +var mp = new MailParser({ + streamAttachments: true +}) + +mp.on("attachment", function(attachment, mail){ + var output = fs.createWriteStream(attachment.generatedFileName); + attachment.stream.pipe(output); +}); + + + + diff --git a/mailparser/mailparser.d.ts b/mailparser/mailparser.d.ts new file mode 100644 index 000000000..9e67cc78a --- /dev/null +++ b/mailparser/mailparser.d.ts @@ -0,0 +1,86 @@ +// Type definitions for mailparser v0.5.2 +// Project: https://www.npmjs.com/package/mailparser +// Definitions by: Peter Snider +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +/// + + +declare module 'mailparser' { + import WritableStream = NodeJS.WritableStream; + import EventEmitter = NodeJS.EventEmitter; + + interface Options { + debug?: boolean; // if set to true print all incoming lines to console + streamAttachments?: boolean; // if set to true, stream attachments instead of including them + unescapeSMTP?: boolean; // if set to true replace double dots in the beginning of the file + defaultCharset?: string; // the default charset for text/plain and text/html content, if not set reverts to Latin-1 + showAttachmentLinks?: boolean; // if set to true, show inlined attachment links filename + } + + + interface EmailAddress { + address: string; + name: string; + } + + + interface Attachment { + contentType: string; + fileName: string; + contentDisposition: string; // e.g. 'attachment' + contentId: string; // e.g. '5.1321281380971@localhost' + transferEncoding: string; // e.g. 'base64' + length: number; // length of the attachment in bytes + generatedFileName: string; // e.g. 'image.png' + checksum: string; // the md5 hash of the file, e.g. 'e4cef4c6e26037bcf8166905207ea09b' + content: Buffer; // possibly a SlowBuffer + } + + // emitted with the 'end' event + interface ParsedMail { + headers: any; // unprocessed headers in the form of - {key: value} - if there were multiple fields with the same key then the value is an array + from: EmailAddress[]; // should be only one though) + to: EmailAddress[]; + cc?: EmailAddress[]; + bcc?: EmailAddress[]; + subject: string; // the subject line + references?: string[]; // an array of reference message id values (not set if no reference values present) + inReplyTo?: string[]; // an array of In-Reply-To message id values (not set if no in-reply-to values present) + priority?: string; // priority of the e-mail, always one of the following: normal (default), high, low + text: string; // text body + html: string; // html body + date?: Date; // If date could not be resolved or is not found this field is not set. Check the original date string from headers.date + attachments?: Attachment[]; + } + + + + class MailParser implements WritableStream { + constructor(options? : Options); + on(event : string, callback : (any : any) => void) : void; + + // from WritableStream + writable: boolean; + write(buffer: Buffer, cb?: Function): boolean; + write(str: string, cb?: Function): boolean; + write(str: string, encoding?: string, cb?: Function): boolean; + end(): void; + end(buffer: Buffer, cb?: Function): void; + end(str: string, cb?: Function): void; + end(str: string, encoding?: string, cb?: Function): void; + + // from EventEmitter + static listenerCount(emitter: EventEmitter, event: string): number; + addListener(event: string, listener: Function): EventEmitter; + on(event: string, listener: Function): EventEmitter; + once(event: string, listener: Function): EventEmitter; + removeListener(event: string, listener: Function): EventEmitter; + removeAllListeners(event?: string): EventEmitter; + setMaxListeners(n: number): void; + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + } +} + From 9f02d024a6938f9cacb17ced718d818775656645 Mon Sep 17 00:00:00 2001 From: Raphael ATALLAH Date: Mon, 17 Aug 2015 15:54:05 -0700 Subject: [PATCH 049/173] Updated typescript definitions for angular-odata-resources. Added support for $select --- .../angular-odata-resources-tests.ts | 9 +++++++++ .../angular-odata-resources.d.ts | 13 ++++++++----- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/angular-odata-resources/angular-odata-resources-tests.ts b/angular-odata-resources/angular-odata-resources-tests.ts index 5b8dbcc52..23286adc0 100644 --- a/angular-odata-resources/angular-odata-resources-tests.ts +++ b/angular-odata-resources/angular-odata-resources-tests.ts @@ -197,3 +197,12 @@ users = odataResourceClass.odata() var countResult = odataResourceClass.odata().count(); var total = countResult.result; + + + +var usersSelect1 = odataResourceClass.odata() + .select('name', 'user'); + + +var usersSelect2 = odataResourceClass.odata() + .select(['name', 'user']); \ No newline at end of file diff --git a/angular-odata-resources/angular-odata-resources.d.ts b/angular-odata-resources/angular-odata-resources.d.ts index 0a83df2c3..fb6fa5b81 100644 --- a/angular-odata-resources/angular-odata-resources.d.ts +++ b/angular-odata-resources/angular-odata-resources.d.ts @@ -278,14 +278,17 @@ declare module OData { private expandables; constructor(callback: ProviderCallback); filter(operand1: any, operand2?: any, operand3?: any): Provider; - orderBy(arg1: any, arg2?: any): Provider; + orderBy(arg1: string, arg2?: string): Provider; take(amount: number): Provider; skip(amount: number): Provider; private execute(); - query(success?: any, error?: any): T[]; - single(success?: any, error?: any): T; - get(data: any, success?: any, error?: any): T; - expand(params: any, otherParam1?: any, otherParam2?: any, otherParam3?: any, otherParam4?: any, otherParam5?: any, otherParam6?: any, otherParam7?: any): Provider; + query(success?: ((p:T)=>void), error?: (()=>void)): T[]; + single(success?: ((p:T)=>void), error?: (()=>void)): T; + get(key: any, success?: ((p:T)=>void), error?: (()=>void)): T; + expand(...params: string[]): Provider; + expand(params: string[]): Provider; + select(...params: string[]): Provider; + select(params: string[]): Provider; count(success?: (result: ICountResult) => any, error?: () => any):ICountResult; withInlineCount(): Provider; } From e99ef514ee0989bb5ce126e43dffd52b15df0be8 Mon Sep 17 00:00:00 2001 From: Raphael ATALLAH Date: Mon, 17 Aug 2015 16:06:16 -0700 Subject: [PATCH 050/173] 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 051/173] 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 052/173] 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 053/173] 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 054/173] 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 055/173] [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 056/173] 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 057/173] 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 058/173] 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 059/173] 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 060/173] 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 061/173] 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 062/173] 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 3ef00546da8850c9c962bffb87d65cd43a9b262b Mon Sep 17 00:00:00 2001 From: Marcin Porebski Date: Wed, 19 Aug 2015 15:09:10 +0200 Subject: [PATCH 063/173] 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 064/173] 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 065/173] 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 066/173] 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 067/173] 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 068/173] Fix cordova file transfer download --- cordova/cordova-tests.ts | 8 ++++++-- cordova/plugins/FileTransfer.d.ts | 8 ++++---- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/cordova/cordova-tests.ts b/cordova/cordova-tests.ts index d162b1ab6..491b49773 100644 --- a/cordova/cordova-tests.ts +++ b/cordova/cordova-tests.ts @@ -176,8 +176,12 @@ file.download('http://some.server.com/download.php', console.error('Failed with exception ' + err.exception); } }, - { headers: null }, - true); + true, + { + headers: { + "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA==" + } + }); file.upload('cdvfile://localhost/persistent/path/to/downloads/', 'http://some.server.com/download.php', diff --git a/cordova/plugins/FileTransfer.d.ts b/cordova/plugins/FileTransfer.d.ts index d0c023ae8..7cbde5322 100644 --- a/cordova/plugins/FileTransfer.d.ts +++ b/cordova/plugins/FileTransfer.d.ts @@ -53,8 +53,8 @@ interface FileTransfer { target: string, successCallback: (fileEntry: FileEntry) => void, errorCallback: (error: FileTransferError) => void, - options?: FileDownloadOptions, - trustAllHosts?: boolean): void; + trustAllHosts?: boolean, + options?: FileDownloadOptions): void; /** * Aborts an in-progress transfer. The onerror callback is passed a FileTransferError object * which has an error code of FileTransferError.ABORT_ERR. @@ -98,8 +98,8 @@ interface FileUploadOptions { /** Optional parameters for download method. */ interface FileDownloadOptions { - /** A map of header name/header values. Use an array to specify more than one value. */ - headers?: Object[]; + /** A map of header name/header values. */ + headers?: {}; } /** A FileTransferError object is passed to an error callback when an error occurs. */ From cb2b22f81a17658943fbcb06f15c0bde4e60e79c Mon Sep 17 00:00:00 2001 From: Marcin Porebski Date: Wed, 19 Aug 2015 18:48:48 +0200 Subject: [PATCH 069/173] string score definitions --- string_score/string_score-tests.ts | 8 ++++++++ string_score/string_score.d.ts | 8 ++++++++ 2 files changed, 16 insertions(+) create mode 100644 string_score/string_score-tests.ts create mode 100644 string_score/string_score.d.ts diff --git a/string_score/string_score-tests.ts b/string_score/string_score-tests.ts new file mode 100644 index 000000000..8a7399603 --- /dev/null +++ b/string_score/string_score-tests.ts @@ -0,0 +1,8 @@ +/// + +import string_score = require('string_score'); + +var a = 'abc'; +var b = 'xyz'; + +console.log(a.score(b).toString()); diff --git a/string_score/string_score.d.ts b/string_score/string_score.d.ts new file mode 100644 index 000000000..2d901ba39 --- /dev/null +++ b/string_score/string_score.d.ts @@ -0,0 +1,8 @@ +// Type definitions for url-template 0.1.22 +// Project: https://github.com/joshaven/string_score +// Definitions by: Marcin Porębski +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface String { + score: (word: string, fuzzy?: number) => number; +} From 0659ddca429da57326e2856c92bf51dfbad29dc2 Mon Sep 17 00:00:00 2001 From: Ray Solomon Date: Wed, 19 Aug 2015 10:10:20 -0700 Subject: [PATCH 070/173] bunyan: fix ts1202 errors when targeting es6 Before this change: ``` [ray@localhost DefinitelyTyped]$ tsc --noImplicitAny bunyan/bunyan-test.ts --module commonjs --target es6 bunyan/bunyan-test.ts(3,1): error TS1202: Import assignment cannot be used when targeting ECMAScript 6 or higher. Consider using 'import * as ns from "mod"', 'import {a} from "mod"' or 'import d from "mod"' instead. bunyan/bunyan.d.ts(9,5): error TS1202: Import assignment cannot be used when targeting ECMAScript 6 or higher. Consider using 'import * as ns from "mod"', 'import {a} from "mod"' or 'import d from "mod"' instead. [ray@localhost DefinitelyTyped]$ ``` After this change: ``` [ray@localhost DefinitelyTyped]$ tsc --noImplicitAny bunyan/bunyan-test.ts --module commonjs --target es6 [ray@localhost DefinitelyTyped]$ ``` --- bunyan/bunyan-test.ts | 2 +- bunyan/bunyan.d.ts | 8 +++----- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/bunyan/bunyan-test.ts b/bunyan/bunyan-test.ts index b8e51d145..c10c6c6e0 100644 --- a/bunyan/bunyan-test.ts +++ b/bunyan/bunyan-test.ts @@ -1,6 +1,6 @@ /// -import bunyan = require('bunyan'); +import * as bunyan from 'bunyan'; var ringBufferOptions:bunyan.RingBufferOptions = { limit: 100 diff --git a/bunyan/bunyan.d.ts b/bunyan/bunyan.d.ts index 1f73705c3..e491b8cd3 100644 --- a/bunyan/bunyan.d.ts +++ b/bunyan/bunyan.d.ts @@ -6,9 +6,7 @@ /// declare module "bunyan" { - import events = require('events'); - import EventEmitter = events.EventEmitter; - import WritableStream = NodeJS.WritableStream; + import { EventEmitter } from 'events'; class Logger extends EventEmitter { constructor(options:LoggerOptions); @@ -52,7 +50,7 @@ declare module "bunyan" { name: string; streams?: Stream[]; level?: string | number; - stream?: WritableStream; + stream?: NodeJS.WritableStream; serializers?: Serializers; src?: boolean; } @@ -65,7 +63,7 @@ declare module "bunyan" { type?: string; level?: number | string; path?: string; - stream?: WritableStream | Stream; + stream?: NodeJS.WritableStream | Stream; closeOnExit?: boolean; } From 8409007d3e20b8d462d945b5c3c9d86d2e6bbf06 Mon Sep 17 00:00:00 2001 From: Andrew F Date: Wed, 19 Aug 2015 11:35:40 -0700 Subject: [PATCH 071/173] Add interface typing --- segment-analytics/segment-analytics.d.ts | 98 ++++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100755 segment-analytics/segment-analytics.d.ts diff --git a/segment-analytics/segment-analytics.d.ts b/segment-analytics/segment-analytics.d.ts new file mode 100755 index 000000000..6d5f4465f --- /dev/null +++ b/segment-analytics/segment-analytics.d.ts @@ -0,0 +1,98 @@ +// Type definitions for Segment's analytics.js +// Project: https://segment.com/docs/libraries/analytics.js/ +// Definitions by: Andrew Fong +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module SegmentAnalytics { + + // Generic options object with integrations + interface ISegmentOpts { + integrations: Integrations; + }; + + // The actual analytics.js object + interface AnalyticsJS { + + /* Configure Segment with write key */ + load(writeKey: string); + + /* The identify method is how you tie one of your users and their actions + to a recognizable userId and traits. */ + identify(userId: string, traits?: Object, + options?: ISegmentOpts, + callback?: () => void): void; + identify(userId: string, traits: Object, callback?: () => void): void; + identify(userId: string, callback?: () => void): void; + identify(traits?: Object, + options?: ISegmentOpts, + callback?: () => void): void; + identify(traits?: Object, + callback?: () => void): void; + identify(callback: () => void): void; + + /* The track method lets you record any actions your users perform. */ + track(event: string, properties?: Object, + options?: ISegmentOpts, + callback?: () => void): void; + track(event: string, properties?: Object, + callback?: () => void): void; + track(event: string, callback?: () => void): void; + + /* The page method lets you record page views on your website, along with + optional extra information about the page being viewed. */ + page(category: string, name: string, properties?: Object, + options?: ISegmentOpts, + callback?: () => void): void; + page(name?: string, properties?: Object, + options?: ISegmentOpts, + callback?: () => void): void; + page(name?: string, properties?: Object, callback?: () => void): void; + page(name?: string, callback?: () => void): void; + page(properties?: Object, + options?: ISegmentOpts, + callback?: () => void): void; + page(callback?: () => void): void; + + /* The alias method combines two previously unassociated user identities. + This comes in handy if the same user visits from two different devices + and you want to combine their history. + + Some providers also don’t alias automatically for you when an anonymous + user signs up (like Mixpanel), so you need to call alias manually right + after sign up with their brand new userId. */ + alias(userId: string, previousId?: string, + options?: ISegmentOpts, + callback?: () => void): void; + alias(userId: string, previousId?: string, callback?: () => void): void; + alias(userId: string, callback?: () => void): void; + alias(userId: string, options?: ISegmentOpts, + callback?: () => void): void; + + /* trackLink is a helper that binds a track call to whenever a link is + clicked. Usually the page would change before you could call track, but + with trackLink a small timeout is inserted to give the track call enough + time to fire. */ + trackLink(elements: Element|Element[], event: string, properties?: Object); + + /* trackForm is a helper that binds a track call to a form submission. + Usually the page would change before you could call track, but with + trackForm a small timeout is inserted to give the track call enough + time to fire. */ + trackForm(elements: Element|Element[], event: string, properties?: Object); + + /* The ready method allows you to pass in a callback that will be called as + soon as all of your enabled integrations have loaded. It’s like jQuery’s + ready method, except for integrations. */ + ready(callback: () => void); + + // Cookie-based user object + user(): { + id(): string; + logout(): void; + reset(): void; + }; + } +} + + +// declare var analytics: ISegment; \ No newline at end of file From 42edb17991ae0d38eb41325637e81d6e728c2da8 Mon Sep 17 00:00:00 2001 From: Andrew F Date: Wed, 19 Aug 2015 12:03:08 -0700 Subject: [PATCH 072/173] Group method --- segment-analytics/segment-analytics.d.ts | 34 +++++++++++++++--------- 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/segment-analytics/segment-analytics.d.ts b/segment-analytics/segment-analytics.d.ts index 6d5f4465f..1b8cc8bf5 100755 --- a/segment-analytics/segment-analytics.d.ts +++ b/segment-analytics/segment-analytics.d.ts @@ -6,8 +6,9 @@ declare module SegmentAnalytics { // Generic options object with integrations - interface ISegmentOpts { - integrations: Integrations; + interface SegmentOpts { + integrations?: Integrations; + anonymousId?: string; }; // The actual analytics.js object @@ -19,12 +20,12 @@ declare module SegmentAnalytics { /* The identify method is how you tie one of your users and their actions to a recognizable userId and traits. */ identify(userId: string, traits?: Object, - options?: ISegmentOpts, + options?: SegmentOpts, callback?: () => void): void; identify(userId: string, traits: Object, callback?: () => void): void; identify(userId: string, callback?: () => void): void; identify(traits?: Object, - options?: ISegmentOpts, + options?: SegmentOpts, callback?: () => void): void; identify(traits?: Object, callback?: () => void): void; @@ -32,7 +33,7 @@ declare module SegmentAnalytics { /* The track method lets you record any actions your users perform. */ track(event: string, properties?: Object, - options?: ISegmentOpts, + options?: SegmentOpts, callback?: () => void): void; track(event: string, properties?: Object, callback?: () => void): void; @@ -41,18 +42,27 @@ declare module SegmentAnalytics { /* The page method lets you record page views on your website, along with optional extra information about the page being viewed. */ page(category: string, name: string, properties?: Object, - options?: ISegmentOpts, + options?: SegmentOpts, callback?: () => void): void; page(name?: string, properties?: Object, - options?: ISegmentOpts, + options?: SegmentOpts, callback?: () => void): void; page(name?: string, properties?: Object, callback?: () => void): void; page(name?: string, callback?: () => void): void; page(properties?: Object, - options?: ISegmentOpts, + options?: SegmentOpts, callback?: () => void): void; page(callback?: () => void): void; + /* The group method associates an individual user with a group. The group + can a company, organization, account, project, team or any other name + you came up with for the same concept. */ + group(groupId: string, traits?: Object, + options?: SegemntOpts, + callback?: () => void): void; + group(groupId: string, traits?: Object, callback?: () => void): void; + group(groupId: string, callback?: () => void): void; + /* The alias method combines two previously unassociated user identities. This comes in handy if the same user visits from two different devices and you want to combine their history. @@ -61,11 +71,11 @@ declare module SegmentAnalytics { user signs up (like Mixpanel), so you need to call alias manually right after sign up with their brand new userId. */ alias(userId: string, previousId?: string, - options?: ISegmentOpts, + options?: SegmentOpts, callback?: () => void): void; alias(userId: string, previousId?: string, callback?: () => void): void; alias(userId: string, callback?: () => void): void; - alias(userId: string, options?: ISegmentOpts, + alias(userId: string, options?: SegmentOpts, callback?: () => void): void; /* trackLink is a helper that binds a track call to whenever a link is @@ -90,9 +100,9 @@ declare module SegmentAnalytics { id(): string; logout(): void; reset(): void; + anonymousId(newId?: string): string; }; } } - -// declare var analytics: ISegment; \ No newline at end of file +declare var analytics: SegmentAnalytics.AnalyticsJS; From d4a0660d7174dfa67ff1c983fd0d4001220e96c3 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Thu, 20 Aug 2015 01:04:01 +0500 Subject: [PATCH 073/173] lodash: changed _.isRegExp() method --- lodash/lodash-tests.ts | 8 ++++++-- lodash/lodash.d.ts | 27 +++++++++++++++++---------- 2 files changed, 23 insertions(+), 12 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 2cbec6853..62d17bbe0 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1168,6 +1168,12 @@ result = _(undefined).isNaN(); result = _.isNative(Array.prototype.push); result = _(Array.prototype.push).isNative(); +// _.isRegExp +result = _.isRegExp(any); +result = _(1).isRegExp(); +result = _([]).isRegExp(); +result = _({}).isRegExp(); + // _.isTypedArray result = _.isTypedArray([]); result = _([]).isTypedArray(); @@ -1427,8 +1433,6 @@ result = _.isPlainObject(new Stooge('moe', 40)); result = _.isPlainObject([1, 2, 3]); result = _.isPlainObject({ 'name': 'moe', 'age': 40 }); -result = _.isRegExp(/moe/); - result = _.isString('moe'); result = _.isUndefined(void 0); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index c088f5459..71c4a2ef0 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -6160,6 +6160,23 @@ declare module _ { isNative(): boolean; } + //_.isRegExp + interface LoDashStatic { + /** + * Checks if value is classified as a RegExp object. + * @param value The value to check. + * @return Returns true if value is correctly classified, else false. + */ + isRegExp(value?: any): boolean; + } + + interface LoDashWrapperBase { + /** + * see _.isRegExp + */ + isRegExp(): boolean; + } + //_.isTypedArray interface LoDashStatic { /** @@ -7036,16 +7053,6 @@ declare module _ { isPlainObject(value?: any): boolean; } - //_.isRegExp - interface LoDashStatic { - /** - * Checks if value is a regular expression. - * @param value The value to check. - * @return True if the value is a regular expression, else false. - **/ - isRegExp(value?: any): boolean; - } - //_.isString interface LoDashStatic { /** From 4d2ad3d1b3a5b8890d68ab370ad78dbaf723d914 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Wed, 19 Aug 2015 05:40:51 +0500 Subject: [PATCH 074/173] lodash: changed _.isArray() method --- lodash/lodash-tests.ts | 9 ++++++--- lodash/lodash.d.ts | 27 +++++++++++++++++---------- 2 files changed, 23 insertions(+), 13 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 2cbec6853..a3728d7f2 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1139,6 +1139,12 @@ result = _(1).gte(2); result = _([]).gte(2); result = _({}).gte(2); +// _.isArray +result = _.isArray(any); +result = _(1).isArray(); +result = _([]).isArray(); +result = _({}).isArray(); + // _.isEmpty result = _.isEmpty([1, 2, 3]); result = _.isEmpty({}); @@ -1365,9 +1371,6 @@ result = _.invert({ 'first': 'moe', 'second': 'larry' }); (function (...args: any[]) { return _.isArguments(arguments); })(1, 2, 3); -(function () { return _.isArray(arguments); })(); -result = _.isArray([1, 2, 3]); - result = _.isBoolean(null); result = _.isDate(new Date()); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index c088f5459..61c99b913 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -6080,6 +6080,23 @@ declare module _ { gte(other: any): boolean; } + //_.isArray + interface LoDashStatic { + /** + * Checks if value is classified as an Array object. + * @param value The value to check. + * @return Returns true if value is correctly classified, else false. + **/ + isArray(value?: any): boolean; + } + + interface LoDashWrapperBase { + /** + * @see _.isArray + */ + isArray(): boolean; + } + //_.isEmpty interface LoDashStatic { /** @@ -6839,16 +6856,6 @@ declare module _ { isArguments(value?: any): boolean; } - //_.isArray - interface LoDashStatic { - /** - * Checks if value is an array. - * @param value The value to check. - * @return True if the value is an array, else false. - **/ - isArray(value?: any): boolean; - } - //_.isBoolean interface LoDashStatic { /** From 8f3167dc9f512956db10a3ba4524978f64d1aeac Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Thu, 20 Aug 2015 01:20:35 +0500 Subject: [PATCH 075/173] lodash: changed _.deburr() method --- lodash/lodash-tests.ts | 4 ++++ lodash/lodash.d.ts | 22 +++++++++++++++++++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 2cbec6853..c3e378c11 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1652,7 +1652,11 @@ result = _.uniqueId(); result = _.camelCase('Foo Bar'); result = _.capitalize('fred'); + +// _.deburr result = _.deburr('déjà vu'); +result = _('déjà vu').deburr(); + result = _.endsWith('abc', 'c'); // _.escape diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index c088f5459..506c3c47b 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -7441,7 +7441,27 @@ declare module _ { interface LoDashStatic { camelCase(str?: string): string; capitalize(str?: string): string; - deburr(str?: string): string; + } + + //_.deburr + interface LoDashStatic { + /** + * Deburrs string by converting latin-1 supplementary letters to basic latin letters and removing combining + * diacritical marks. + * @param string The string to deburr. + * @return Returns the deburred string. + */ + deburr(string?: string): string; + } + + interface LoDashWrapper { + /** + * @see _.deburr + */ + deburr(): string; + } + + interface LoDashStatic { endsWith(str?: string, target?: string, position?: number): boolean; } From d34f2fd473602067925a4304e350e2378767e2d7 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Thu, 20 Aug 2015 01:33:02 +0500 Subject: [PATCH 076/173] lodash: changed _.isUndefined() method --- lodash/lodash-tests.ts | 8 ++++++-- lodash/lodash.d.ts | 27 +++++++++++++++++---------- 2 files changed, 23 insertions(+), 12 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 2cbec6853..e37c827ed 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1172,6 +1172,12 @@ result = _(Array.prototype.push).isNative(); result = _.isTypedArray([]); result = _([]).isTypedArray(); +// _.isUndefined +result = _.isUndefined(any); +result = _(1).isUndefined(); +result = _([]).isUndefined(); +result = _({}).isUndefined(); + // _.lt result = _.lt(1, 2); result = _(1).lt(2); @@ -1431,8 +1437,6 @@ result = _.isRegExp(/moe/); result = _.isString('moe'); -result = _.isUndefined(void 0); - result = _.keys({ 'one': 1, 'two': 2, 'three': 3 }); result = _({ 'one': 1, 'two': 2, 'three': 3 }).keys().value(); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index c088f5459..2c2220238 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -6177,6 +6177,23 @@ declare module _ { isTypedArray(): boolean; } + //_.isUndefined + interface LoDashStatic { + /** + * Checks if value is undefined. + * @param value The value to check. + * @return Returns true if value is undefined, else false. + **/ + isUndefined(value: any): boolean; + } + + interface LoDashWrapperBase { + /** + * see _.isUndefined + */ + isUndefined(): boolean; + } + //_.lt interface LoDashStatic { /** @@ -7056,16 +7073,6 @@ declare module _ { isString(value?: any): boolean; } - //_.isUndefined - interface LoDashStatic { - /** - * Checks if value is undefined. - * @param value The value to check. - * @return True if the value is undefined, else false. - **/ - isUndefined(value?: any): boolean; - } - //_.keys interface LoDashStatic { /** From 46dc2e2b3d4cd73e7d80235608da3b69bee5e449 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Wed, 19 Aug 2015 05:54:51 +0500 Subject: [PATCH 077/173] lodash: changed _.startsWith() method --- lodash/lodash-tests.ts | 5 +++++ lodash/lodash.d.ts | 20 +++++++++++++++++++- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 2cbec6853..c8b386a7e 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1683,7 +1683,12 @@ result = _.snakeCase('Foo Bar'); result = _('Foo Bar').snakeCase(); result = _.startCase('--foo-bar'); + +// _.startsWith result = _.startsWith('abc', 'a'); +result = _.startsWith('abc', 'a', 1); +result = _('abc').startsWith('a'); +result = _('abc').startsWith('a', 1); // _.trim result = _.trim(); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index c088f5459..ecbcc05f2 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -7530,7 +7530,25 @@ declare module _ { interface LoDashStatic { startCase(str?: string): string; - startsWith(str?: string, target?: string, position?: number): boolean; + } + + //_.startsWith + interface LoDashStatic { + /** + * Checks if string starts with the given target string. + * @param string The string to search. + * @param target The string to search for. + * @param position The position to search from. + * @return Returns true if string starts with target, else false. + */ + startsWith(string?: string, target?: string, position?: number): boolean; + } + + interface LoDashWrapper { + /** + * @see _.startsWith + */ + startsWith(target?: string, position?: number): boolean; } //_.trim From 763b5865d4d69da428f3ad65258d7b31be1e7058 Mon Sep 17 00:00:00 2001 From: Andrew F Date: Wed, 19 Aug 2015 13:35:56 -0700 Subject: [PATCH 078/173] Add tests and additional definitions --- segment-analytics/segment-analytics-tests.ts | 211 +++++++++++++++++++ segment-analytics/segment-analytics.d.ts | 84 +++++--- 2 files changed, 265 insertions(+), 30 deletions(-) create mode 100755 segment-analytics/segment-analytics-tests.ts diff --git a/segment-analytics/segment-analytics-tests.ts b/segment-analytics/segment-analytics-tests.ts new file mode 100755 index 000000000..56df14e28 --- /dev/null +++ b/segment-analytics/segment-analytics-tests.ts @@ -0,0 +1,211 @@ +/// +/// + +// Some random vals to use + +// Use for page props or user traits +var testProps = { + favoriteCheese: "brie", + favoritePie: "apple" +}; + +// Segment options +var testOpts = { + integrations: { + Mixpanel: true + } +}; + +var testCb = function() {}; + + +///////////// + +function test_identify() { + // userId and traits + analytics.identify('1e810c197e', { + name: 'Bill Lumbergh', + email: 'bill@initech.com' + }); + + // No traits + analytics.identify('1e810c197e'); + + // No userId + analytics.identify({ + email: 'bill@initech.com', + newsletter: true, + industry: 'Technology' + }); + + // Callback + analytics.identify('1e810c197e', function(){ + // Do something after the identify request has been sent, like + // submit a form or redirect to a new page. + }); + + // With options + analytics.identify('1e810c197e', testProps, testOpts); + + // All args + analytics.identify('1e810c197e', testProps, testOpts, testCb); +} + +function testTrack() { + analytics.track('Signed Up'); + + analytics.track('Signed Up', { + plan: 'Startup', + source: 'Analytics Academy' + }); + + analytics.track('Signed Up', testProps, testOpts, testCb); +} + +function testPage() { + analytics.page('Signup'); + + analytics.page('Pricing', { + title: 'Segment Pricing', + url: 'https://segment.com/pricing', + path: '/pricing', + referrer: 'https://segment.com' + }); + + analytics.page('Category', 'Signup'); + + analytics.page('Signup', testProps, testOpts, testCb); +} + +function testAlias() { + analytics.alias('019mr8mf4r'); + analytics.alias('newId', 'oldId'); + analytics.alias('019mr8mf4r', testOpts, testCb); +} + +function testGroup() { + analytics.group('test_group'); + analytics.group('test_group', { + name: "Initech", + industry: "Technology", + employees: 329 + }); + analytics.group('test_group', testProps, testOpts, testCb); +} + +function testTrackLink() { + var link1 = document.getElementById('free-trial-link'); + var link2 = document.getElementById('free-trial-link-2'); + var links = $('.free-trial-links'); + + analytics.trackLink(link1, 'Clicked Free-Trial Link'); + analytics.trackLink(link1, 'Clicked Free-Trial Link', { + plan: 'Enterprise' + }); + + analytics.trackLink([link1, link2], 'Clicked Free-Trial Link', testProps); + analytics.trackLink(links, 'Clicked Free-Trial Link', testProps); + + // With function name and properties + analytics.trackLink(links, + function(elm) { + return String(elm); + }, + function(elm) { + return { + x: 123, + y: 456 + }; + }); +} + +function testTrackForm() { + var form1 = document.getElementById('signup-form'); + var form2 = document.getElementById('signin-form'); + var forms = $('.forms'); + + analytics.trackForm(form1, 'Signed up'); + analytics.trackForm(form1, 'Signed Up', { + plan: 'Premium', + revenue: 99.00 + }); + + analytics.trackForm([form1, form2], 'Clicked Free-Trial Link', testProps); + analytics.trackForm(forms, 'Clicked Free-Trial Link', testProps); + + // With function name and properties + analytics.trackForm(forms, + function(elm) { + return String(elm); + }, + function(elm) { + return { + x: 123, + y: 456 + }; + }); +} + +function testReady() { + analytics.ready(function(){ + ( window).mixpanel.set_config({ verbose: true }); + }); +} + +function testUserGroup() { + analytics.ready(function(){ + var user = analytics.user(); + var id = user.id(); + var traits = user.traits(); + }); + + analytics.ready(function(){ + var group = analytics.group(); + var id = group.id(); + var traits = group.traits(); + }); +} + +function testClearTraits() { + analytics.user().traits({}); + analytics.group().traits({}); +} + +function testResetLogout() { + analytics.reset(); +} + +function testAnonId() { + analytics.user().anonymousId(); + analytics.user().anonymousId('ABC-123-XYZ'); + + analytics.identify('123', { + gender: 'Male', + }, { + anonymousId: 'ABC-123-XYZ' + }); + + analytics.page({}, { anonymousId: 'ABC-123-XYZ' }); + + analytics.track('Clicked CTA', { + callToAction: 'Signup' + }, { + anonymousId: 'ABC-123-XYZ' + }); +} + +function testDebug() { + analytics.debug(); + analytics.debug(false); +} + +declare var bigdata: any; +function testEmitter() { + analytics.on('track', function(event, properties, options){ + bigdata.push(['recordEvent', event]); + }); +} + +function testTimeout() { + analytics.timeout(500); +} \ No newline at end of file diff --git a/segment-analytics/segment-analytics.d.ts b/segment-analytics/segment-analytics.d.ts index 1b8cc8bf5..f2de55846 100755 --- a/segment-analytics/segment-analytics.d.ts +++ b/segment-analytics/segment-analytics.d.ts @@ -3,37 +3,35 @@ // Definitions by: Andrew Fong // Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + declare module SegmentAnalytics { // Generic options object with integrations - interface SegmentOpts { - integrations?: Integrations; + interface SegmentOpts { + integrations?: any; anonymousId?: string; - }; + } // The actual analytics.js object - interface AnalyticsJS { + interface AnalyticsJS { /* Configure Segment with write key */ load(writeKey: string); /* The identify method is how you tie one of your users and their actions to a recognizable userId and traits. */ - identify(userId: string, traits?: Object, - options?: SegmentOpts, + identify(userId: string, traits?: Object, options?: SegmentOpts, callback?: () => void): void; identify(userId: string, traits: Object, callback?: () => void): void; identify(userId: string, callback?: () => void): void; - identify(traits?: Object, - options?: SegmentOpts, - callback?: () => void): void; - identify(traits?: Object, + identify(traits?: Object, options?: SegmentOpts, callback?: () => void): void; + identify(traits?: Object, callback?: () => void): void; identify(callback: () => void): void; /* The track method lets you record any actions your users perform. */ - track(event: string, properties?: Object, - options?: SegmentOpts, + track(event: string, properties?: Object, options?: SegmentOpts, callback?: () => void): void; track(event: string, properties?: Object, callback?: () => void): void; @@ -42,23 +40,19 @@ declare module SegmentAnalytics { /* The page method lets you record page views on your website, along with optional extra information about the page being viewed. */ page(category: string, name: string, properties?: Object, - options?: SegmentOpts, - callback?: () => void): void; + options?: SegmentOpts, callback?: () => void): void; page(name?: string, properties?: Object, - options?: SegmentOpts, - callback?: () => void): void; + options?: SegmentOpts, callback?: () => void): void; page(name?: string, properties?: Object, callback?: () => void): void; page(name?: string, callback?: () => void): void; - page(properties?: Object, - options?: SegmentOpts, + page(properties?: Object, options?: SegmentOpts, callback?: () => void): void; page(callback?: () => void): void; /* The group method associates an individual user with a group. The group - can a company, organization, account, project, team or any other name + can a company, organization, account, project, team or any other name you came up with for the same concept. */ - group(groupId: string, traits?: Object, - options?: SegemntOpts, + group(groupId: string, traits?: Object, options?: SegmentOpts, callback?: () => void): void; group(groupId: string, traits?: Object, callback?: () => void): void; group(groupId: string, callback?: () => void): void; @@ -70,39 +64,69 @@ declare module SegmentAnalytics { Some providers also don’t alias automatically for you when an anonymous user signs up (like Mixpanel), so you need to call alias manually right after sign up with their brand new userId. */ - alias(userId: string, previousId?: string, - options?: SegmentOpts, + alias(userId: string, previousId?: string, options?: SegmentOpts, callback?: () => void): void; alias(userId: string, previousId?: string, callback?: () => void): void; alias(userId: string, callback?: () => void): void; - alias(userId: string, options?: SegmentOpts, - callback?: () => void): void; + alias(userId: string, options?: SegmentOpts, callback?: () => void): void; /* trackLink is a helper that binds a track call to whenever a link is clicked. Usually the page would change before you could call track, but with trackLink a small timeout is inserted to give the track call enough time to fire. */ - trackLink(elements: Element|Element[], event: string, properties?: Object); + trackLink(elements: JQuery|Element[]|Element, + event: string|{ (elm: Element): string }, + properties?: Object|{ (elm: Element): Object }); /* trackForm is a helper that binds a track call to a form submission. Usually the page would change before you could call track, but with trackForm a small timeout is inserted to give the track call enough time to fire. */ - trackForm(elements: Element|Element[], event: string, properties?: Object); + trackForm(elements: JQuery|Element[]|Element, + event: string|{ (Element): string }, + properties?: Object|{ (elm: Element): Object }); /* The ready method allows you to pass in a callback that will be called as soon as all of your enabled integrations have loaded. It’s like jQuery’s ready method, except for integrations. */ ready(callback: () => void); - // Cookie-based user object + /* If you need to clear the user and group id and traits we’ve added a + reset function that is most commonly used when your identified users + logout of your application. */ + reset(); + + /* Once Analytics.js loaded, you can retrieve information about the + currently identified user or group like their id and traits. */ user(): { id(): string; logout(): void; reset(): void; anonymousId(newId?: string): string; - }; + traits(newTraits?: Object): void; + } + + group(): { + id(): string; + traits(newTraits?: Object): void; + } + + /* Analytics.js has a debug mode that logs helpful messages to the + console. */ + debug(state?: boolean): void; + + /* The global analytics object emits events whenever you call alias, group, + identify, track or page. That way you can listen to those events and run + your own custom code. */ + on(event: string, + callback: { + (event: string, properties: Object, options: SegmentOpts): void + }); + + /* You can extend the length (in milliseconds) of the method callbacks and + helpers */ + timeout(milliseconds: number); } } -declare var analytics: SegmentAnalytics.AnalyticsJS; +declare var analytics: SegmentAnalytics.AnalyticsJS; From fdb85c2f307fb20458b640de55bb3a9b594a3fbc Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Mon, 17 Aug 2015 20:09:46 +0500 Subject: [PATCH 079/173] lodash: added _.attempt() method --- lodash/lodash-tests.ts | 16 +++++++++++++++- lodash/lodash.d.ts | 24 +++++++++++++++++++++--- 2 files changed, 36 insertions(+), 4 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 2cbec6853..8922569da 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -91,6 +91,12 @@ var result: any; var any: any; +interface TResult { + a: number; + b: string; + c: boolean; +} + // _.MapCache var testMapCache: _.MapCache; result = <(key: string) => boolean>testMapCache.delete; @@ -1539,9 +1545,17 @@ result = _(new TestValueIn()).valuesIn().value(); // → [1, 2, 3] /********** -* Utilities * +* Utility * ***********/ +// _.attempt +interface TestAttemptFn { + (): TResult; +} +var testAttempFn: TestAttemptFn; +result = _.attempt(testAttempFn); +result = _(testAttempFn).attempt(); + result = <{ name: string }>_.identity({ 'name': 'moe' }); _.mixin({ diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index c088f5459..6146bc97d 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -7614,9 +7614,27 @@ declare module _ { words(str?: string, pattern?: string|RegExp): string[]; } - /************* - * Utilities * - *************/ + /*********** + * Utility * + ***********/ + + //_.attempt + interface LoDashStatic { + /** + * Attempts to invoke func, returning either the result or the caught error object. Any additional arguments + * are provided to func when it’s invoked. + * @param func The function to attempt. + * @return Returns the func result or error object. + */ + attempt(func: (...args: any[]) => TResult): TResult|Error; + } + + interface LoDashObjectWrapper { + /** + * @see _.attempt + */ + attempt(): TResult|Error; + } //_.identity interface LoDashStatic { From 496f751d45a1f63f3dc36171427cb658ea1d666f Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Tue, 18 Aug 2015 21:16:18 +0500 Subject: [PATCH 080/173] lodash: changed _.isFinite() method --- lodash/lodash-tests.ts | 12 ++++++------ lodash/lodash.d.ts | 31 ++++++++++++++++++------------- 2 files changed, 24 insertions(+), 19 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 2cbec6853..c2f0b3f2d 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1147,6 +1147,12 @@ result = _([1, 2, 3]).isEmpty(); result = _({}).isEmpty(); result = _('').isEmpty(); +// _.isFinite +result = _.isFinite(any); +result = _(1).isFinite(); +result = _([]).isFinite(); +result = _({}).isFinite(); + // _.isMatch var testIsMatchCustiomizerFn: (value: any, other: any, indexOrKey: number|string) => boolean; result = _.isMatch({}, {}); @@ -1399,12 +1405,6 @@ result = _(testEqArray).isEqual(testEqOtherArray, testEqCustomizerFn); result = _.eq(testEqArray, testEqOtherArray, testEqCustomizerFn); result = _(testEqArray).eq(testEqOtherArray, testEqCustomizerFn); -result = _.isFinite(-101); -result = _.isFinite('10'); -result = _.isFinite(true); -result = _.isFinite(''); -result = _.isFinite(Infinity); - result = _.isFunction(_); result = _.isNull(null); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index c088f5459..9e4834df8 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -6098,6 +6098,24 @@ declare module _ { isEmpty(): boolean; } + //_.isFinite + interface LoDashStatic { + /** + * Checks if value is a finite primitive number. + * Note: This method is based on Number.isFinite. + * @param value The value to check. + * @return Returns true if value is a finite number, else false. + **/ + isFinite(value?: any): boolean; + } + + interface LoDashWrapperBase { + /** + * @see _.isFinite + */ + isFinite(): boolean; + } + //_.isMatch interface isMatchCustomizer { (value: any, other: any, indexOrKey?: number|string): boolean; @@ -6970,19 +6988,6 @@ declare module _ { thisArg?: any): boolean; } - //_.isFinite - interface LoDashStatic { - /** - * Checks if value is, or can be coerced to, a finite number. - * - * Note: This is not the same as native isFinite which will return true for booleans and empty - * strings. See http://es5.github.io/#x15.1.2.5. - * @param value The value to check. - * @return True if the value is finite, else false. - **/ - isFinite(value?: any): boolean; - } - //_.isFunction interface LoDashStatic { /** From 01730f3e2796bae492464e00c9591ef8c10f0aca Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Tue, 18 Aug 2015 20:47:46 +0500 Subject: [PATCH 081/173] lodash: changed _.pad(), _.padLeft() and _.padRight() methods --- lodash/lodash-tests.ts | 19 +++++++++++++ lodash/lodash.d.ts | 64 ++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 80 insertions(+), 3 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 2cbec6853..4008f23f7 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1664,12 +1664,31 @@ result = _.escapeRegExp('[lodash](https://lodash.com/)'); result = _('[lodash](https://lodash.com/)').escapeRegExp(); result = _.kebabCase('Foo Bar'); + +// _.pad +result = _.pad('abd'); result = _.pad('abc', 8); result = _.pad('abc', 8, '_-'); +result = _('abc').pad(); +result = _('abc').pad(8); +result = _('abc').pad(8, '_-'); + +// _.padLeft +result = _.padLeft('abc'); result = _.padLeft('abc', 6); result = _.padLeft('abc', 6, '_-'); +result = _('abc').padLeft(); +result = _('abc').padLeft(6); +result = _('abc').padLeft(6, '_-'); + +// _.padRight +result = _.padRight('abc'); result = _.padRight('abc', 6); result = _.padRight('abc', 6, '_-'); +result = _('abc').padRight(); +result = _('abc').padRight(6); +result = _('abc').padRight(6, '_-'); + result = _.repeat('*', 3); // _.parseInt diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index c088f5459..6eb4a69c6 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -7482,9 +7482,67 @@ declare module _ { interface LoDashStatic { kebabCase(str?: string): string; - pad(str?: string, length?: number, chars?: string): string; - padLeft(str?: string, length?: number, chars?: string): string; - padRight(str?: string, length?: number, chars?: string): string; + } + + interface LoDashStatic { + /** + * + * @param string The string to pad. + * @param length The padding length. + * @param chars The string used as padding. + * @return Returns the padded string. + */ + pad(string?: string, length?: number, chars?: string): string; + } + + //_.pad + interface LoDashWrapper { + /** + * @see _.pad + */ + pad(length?: number, chars?: string): string; + } + + //_.padLeft + interface LoDashStatic { + /** + * Pads string on the left side if it’s shorter than length. Padding characters are truncated if they exceed + * length. + * @param string The string to pad. + * @param length The padding length. + * @param chars The string used as padding. + * @return Returns the padded string. + */ + padLeft(string?: string, length?: number, chars?: string): string; + } + + //_.padLeft + interface LoDashWrapper { + /** + * @see _.padLeft + */ + padLeft(length?: number, chars?: string): string; + } + + //_.padRight + interface LoDashStatic { + /** + * Pads string on the right side if it’s shorter than length. Padding characters are truncated if they exceed + * length. + * @param string The string to pad. + * @param length The padding length. + * @param chars The string used as padding. + * @return Returns the padded string. + */ + padRight(string?: string, length?: number, chars?: string): string; + } + + //_.padRight + interface LoDashWrapper { + /** + * @see _.padRight + */ + padRight(length?: number, chars?: string): string; } //_.parseInt From 68b97ecc7d1d15f64673aa2ab092ebb283d613fc Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Tue, 11 Aug 2015 22:13:13 +0500 Subject: [PATCH 082/173] angularjs: added Deferred tests --- angularjs/angular-tests.ts | 42 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index 10d806217..01b8eff26 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -325,6 +325,48 @@ httpFoo.success((data, status, headers, config) => { }); +// Deferred signature tests +module TestDeferred { + var any: any; + + interface TResult { + a: number; + b: string; + c: boolean; + } + var tResult: TResult; + + var deferred: angular.IDeferred; + + // deferred.resolve + { + let result: void; + result = deferred.resolve(); + result = deferred.resolve(tResult); + } + + // deferred.reject + { + let result: void; + result = deferred.reject(); + result = deferred.reject(any); + } + + // deferred.notify + { + let result: void; + result = deferred.notify(); + result = deferred.notify(any); + } + + // deferred.promise + { + let result: angular.IPromise; + result = deferred.promise; + } +} + + // Promise signature tests module TestPromise { var result: any; From 7652914a5b38b44434f1f4173f377a05cb8f2cfd Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Tue, 11 Aug 2015 21:51:19 +0500 Subject: [PATCH 083/173] angularjs: changed $timeout signature, added tests --- angularjs/angular-tests.ts | 39 ++++++++++++++++++++++++++++++++++++++ angularjs/angular.d.ts | 5 +++-- 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index 10d806217..a9f77b97e 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -381,6 +381,45 @@ var scope: ng.IScope = element.scope(); var isolateScope: ng.IScope = element.isolateScope(); +// $timeout signature tests +module TestTimeout { + interface TResult { + a: number; + b: string; + c: boolean; + } + var fnTResult: (...args: any[]) => TResult; + var promiseAny: angular.IPromise; + var $timeout: angular.ITimeoutService; + + // $timeout + { + let result: angular.IPromise; + result = $timeout(); + } + { + let result: angular.IPromise; + result = $timeout(1); + result = $timeout(1, true); + } + { + let result: angular.IPromise; + result = $timeout(fnTResult); + result = $timeout(fnTResult, 1); + result = $timeout(fnTResult, 1, true); + result = $timeout(fnTResult, 1, true, 1); + result = $timeout(fnTResult, 1, true, 1, ''); + result = $timeout(fnTResult, 1, true, 1, '', true); + } + + // $timeout.cancel + { + let result: boolean; + result = $timeout.cancel(); + result = $timeout.cancel(promiseAny); + } +} + function test_IAttributes(attributes: ng.IAttributes){ return attributes; diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 17c0c9384..0dc9ca2ca 100644 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -725,8 +725,9 @@ declare module angular { // see http://docs.angularjs.org/api/ng.$timeout /////////////////////////////////////////////////////////////////////////// interface ITimeoutService { - (func: (...args: any[]) => T, delay?: number, invokeApply?: boolean): IPromise; - cancel(promise: IPromise): boolean; + (delay?: number, invokeApply?: boolean): IPromise; + (fn: (...args: any[]) => T, delay?: number, invokeApply?: boolean, ...args: any[]): IPromise; + cancel(promise?: IPromise): boolean; } /////////////////////////////////////////////////////////////////////////// From 68374669bf0ef6eb20d5aff2ea4d96dca83e4621 Mon Sep 17 00:00:00 2001 From: Andrew F Date: Wed, 19 Aug 2015 13:42:59 -0700 Subject: [PATCH 084/173] load test; fix implicit any errors --- segment-analytics/segment-analytics-tests.ts | 5 +++++ segment-analytics/segment-analytics.d.ts | 16 ++++++++-------- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/segment-analytics/segment-analytics-tests.ts b/segment-analytics/segment-analytics-tests.ts index 56df14e28..b876ea1be 100755 --- a/segment-analytics/segment-analytics-tests.ts +++ b/segment-analytics/segment-analytics-tests.ts @@ -21,6 +21,10 @@ var testCb = function() {}; ///////////// +function test_load() { + analytics.load("YOUR_WRITE_KEY"); +} + function test_identify() { // userId and traits analytics.identify('1e810c197e', { @@ -63,6 +67,7 @@ function testTrack() { } function testPage() { + analytics.page(); analytics.page('Signup'); analytics.page('Pricing', { diff --git a/segment-analytics/segment-analytics.d.ts b/segment-analytics/segment-analytics.d.ts index f2de55846..3cdfbbc56 100755 --- a/segment-analytics/segment-analytics.d.ts +++ b/segment-analytics/segment-analytics.d.ts @@ -17,7 +17,7 @@ declare module SegmentAnalytics { interface AnalyticsJS { /* Configure Segment with write key */ - load(writeKey: string); + load(writeKey: string): void; /* The identify method is how you tie one of your users and their actions to a recognizable userId and traits. */ @@ -76,25 +76,25 @@ declare module SegmentAnalytics { time to fire. */ trackLink(elements: JQuery|Element[]|Element, event: string|{ (elm: Element): string }, - properties?: Object|{ (elm: Element): Object }); + properties?: Object|{ (elm: Element): Object }): void; /* trackForm is a helper that binds a track call to a form submission. Usually the page would change before you could call track, but with trackForm a small timeout is inserted to give the track call enough time to fire. */ trackForm(elements: JQuery|Element[]|Element, - event: string|{ (Element): string }, - properties?: Object|{ (elm: Element): Object }); + event: string|{ (elm: Element): string }, + properties?: Object|{ (elm: Element): Object }): void; /* The ready method allows you to pass in a callback that will be called as soon as all of your enabled integrations have loaded. It’s like jQuery’s ready method, except for integrations. */ - ready(callback: () => void); + ready(callback: () => void): void; /* If you need to clear the user and group id and traits we’ve added a reset function that is most commonly used when your identified users logout of your application. */ - reset(); + reset(): void; /* Once Analytics.js loaded, you can retrieve information about the currently identified user or group like their id and traits. */ @@ -121,11 +121,11 @@ declare module SegmentAnalytics { on(event: string, callback: { (event: string, properties: Object, options: SegmentOpts): void - }); + }): void; /* You can extend the length (in milliseconds) of the method callbacks and helpers */ - timeout(milliseconds: number); + timeout(milliseconds: number): void; } } From 7ed20bd0cf6438bc4590a765c69073212a7c5de9 Mon Sep 17 00:00:00 2001 From: MugeSo Date: Thu, 20 Aug 2015 12:13:36 +0900 Subject: [PATCH 085/173] rsmq-worker: fix contributor name --- rsmq-worker/rsmq-worker.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rsmq-worker/rsmq-worker.d.ts b/rsmq-worker/rsmq-worker.d.ts index 6af1564e1..5d4f9079a 100644 --- a/rsmq-worker/rsmq-worker.d.ts +++ b/rsmq-worker/rsmq-worker.d.ts @@ -1,6 +1,6 @@ // Type definitions for rsmq-worker 0.3.5 // Project: http://smrchy.github.io/rsmq/rsmq-worker/ -// Definitions by: Qubo +// Definitions by: TANAKA Koichi // Definitions: https://github.com/borisyankov/DefinitelyTyped /// From aa7e750ff747a0685378a7db12fede44a07877ef Mon Sep 17 00:00:00 2001 From: TimChen44 Date: Thu, 20 Aug 2015 16:22:03 +0800 Subject: [PATCH 086/173] Update ionic.d.ts Fix IonicActionSheetOptions bugs --- ionic/ionic.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ionic/ionic.d.ts b/ionic/ionic.d.ts index eba0ef6d4..b1b215217 100644 --- a/ionic/ionic.d.ts +++ b/ionic/ionic.d.ts @@ -16,7 +16,7 @@ declare module ionic { cancelText?: string; destructiveText?: string; cancel?: ()=>any; - buttonClicked?: ()=>any; + buttonClicked?: (index: any)=>any; destructiveButtonClicked?: ()=>any; cancelOnStateChange?: boolean; cssClass?: string; From e92bf375381c8e3b8717a2b714f303840856021c Mon Sep 17 00:00:00 2001 From: Rogier Schouten Date: Thu, 20 Aug 2015 10:56:30 +0200 Subject: [PATCH 087/173] Update Sinon typings for Sinon 1.16.0 Add setSystemTime() method --- sinon/sinon-tests.ts | 6 ++++++ sinon/sinon.d.ts | 17 +++++++++++++++-- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/sinon/sinon-tests.ts b/sinon/sinon-tests.ts index ca916788d..3e6f72086 100644 --- a/sinon/sinon-tests.ts +++ b/sinon/sinon-tests.ts @@ -109,3 +109,9 @@ testSix(); testSeven(); testEight(); testNine(); + +var clock: Sinon.SinonFakeTimers = sinon.useFakeTimers(); +clock.setSystemTime(1000); +clock.setSystemTime(new Date()); + + diff --git a/sinon/sinon.d.ts b/sinon/sinon.d.ts index 6440dda90..cdb316976 100644 --- a/sinon/sinon.d.ts +++ b/sinon/sinon.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Sinon 1.8.1 +// Type definitions for Sinon 1.16.0 // Project: http://sinonjs.org/ // Definitions by: William Sears // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -181,7 +181,20 @@ declare module Sinon { Date(year: number, month: number, day: number, hour: number, minute: number, second: number): Date; Date(year: number, month: number, day: number, hour: number, minute: number, second: number, ms: number): Date; restore(): void; - } + + /** + * Simulate the user changing the system clock while your program is running. It changes the 'now' timestamp + * without affecting timers, intervals or immediates. + * @param now The new 'now' in unix milliseconds + */ + setSystemTime(now: number): void; + /** + * Simulate the user changing the system clock while your program is running. It changes the 'now' timestamp + * without affecting timers, intervals or immediates. + * @param now The new 'now' as a JavaScript Date + */ + setSystemTime(date: Date): void; + } interface SinonFakeTimersStatic { (): SinonFakeTimers; From 8a49a6fc1427593898005eda6072da06333fccf1 Mon Sep 17 00:00:00 2001 From: Paul Jolly Date: Thu, 20 Aug 2015 10:17:13 +0100 Subject: [PATCH 088/173] Add type parameters to channel definitions --- postal/postal.d.ts | 62 +++++++++++++++++++++++----------------------- 1 file changed, 31 insertions(+), 31 deletions(-) diff --git a/postal/postal.d.ts b/postal/postal.d.ts index e1bad48cc..a23e14d87 100644 --- a/postal/postal.d.ts +++ b/postal/postal.d.ts @@ -15,36 +15,36 @@ interface IResolver { purge(options?: {topic?: string, binding?: string, compact?: boolean}): void; } -interface ICallback { - (data: any, envelope: IEnvelope): void +interface ICallback { + (data: T, envelope: IEnvelope): void } -interface ISubscriptionDefinition { +interface ISubscriptionDefinition { channel: string; topic: string; - callback: ICallback; + callback: ICallback; // after and before lack documentation - constraint(predicateFn: (data: any, envelope: IEnvelope) => boolean): ISubscriptionDefinition; - constraints(predicateFns: ((data: any, envelope: IEnvelope) => boolean)[]): ISubscriptionDefinition; - context(theContext: any): ISubscriptionDefinition; - debounce(interval: number): ISubscriptionDefinition; - defer(): ISubscriptionDefinition; - delay(waitTime: number): ISubscriptionDefinition; - disposeAfter(maxCalls: number): ISubscriptionDefinition; - distinct(): ISubscriptionDefinition; - distinctUntilChanged(): ISubscriptionDefinition; - logError(): ISubscriptionDefinition; - once(): ISubscriptionDefinition; - throttle(interval: number): ISubscriptionDefinition; - subscribe(callback: ICallback): ISubscriptionDefinition; + constraint(predicateFn: (data: T, envelope: IEnvelope) => boolean): ISubscriptionDefinition; + constraints(predicateFns: ((data: T, envelope: IEnvelope) => boolean)[]): ISubscriptionDefinition; + context(theContext: any): ISubscriptionDefinition; + debounce(interval: number): ISubscriptionDefinition; + defer(): ISubscriptionDefinition; + delay(waitTime: number): ISubscriptionDefinition; + disposeAfter(maxCalls: number): ISubscriptionDefinition; + distinct(): ISubscriptionDefinition; + distinctUntilChanged(): ISubscriptionDefinition; + logError(): ISubscriptionDefinition; + once(): ISubscriptionDefinition; + throttle(interval: number): ISubscriptionDefinition; + subscribe(callback: ICallback): ISubscriptionDefinition; unsubscribe(): void; } -interface IEnvelope { +interface IEnvelope { topic: string; - data?: any; + data?: T; /*Uses DEFAULT_CHANNEL if no channel is provided*/ channel?: string; @@ -53,10 +53,10 @@ interface IEnvelope { } -interface IChannelDefinition { - subscribe(topic: string, callback: ICallback): ISubscriptionDefinition; +interface IChannelDefinition { + subscribe(topic: string, callback: ICallback): ISubscriptionDefinition; - publish(topic: string, data?: any): void; + publish(topic: string, data?: T): void; channel: string; } @@ -73,24 +73,24 @@ interface IDestinationArg { interface IPostal { subscriptions: {}; - wiretaps: ICallback[]; + wiretaps: ICallback[]; - addWireTap(callback: ICallback): () => void; + addWireTap(callback: ICallback): () => void; - channel(name?: string): IChannelDefinition; + channel(name?: string): IChannelDefinition; - getSubscribersFor(): ISubscriptionDefinition[]; - getSubscribersFor(options: {channel?: string, topic?: string, context?: any}): ISubscriptionDefinition[]; - getSubscribersFor(predicateFn: (sub: ISubscriptionDefinition) => boolean): ISubscriptionDefinition[]; + getSubscribersFor(): ISubscriptionDefinition[]; + getSubscribersFor(options: {channel?: string, topic?: string, context?: any}): ISubscriptionDefinition[]; + getSubscribersFor(predicateFn: (sub: ISubscriptionDefinition) => boolean): ISubscriptionDefinition[]; linkChannels(source: ISourceArg | ISourceArg[], destination: IDestinationArg | IDestinationArg[]): void; - publish(envelope: IEnvelope): void; + publish(envelope: IEnvelope): void; reset(): void; - subscribe(options: {channel?: string, topic: string, callback: ICallback}): ISubscriptionDefinition; - unsubscribe(sub: ISubscriptionDefinition): void; + subscribe(options: {channel?: string, topic: string, callback: ICallback}): ISubscriptionDefinition; + unsubscribe(sub: ISubscriptionDefinition): void; unsubscribeFor(): void; unsubscribeFor(options: {channel?: string, topic?: string, context?: any}): void; From 964d8d647001b5277f5a0309fdade125e224f829 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20Corbi=C3=A8re?= Date: Thu, 20 Aug 2015 11:40:54 +0200 Subject: [PATCH 089/173] [gulp-changed] Add type definitions --- gulp-changed/gulp-changed-tests.ts | 19 ++++++++++ gulp-changed/gulp-changed.d.ts | 60 ++++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+) create mode 100644 gulp-changed/gulp-changed-tests.ts create mode 100644 gulp-changed/gulp-changed.d.ts diff --git a/gulp-changed/gulp-changed-tests.ts b/gulp-changed/gulp-changed-tests.ts new file mode 100644 index 000000000..ae6104eed --- /dev/null +++ b/gulp-changed/gulp-changed-tests.ts @@ -0,0 +1,19 @@ +/// +/// +/// + +import * as gulp from "gulp"; +import changed = require("gulp-changed"); +import minifyHtml = require("gulp-minify-html"); + +// Without options +gulp.src("*.html") + .pipe(changed("build")) + .pipe(minifyHtml()) + .pipe(gulp.dest("build")); + +// Without some options +gulp.src("*.html") + .pipe(changed("build", { hasChanged: changed.compareSha1Digest })) + .pipe(minifyHtml()) + .pipe(gulp.dest("build")); diff --git a/gulp-changed/gulp-changed.d.ts b/gulp-changed/gulp-changed.d.ts new file mode 100644 index 000000000..f2a3e0d64 --- /dev/null +++ b/gulp-changed/gulp-changed.d.ts @@ -0,0 +1,60 @@ +// Type definitions for gulp-changed +// Project: https://github.com/sindresorhus/gulp-changed +// Definitions by: Thomas Corbière +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare module "gulp-changed" +{ + import { Transform } from "stream"; + import File = require("vinyl"); + + interface IComparator + { + /** + * @param stream Should be used to queue sourceFile if it passes some comparison + * @param callback Should be called when done + * @param sourceFile File to operate on + * @param destPath Destination for sourceFile as an absolute path + */ + (stream: Transform, callback: Function, sourceFile: File, destPath: string): void; + } + + interface IDestination + { + (file: string|Buffer): string; + } + + interface IOptions + { + /** + * The working directory the folder is relative to. + * @default process.cwd() + */ + cwd?: string; + + /** + * Extension of the destination files. + */ + extension?: string; + + /** + * Function that determines whether the source file is different from the destination file. + * @default changed.compareLastModifiedTime + */ + hasChanged?: IComparator; + } + + interface IGulpChanged + { + (destination: string|IDestination, options?: IOptions): NodeJS.ReadWriteStream; + + compareLastModifiedTime: IComparator; + compareSha1Digest: IComparator; + } + + const changed: IGulpChanged; + export = changed; +} From a0357a3bb1934ef912b73d2042c7cd9abc5b30ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20Corbi=C3=A8re?= Date: Thu, 20 Aug 2015 12:28:13 +0200 Subject: [PATCH 090/173] [gulp-newer] Add type definitions --- gulp-newer/gulp-newer-tests.ts | 17 +++++++++++++ gulp-newer/gulp-newer.d.ts | 46 ++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 gulp-newer/gulp-newer-tests.ts create mode 100644 gulp-newer/gulp-newer.d.ts diff --git a/gulp-newer/gulp-newer-tests.ts b/gulp-newer/gulp-newer-tests.ts new file mode 100644 index 000000000..43f0c55cc --- /dev/null +++ b/gulp-newer/gulp-newer-tests.ts @@ -0,0 +1,17 @@ +/// +/// +/// + +import * as gulp from "gulp"; +import newer = require("gulp-newer"); +import minifyHtml = require("gulp-minify-html"); + +gulp.src("*.html") + .pipe(newer("build")) + .pipe(minifyHtml()) + .pipe(gulp.dest("build")); + +gulp.src("*.html") + .pipe(newer({ dest: "build" })) + .pipe(minifyHtml()) + .pipe(gulp.dest("build")); diff --git a/gulp-newer/gulp-newer.d.ts b/gulp-newer/gulp-newer.d.ts new file mode 100644 index 000000000..ca4fdc9a1 --- /dev/null +++ b/gulp-newer/gulp-newer.d.ts @@ -0,0 +1,46 @@ +// Type definitions for gulp-newer +// Project: https://github.com/tschaub/gulp-newer +// Definitions by: Thomas Corbière +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "gulp-newer" +{ + interface IOptions + { + /** + * Path to destination directory or file. + */ + dest: string; + + /** + * Source files will be matched to destination files with the provided extension. + */ + ext?: string; + + /** + * Map relative source paths to relative destination paths. + */ + map?: (relativePath: string) => string; + } + + interface IGulpNewer + { + /** + * Create a transform stream that passes through files whose modification time + * is more recent than the corresponding destination file's modification time. + * @param dest Path to destination directory or file. + */ + (dest: string): NodeJS.ReadWriteStream; + + /** + * Create a transform stream that passes through files whose modification time + * is more recent than the corresponding destination file's modification time. + */ + (options: IOptions): NodeJS.ReadWriteStream; + } + + const newer: IGulpNewer; + export = newer; +} From 829c564bf1e86a14d35ebaebe78384c281e632d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20Corbi=C3=A8re?= Date: Thu, 20 Aug 2015 12:37:27 +0200 Subject: [PATCH 091/173] [gulp-changed] Fix typo --- gulp-changed/gulp-changed-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gulp-changed/gulp-changed-tests.ts b/gulp-changed/gulp-changed-tests.ts index ae6104eed..dae92e0fd 100644 --- a/gulp-changed/gulp-changed-tests.ts +++ b/gulp-changed/gulp-changed-tests.ts @@ -12,7 +12,7 @@ gulp.src("*.html") .pipe(minifyHtml()) .pipe(gulp.dest("build")); -// Without some options +// With some options gulp.src("*.html") .pipe(changed("build", { hasChanged: changed.compareSha1Digest })) .pipe(minifyHtml()) From 5b010131f16dc0ae1b6ec6cc3cb36a95419ca0db Mon Sep 17 00:00:00 2001 From: Marcin Porebski Date: Thu, 20 Aug 2015 14:17:47 +0200 Subject: [PATCH 092/173] typo fix --- string_score/string_score.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/string_score/string_score.d.ts b/string_score/string_score.d.ts index 2d901ba39..5e3ee05d5 100644 --- a/string_score/string_score.d.ts +++ b/string_score/string_score.d.ts @@ -1,4 +1,4 @@ -// Type definitions for url-template 0.1.22 +// Type definitions for string_score 0.1.22 // Project: https://github.com/joshaven/string_score // Definitions by: Marcin Porębski // Definitions: https://github.com/borisyankov/DefinitelyTyped From 8a1f9f526d462bb6bbbb2603e3bcf1c4e4c818cc Mon Sep 17 00:00:00 2001 From: jbghoul Date: Thu, 20 Aug 2015 15:58:08 +0200 Subject: [PATCH 093/173] HighchartsDateTimeFormats: add missing millisecond --- highcharts/highcharts.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/highcharts/highcharts.d.ts b/highcharts/highcharts.d.ts index ee3a2ce4c..483e37fca 100644 --- a/highcharts/highcharts.d.ts +++ b/highcharts/highcharts.d.ts @@ -13,6 +13,7 @@ interface HighchartsPosition { } interface HighchartsDateTimeFormats { + millisecond?: string; // '%H:%M:%S.%L' second?: string; // '%H:%M:%S' minute?: string; // '%H:%M' hour?: string; // '%H:%M' From f62efc0d21f9029e84bf1cd9c07ec9c17a3c5690 Mon Sep 17 00:00:00 2001 From: Joe Skeen Date: Thu, 20 Aug 2015 08:21:50 -0600 Subject: [PATCH 094/173] Added overloads to gul-if and added documentation --- gulp-if/gulp-if-tests.ts | 24 ++++++++++++---- gulp-if/gulp-if.d.ts | 62 ++++++++++++++++++++++++++++++++++++---- 2 files changed, 74 insertions(+), 12 deletions(-) diff --git a/gulp-if/gulp-if-tests.ts b/gulp-if/gulp-if-tests.ts index e1ba54c91..6edb3bc13 100644 --- a/gulp-if/gulp-if-tests.ts +++ b/gulp-if/gulp-if-tests.ts @@ -1,10 +1,22 @@ /// /// -import gulp = require("gulp"); -import _if = require("gulp-if"); +import gulp = require('gulp'); +import _if = require('gulp-if'); -gulp.src("test.css") - .pipe(_if(true, gulp.src("test.css"))); +gulp.src('test.css') + .pipe(_if(true, gulp.src('test.css'))); -gulp.src("test.css") - .pipe(_if(false, gulp.src("test.css"), gulp.src("test.css"))); \ No newline at end of file +gulp.src('test.css') + .pipe(_if(false, gulp.src('test.css'), gulp.src('test.css'))); + +gulp.src('test.css') + .pipe(_if({isDirectory: true}, gulp.src('test.css'))); + +gulp.src('test.css') + .pipe(_if({isFile: true}, gulp.src('test.css'))); + +gulp.src('test.css') + .pipe(_if(file => true, gulp.src('test.css'))); + +gulp.src('test.css') + .pipe(_if(/.*?\.css/, gulp.src('test.css'))); \ No newline at end of file diff --git a/gulp-if/gulp-if.d.ts b/gulp-if/gulp-if.d.ts index 474682b9d..9eab80f8b 100644 --- a/gulp-if/gulp-if.d.ts +++ b/gulp-if/gulp-if.d.ts @@ -1,14 +1,64 @@ // Type definitions for gulp-if // Project: https://github.com/robrich/gulp-if -// Definitions by: Asana +// Definitions by: Asana , Joe Skeen // Definitions: https://github.com/borisyankov/DefinitelyTyped /// +/// -declare module "gulp-if" { - function gulpIf( - condition: boolean, - stream: NodeJS.ReadWriteStream, - elseStream?: NodeJS.ReadWriteStream): NodeJS.ReadWriteStream; +declare module 'gulp-if' { + import fs = require('fs'); + import vinyl = require('vinyl'); + + interface GulpIf { + /** + * gulp-if will pipe data to stream whenever condition is truthy. + * If condition is falsey and elseStream is passed, data will pipe to elseStream + * After data is piped to stream or elseStream or neither, data is piped down-stream. + * + * @param condition whether input should be piped to stream + * @param stream the stream to pipe to if condition is true + * @param elseStream (optional) the stream to pipe to if condition is false + */ + (condition: boolean, stream: NodeJS.ReadWriteStream, elseStream?: NodeJS.ReadWriteStream): NodeJS.ReadWriteStream; + /** + * gulp-if will pipe data to stream whenever condition is truthy. + * If condition is falsey and elseStream is passed, data will pipe to elseStream + * After data is piped to stream or elseStream or neither, data is piped down-stream. + * + * @param condition a Node Stat filter condition to be executed on the vinyl file's Stats object + * @param stream the stream to pipe to if condition is true + * @param elseStream (optional) the stream to pipe to if condition is false + */ + (condition: StatFilterCondition, stream: NodeJS.ReadWriteStream, elseStream?: NodeJS.ReadWriteStream): NodeJS.ReadWriteStream; + /** + * gulp-if will pipe data to stream whenever condition is truthy. + * If condition is falsey and elseStream is passed, data will pipe to elseStream + * After data is piped to stream or elseStream or neither, data is piped down-stream. + * + * @param condition a function taking a vinyl file and returning a boolean + * @param stream the stream to pipe to if condition is true + * @param elseStream (optional) the stream to pipe to if condition is false + */ + (condition: (fs: vinyl) => boolean, stream: NodeJS.ReadWriteStream, elseStream?: NodeJS.ReadWriteStream): NodeJS.ReadWriteStream; + /** + * gulp-if will pipe data to stream whenever condition is truthy. + * If condition is falsey and elseStream is passed, data will pipe to elseStream + * After data is piped to stream or elseStream or neither, data is piped down-stream. + * + * @param condition a RegularExpression that works on the file.path + * @param stream the stream to pipe to if condition is true + * @param elseStream (optional) the stream to pipe to if condition is false + */ + (condition: RegExp, stream: NodeJS.ReadWriteStream, elseStream?: NodeJS.ReadWriteStream): NodeJS.ReadWriteStream; + } + + interface StatFilterCondition { + isDirectory?: boolean; + isFile?: boolean; + } + + var gulpIf: GulpIf; + export = gulpIf; } \ No newline at end of file From 673be8a16912c0f95dd998e1ffcadb17cd7d5328 Mon Sep 17 00:00:00 2001 From: Aya Morisawa Date: Thu, 20 Aug 2015 23:52:15 +0900 Subject: [PATCH 095/173] Fix return value of transform in request-promise.d.ts The return value of `transform` function is not necessarily `number`. --- request-promise/request-promise.d.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/request-promise/request-promise.d.ts b/request-promise/request-promise.d.ts index 9cee53eee..246f1e5d9 100644 --- a/request-promise/request-promise.d.ts +++ b/request-promise/request-promise.d.ts @@ -3,6 +3,8 @@ // Definitions by: Christopher Glantschnig // Definitions: https://github.com/borisyankov/DefinitelyTyped +// Change [0]: 2015/08/20 - Aya Morisawa + /// /// /// @@ -22,7 +24,7 @@ declare module 'request-promise' { module RequestPromiseAPI { export interface Options extends request.Options { simple?: boolean; - transform?: (body: any, response: http.IncomingMessage) => number; + transform?: (body: any, response: http.IncomingMessage) => any; resolveWithFullResponse?: boolean; } } From b49efc4030dd0eed7929c738f316d3a541c185ef Mon Sep 17 00:00:00 2001 From: rhysd Date: Fri, 21 Aug 2015 00:55:57 +0900 Subject: [PATCH 096/173] Added definitions for auto-launch package Project page is here. https://github.com/Teamwork/node-auto-launch > Launch node-webkit apps at login (mac & windows) --- auto-launch/auto-launch-tests.ts | 17 +++++++++++++ auto-launch/auto-launch.d.ts | 41 ++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 auto-launch/auto-launch-tests.ts create mode 100644 auto-launch/auto-launch.d.ts diff --git a/auto-launch/auto-launch-tests.ts b/auto-launch/auto-launch-tests.ts new file mode 100644 index 000000000..735985624 --- /dev/null +++ b/auto-launch/auto-launch-tests.ts @@ -0,0 +1,17 @@ +/// + +import AutoLaunch = require('auto-launch'); + +var a1 = new AutoLaunch({ + name: 'Foo', +}); + +var a2 = new AutoLaunch({ + name: 'Foo', + path: '/Applications/Foo.app', + isHidden: true, +}); + +a1.enable(); +a2.disable(); +var enabled: boolean = a1.isEnabled(); diff --git a/auto-launch/auto-launch.d.ts b/auto-launch/auto-launch.d.ts new file mode 100644 index 000000000..c208d10fd --- /dev/null +++ b/auto-launch/auto-launch.d.ts @@ -0,0 +1,41 @@ +// Type definitions for auto-launch 0.1.18 +// Project: https://github.com/Teamwork/node-auto-launch +// Definitions by: rhysd +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface AutoLaunchOption { + /** + * Application name. + */ + name: string; + /** + * Hidden on launch or not. Default is false. + */ + isHidden?: boolean; + /** + * Path to application directory. + * Default is process.execPath. + */ + path?: string; +} + +declare class AutoLaunch { + constructor(opts: AutoLaunchOption); + /** + * Enables to launch at start up + */ + enable(callback?: (err: Error) => void): void; + /** + * Disables to launch at start up + */ + disable(callback?: (err: Error) => void): void; + /** + * Returns if auto start up is enabled + */ + isEnabled(callback?: (err: Error) => void): boolean; +} + +declare module "auto-launch" { + var al: typeof AutoLaunch; + export = al; +} From e7b8c8bc7f784811a2d7dd57339686f60db82796 Mon Sep 17 00:00:00 2001 From: mfrantz Date: Thu, 6 Aug 2015 13:06:30 -0700 Subject: [PATCH 097/173] semaphore v1.0.3 --- semaphore/semaphore-tests.ts | 14 ++++++++++++++ semaphore/semaphore.d.ts | 26 ++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 semaphore/semaphore-tests.ts create mode 100644 semaphore/semaphore.d.ts diff --git a/semaphore/semaphore-tests.ts b/semaphore/semaphore-tests.ts new file mode 100644 index 000000000..d6df36030 --- /dev/null +++ b/semaphore/semaphore-tests.ts @@ -0,0 +1,14 @@ +/// + +import semaphore = require('semaphore'); + +var sem: semaphore.Semaphore = semaphore(10); + +function task() { + console.log('My task'); + sem.leave(); +} + +sem.take(task); +sem.take(2, task); +sem.leave(2); diff --git a/semaphore/semaphore.d.ts b/semaphore/semaphore.d.ts new file mode 100644 index 000000000..0a2855b82 --- /dev/null +++ b/semaphore/semaphore.d.ts @@ -0,0 +1,26 @@ +// Type definitions for semaphore v1.0.3 +// Project: https://github.com/abrkn/semaphore.js +// Definitions by: Matt Frantz +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module 'semaphore' { + + function semaphore(capacity?: number): semaphore.Semaphore; + + module semaphore { + + interface Task { + (): void; + } + + interface Semaphore { + capacity: number; + + take(task: Task): void; + take(n: number, task: Task): void; + + leave(n?: number): void; + } + } + export = semaphore; +} From c7a19cd5342b9cd64108f4ea5e8f709601d0feae Mon Sep 17 00:00:00 2001 From: Mark Nadig Date: Thu, 20 Aug 2015 12:41:58 -0600 Subject: [PATCH 098/173] angular-ui-scroll typings and tests --- angular-ui-scroll/angular-ui-scroll-tests.ts | 93 ++++++++++++++++++++ angular-ui-scroll/angular-ui-scroll.d.ts | 85 ++++++++++++++++++ 2 files changed, 178 insertions(+) create mode 100644 angular-ui-scroll/angular-ui-scroll-tests.ts create mode 100644 angular-ui-scroll/angular-ui-scroll.d.ts diff --git a/angular-ui-scroll/angular-ui-scroll-tests.ts b/angular-ui-scroll/angular-ui-scroll-tests.ts new file mode 100644 index 000000000..1a85dd6b5 --- /dev/null +++ b/angular-ui-scroll/angular-ui-scroll-tests.ts @@ -0,0 +1,93 @@ +/// +var myApp = angular.module('application', ['ui.scroll', 'ui.scroll.jqlite']); + +module application { + interface IItem { + id: number; + content: string; + } + + class DatasourceTest implements ng.ui.IScrollDatasource { + get(index: number, count: number, success: (results: IItem[]) => void): void { + var ret = new Array(); + for (var i=0; i < count; i++) { + ret.push({id: i, content: 'item ' + i.toString()}); + } + success(ret); + } + } + + function factory(): any { + return DatasourceTest; + } + + myApp.factory('DatasourceTest', factory); + + // demo/examples/adapter + myApp.controller('mainController', ['$scope', 'DatasourceTest', function($scope: ng.IScope, datasource: DatasourceTest) { + var firstListAdapter: ng.ui.IScrollAdapter, secondListAdapter: ng.ui.IScrollAdapter; + $scope['datasource'] = datasource; + + $scope['updateList1'] = (): void => { + firstListAdapter.applyUpdates( (item: IItem, scope: ng.IRepeatScope) => { + return item.content += ' *'; + }) + }; + + $scope['removeFromList1'] = (): void => { + firstListAdapter.applyUpdates( (item: IItem, scope: ng.IRepeatScope) => { + if (scope.$index % 2 === 0) { + return [] + } + }) + }; + + var idList1: number = 1000; + $scope['addToList1'] = (): void => { + firstListAdapter.applyUpdates((item: IItem, scope: ng.IRepeatScope) => { + var newItem: IItem; + newItem = void 0; + if (scope.$index === 2) { + newItem = { + id: idList1, + content: 'a new one #' + idList1 + }; + idList1++; + return [item, newItem]; + } + }); + }; + + $scope['updateList2'] = (): void => { + secondListAdapter.applyUpdates((item: IItem, scope: ng.IRepeatScope) => { + return item.content += ' *'; + }); + }; + + $scope['removeFromList2'] = (): void => { + secondListAdapter.applyUpdates((item: IItem, scope: ng.IRepeatScope) => { + if (scope.$index % 2 !== 0) { + return []; + } + }); + }; + + var idList2: number = 2000; + $scope['addToList2'] = (): void => { + secondListAdapter.applyUpdates((item: IItem, scope: ng.IRepeatScope) => { + var newItem: IItem; + newItem = void 0; + if (scope.$index === 4) { + newItem = { + id: idList2, + content: 'a new one #' + idList1 + }; + idList2++; + return [item, newItem]; + } + }); + }; + + }]); +} + diff --git a/angular-ui-scroll/angular-ui-scroll.d.ts b/angular-ui-scroll/angular-ui-scroll.d.ts new file mode 100644 index 000000000..08ed233c0 --- /dev/null +++ b/angular-ui-scroll/angular-ui-scroll.d.ts @@ -0,0 +1,85 @@ +// Type definitions for Angular JS 1.3.1+ (ui.scroll module) +// Project: https://github.com/angular-ui/ui-scroll +// Definitions by: Mark Nadig +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module angular.ui { + interface IScrollDatasource { + /** + * The datasource object implements methods and properties to be used by the directive to access the data + * + * @param index indicates the first data row requested + * + * @param count indicates number of data rows requested + * + * @param success function to call when the data are retrieved. The implementation of the service has to call + * this function when the data are retrieved and pass it an array of the items retrieved. If no items are + * retrieved, an empty array has to be passed. + * + * Important: Make sure to respect the index and count parameters of the request. The array passed to the + * success method should have exactly count elements unless it hit eof/bof + */ + get(index: number, count: number, success: (results: Array) => any): void; + } + + interface IScrollAdapter { + /** + * a boolean value indicating whether there are any pending load requests. + */ + isLoading: boolean; + /** + * a reference to the item currently in the topmost visible position. + */ + topVisible: any; + /** + * a reference to the DOM element currently in the topmost visible position. + */ + topVisibleElement: ng.IAugmentedJQueryStatic; + /** + * a reference to the scope created for the item currently in the topmost visible position. + */ + topVisibleScope: ng.IRepeatScope; + /** + * calling this method reinitializes and reloads the scroller content. + */ + reload(): void; + /** + * Replaces the item in the buffer at the given index with the new items. + * + * @param index provides position of the item to be affected in the dataset (not in the buffer). If the item with + * the given index currently is not in the buffer no updates will be applied. $index property of the item $scope + * can be used to access the index value for a given item + * + * @param newItems is an array of items to replace the affected item. If the array is empty ([]) the item will + * be deleted, otherwise the items in the array replace the item. If the newItem array contains the old item, + * the old item stays in place. + */ + applyUpdates(index: number, newItems: any[]): void; + /** + * Replaces the item in the buffer at the given index with the new items. + * + * @param updater is a function to be applied to every item currently in the buffer. The function will receive + * 3 parameters: item, scope, and element. Here item is the item to be affected, scope is the item $scope, and + * element is the html element for the item. The return value of the function should be an array of items. + * Similarly to the newItem parameter (see above), if the array is empty([]), the item is deleted, otherwise + * the item is replaced by the items in the array. If the return value is not an array, the item remains + * unaffected, unless some updates were made to the item in the updater function. This can be thought of as + * in place update. + */ + applyUpdates(updater: (item: any, scope: ng.IRepeatScope) => any): void; + /** + * Adds new items after the last item in the buffer + * + * @param newItems provides an array of items to be appended. + */ + append(newItems: any[]): void; + /** + * Adds new items before the first item in the buffer + * + * @param newItems provides an array of items to be prepended. + */ + prepend(newItems: any[]): void; + } +} From e48415a72df4eec7a26062065a394f97218c77d9 Mon Sep 17 00:00:00 2001 From: John Palgut Date: Thu, 20 Aug 2015 15:23:11 -0500 Subject: [PATCH 099/173] Add a type definition for HTTPOptions The method [Parse.Cloud.httpRequest](https://parse.com/docs/js/api/symbols/Parse.Cloud.html#.httpRequest) takes a [HTTPOptions](https://parse.com/docs/js/api/symbols/Parse.Cloud.HTTPOptions.html) options object and not a ParseDefaultOptions object. I've included an initial interface definition for HTTPOptions and updated the httpRequest method definition to match --- parse/parse.d.ts | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/parse/parse.d.ts b/parse/parse.d.ts index cb4fa8b2b..9322188af 100644 --- a/parse/parse.d.ts +++ b/parse/parse.d.ts @@ -23,6 +23,17 @@ declare module Parse { useMasterKey?: boolean; } + interface HTTPOptions { + url: string; + body?: any; + error?: Function; + followRedirects?: boolean; + headers?: any; + method?: string; + params?: any; + success?: Function; + } + interface CollectionOptions { model?: Object; query?: Query; @@ -796,7 +807,7 @@ declare module Parse { function beforeDelete(arg1: any, func?: (request: BeforeDeleteRequest, response: BeforeDeleteResponse) => void): void; function beforeSave(arg1: any, func?: (request: BeforeSaveRequest, response: BeforeSaveResponse) => void): void; function define(name: string, func?: (request: FunctionRequest, response: FunctionResponse) => void): void; - function httpRequest(options: ParseDefaultOptions): Promise; + function httpRequest(options: HTTPOptions): Promise; function job(name: string, func?: (request: JobRequest, status: JobStatus) => void): HttpResponse; function run(name: string, data?: any, options?: ParseDefaultOptions): Promise; function useMasterKey(): void; From cd5653f5a430db1875b33e7e0824c175e5a439aa Mon Sep 17 00:00:00 2001 From: Jordan Potter Date: Thu, 20 Aug 2015 16:29:39 -0700 Subject: [PATCH 100/173] Correct history.js return type annotations --- history/history.d.ts | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/history/history.d.ts b/history/history.d.ts index 07a31d011..f6a6bf407 100644 --- a/history/history.d.ts +++ b/history/history.d.ts @@ -5,23 +5,23 @@ interface HistoryAdapter { - bind(element: any, event: string, callback: () => void); - trigger(element: any, event: string); - onDomLoad(callback: () => void); + bind(element: any, event: string, callback: () => void): void; + trigger(element: any, event: string): void; + onDomLoad(callback: () => void): void; } -// Since History is defined in lib.d.ts as well +// Since History is defined in lib.d.ts as well // the name for our interfaces was chosen to be Historyjs // However at runtime you would need to do -// https://github.com/borisyankov/DefinitelyTyped/issues/277 +// https://github.com/borisyankov/DefinitelyTyped/issues/277 // var Historyjs: Historyjs = History; interface Historyjs { enabled: boolean; - pushState(data: any, title: string, url: string); - replaceState(data: any, title: string, url: string); + pushState(data: any, title: string, url: string): void; + replaceState(data: any, title: string, url: string): void; getState(): HistoryState; getStateByIndex(index: number): HistoryState; getCurrentIndex(): number; @@ -58,4 +58,4 @@ interface HistoryOptions { delayInit?: number; -} \ No newline at end of file +} From a0143072d67e316c8d2f1ceac4ab246e156d7c92 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Fri, 21 Aug 2015 06:07:26 +0500 Subject: [PATCH 101/173] lodash: changed _.trunc() method --- lodash/lodash-tests.ts | 6 ++++++ lodash/lodash.d.ts | 27 +++++++++++++++++++++++++-- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 2cbec6853..a63e308ac 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1706,11 +1706,17 @@ result = _.trimRight('-_-abc-_-', '_-'); result = _('-_-abc-_-').trimRight(); result = _('-_-abc-_-').trimRight('_-'); +// _.trunc result = _.trunc('hi-diddly-ho there, neighborino'); result = _.trunc('hi-diddly-ho there, neighborino', 24); result = _.trunc('hi-diddly-ho there, neighborino', { 'length': 24, 'separator': ' ' }); result = _.trunc('hi-diddly-ho there, neighborino', { 'length': 24, 'separator': /,? +/ }); result = _.trunc('hi-diddly-ho there, neighborino', { 'omission': ' […]' }); +result = _('hi-diddly-ho there, neighborino').trunc(); +result = _('hi-diddly-ho there, neighborino').trunc(24); +result = _('hi-diddly-ho there, neighborino').trunc({ 'length': 24, 'separator': ' ' }); +result = _('hi-diddly-ho there, neighborino').trunc({ 'length': 24, 'separator': /,? +/ }); +result = _('hi-diddly-ho there, neighborino').trunc({ 'omission': ' […]' }); // _.unescape result = _.unescape('fred, barney, & pebbles'); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index c088f5459..e9248577a 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -7587,9 +7587,32 @@ declare module _ { trimRight(chars?: string): string; } + //_.trunc + interface TruncOptions { + /** The maximum string length. */ + length?: number; + /** The string to indicate text is omitted. */ + omission?: string; + /** The separator pattern to truncate to. */ + separator?: string|RegExp; + } + interface LoDashStatic { - trunc(str?: string, len?: number): string; - trunc(str?: string, options?: { length?: number; omission?: string; separator?: string|RegExp }): string; + /** + * Truncates string if it’s longer than the given maximum string length. The last characters of the truncated + * string are replaced with the omission string which defaults to "…". + * @param string The string to truncate. + * @param options The options object or maximum string length. + * @return Returns the truncated string. + */ + trunc(string?: string, options?: TruncOptions|number): string; + } + + interface LoDashWrapper { + /** + * @see _.trunc + */ + trunc(options?: TruncOptions|number): string; } //_.unescape From 7b4ab5384c58f9508d4a6d877dc64b5e3a51fee0 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Fri, 21 Aug 2015 07:12:25 +0500 Subject: [PATCH 102/173] lodash: changed _.clone() and _.cloneDeep() methods --- lodash/lodash-tests.ts | 120 +++++++++++++++++++++++++++-------------- lodash/lodash.d.ts | 112 +++++++++++++++++++++++++++++--------- 2 files changed, 168 insertions(+), 64 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 2cbec6853..ef2d5e457 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1091,41 +1091,89 @@ helloWrap2(); * Lang * ********/ -// _.cloneDeep -interface TestCloneDeepFn { +// _.clone +interface TestCloneCustomizerFn { (value: any): any; } -var testCloneDeepFn: TestCloneDeepFn; -result = _.cloneDeep(1); -result = _.cloneDeep(1, testCloneDeepFn); -result = _.cloneDeep(1, testCloneDeepFn, any); -result = _.cloneDeep('a'); -result = _.cloneDeep('a', testCloneDeepFn); -result = _.cloneDeep('a', testCloneDeepFn, any); -result = _.cloneDeep(true); -result = _.cloneDeep(true, testCloneDeepFn); -result = _.cloneDeep(true, testCloneDeepFn, any); -result = _.cloneDeep([1, 2]); -result = _.cloneDeep([1, 2], testCloneDeepFn); -result = _.cloneDeep([1, 2], testCloneDeepFn, any); -result = <{a: {b: number;}}>_.cloneDeep<{a: {b: number;}}>({a: {b: 2}}); -result = <{a: {b: number;}}>_.cloneDeep<{a: {b: number;}}>({a: {b: 2}}, testCloneDeepFn); -result = <{a: {b: number;}}>_.cloneDeep<{a: {b: number;}}>({a: {b: 2}}, testCloneDeepFn, any); -result = _(1).cloneDeep(); -result = _(1).cloneDeep(testCloneDeepFn); -result = _(1).cloneDeep(testCloneDeepFn, any); -result = _('a').cloneDeep(); -result = _('a').cloneDeep(testCloneDeepFn); -result = _('a').cloneDeep(testCloneDeepFn, any); -result = _(true).cloneDeep(); -result = _(true).cloneDeep(testCloneDeepFn); -result = _(true).cloneDeep(testCloneDeepFn, any); -result = _([1, 2]).cloneDeep(); -result = _([1, 2]).cloneDeep(testCloneDeepFn); -result = _([1, 2]).cloneDeep(testCloneDeepFn, any); -result = <{a: {b: number;}}>_({a: {b: 2}}).cloneDeep(); -result = <{a: {b: number;}}>_({a: {b: 2}}).cloneDeep(testCloneDeepFn); -result = <{a: {b: number;}}>_({a: {b: 2}}).cloneDeep(testCloneDeepFn, any); +var testCloneCustomizerFn: TestCloneCustomizerFn; +{ + let result: number; + result = _.clone(42); + result = _.clone(42, false); + result = _.clone(42, false, testCloneCustomizerFn); + result = _.clone(42, false, testCloneCustomizerFn, any); + result = _.clone(42, testCloneCustomizerFn); + result = _.clone(42, testCloneCustomizerFn, any); + result = _(42).clone(); + result = _(42).clone(false); + result = _(42).clone(false, testCloneCustomizerFn); + result = _(42).clone(false, testCloneCustomizerFn, any); + result = _(42).clone(testCloneCustomizerFn); + result = _(42).clone(testCloneCustomizerFn, any); +} +{ + let result: string[]; + result = _.clone([]); + result = _.clone([], false); + result = _.clone([], false, testCloneCustomizerFn); + result = _.clone([], false, testCloneCustomizerFn, any); + result = _.clone([], testCloneCustomizerFn); + result = _.clone([], testCloneCustomizerFn, any); + result = _([]).clone(); + result = _([]).clone(false); + result = _([]).clone(false, testCloneCustomizerFn); + result = _([]).clone(false, testCloneCustomizerFn, any); + result = _([]).clone(testCloneCustomizerFn); + result = _([]).clone(testCloneCustomizerFn, any); +} +{ + let result: {a: {b: number;}}; + result = _.clone<{a: {b: number;}}>({a: {b: 2}}); + result = _.clone<{a: {b: number;}}>({a: {b: 2}}, false); + result = _.clone<{a: {b: number;}}>({a: {b: 2}}, false, testCloneCustomizerFn); + result = _.clone<{a: {b: number;}}>({a: {b: 2}}, false, testCloneCustomizerFn, any); + result = _.clone<{a: {b: number;}}>({a: {b: 2}}, testCloneCustomizerFn); + result = _.clone<{a: {b: number;}}>({a: {b: 2}}, testCloneCustomizerFn, any); + result = _({a: {b: 2}}).clone(); + result = _({a: {b: 2}}).clone(false); + result = _({a: {b: 2}}).clone(false, testCloneCustomizerFn); + result = _({a: {b: 2}}).clone(false, testCloneCustomizerFn, any); + result = _({a: {b: 2}}).clone(testCloneCustomizerFn); + result = _({a: {b: 2}}).clone(testCloneCustomizerFn, any); +} + +// _.cloneDeep +interface TestCloneDeepCustomizerFn { + (value: any): any; +} +var testCloneDeepCustomizerFn: TestCloneDeepCustomizerFn; +{ + let result: number; + result = _.cloneDeep(42); + result = _.cloneDeep(42, testCloneDeepCustomizerFn); + result = _.cloneDeep(42, testCloneDeepCustomizerFn, any); + result = _(42).cloneDeep(); + result = _(42).cloneDeep(testCloneDeepCustomizerFn); + result = _(42).cloneDeep(testCloneDeepCustomizerFn, any); +} +{ + let result: string[]; + result = _.cloneDeep([]); + result = _.cloneDeep([], testCloneDeepCustomizerFn); + result = _.cloneDeep([], testCloneDeepCustomizerFn, any); + result = _([]).cloneDeep(); + result = _([]).cloneDeep(testCloneDeepCustomizerFn); + result = _([]).cloneDeep(testCloneDeepCustomizerFn, any); +} +{ + let result: {a: {b: number;}}; + result = _.cloneDeep<{a: {b: number;}}>({a: {b: 2}}); + result = _.cloneDeep<{a: {b: number;}}>({a: {b: 2}}, testCloneDeepCustomizerFn); + result = _.cloneDeep<{a: {b: number;}}>({a: {b: 2}}, testCloneDeepCustomizerFn, any); + result = _({a: {b: 2}}).cloneDeep(); + result = _({a: {b: 2}}).cloneDeep(testCloneDeepCustomizerFn); + result = _({a: {b: 2}}).cloneDeep(testCloneDeepCustomizerFn, any); +} // _.gt result = _.gt(1, 2); @@ -1262,12 +1310,6 @@ result = <{}>_(testCreateProto).create(testCreateProps).value(); result = _(testCreateProto).create().value(); result = _(testCreateProto).create(testCreateProps).value(); -result = _.clone(stoogesAges); -result = _.clone(stoogesAges, true); -result = _.clone(stoogesAges, true, function (value) { - return _.isElement(value) ? value.cloneNode(false) : undefined; -}); - interface Food { name: string; type: string; diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index c088f5459..16b39a64d 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -5997,6 +5997,88 @@ declare module _ { * Lang * ********/ + //_.clone + interface LoDashStatic { + /** + * Creates a clone of value. If isDeep is true nested objects are cloned, otherwise they are assigned by + * reference. If customizer is provided it’s invoked to produce the cloned values. If customizer returns + * undefined cloning is handled by the method instead. The customizer is bound to thisArg and invoked with up + * to three argument; (value [, index|key, object]). + * Note: This method is loosely based on the structured clone algorithm. The enumerable properties of arguments + * objects and objects created by constructors other than Object are cloned to plain Object objects. An empty + * object is returned for uncloneable values such as functions, DOM nodes, Maps, Sets, and WeakMaps. + * @param value The value to clone. + * @param isDeep Specify a deep clone. + * @param customizer The function to customize cloning values. + * @param thisArg The this binding of customizer. + * @return Returns the cloned value. + */ + clone( + value: T, + isDeep?: boolean, + customizer?: (value: any) => any, + thisArg?: any): T; + + /** + * @see _.clone + */ + clone( + value: T, + customizer?: (value: any) => any, + thisArg?: any): T; + } + + interface LoDashWrapper { + /** + * @see _.clone + */ + clone( + isDeep?: boolean, + customizer?: (value: any) => any, + thisArg?: any): T; + + /** + * @see _.clone + */ + clone( + customizer?: (value: any) => any, + thisArg?: any): T; + } + + interface LoDashArrayWrapper { + /** + * @see _.clone + */ + clone( + isDeep?: boolean, + customizer?: (value: any) => any, + thisArg?: any): T[]; + + /** + * @see _.clone + */ + clone( + customizer?: (value: any) => any, + thisArg?: any): T[]; + } + + interface LoDashObjectWrapper { + /** + * @see _.clone + */ + clone( + isDeep?: boolean, + customizer?: (value: any) => any, + thisArg?: any): T; + + /** + * @see _.clone + */ + clone( + customizer?: (value: any) => any, + thisArg?: any): T; + } + //_.cloneDeep interface LoDashStatic { /** @@ -6007,13 +6089,13 @@ declare module _ { * objects and objects created by constructors other than Object are cloned to plain Object objects. An empty * object is returned for uncloneable values such as functions, DOM nodes, Maps, Sets, and WeakMaps. * @param value The value to deep clone. - * @param callback The function to customize cloning values. + * @param customizer The function to customize cloning values. * @param thisArg The this binding of customizer. * @return Returns the deep cloned value. */ cloneDeep( value: T, - callback?: (value: any) => any, + customizer?: (value: any) => any, thisArg?: any): T; } @@ -6022,7 +6104,7 @@ declare module _ { * @see _.cloneDeep */ cloneDeep( - callback?: (value: any) => any, + customizer?: (value: any) => any, thisArg?: any): T; } @@ -6031,7 +6113,7 @@ declare module _ { * @see _.cloneDeep */ cloneDeep( - callback?: (value: any) => any, + customizer?: (value: any) => any, thisArg?: any): T[]; } @@ -6040,7 +6122,7 @@ declare module _ { * @see _.cloneDeep */ cloneDeep( - callback?: (value: any) => any, + customizer?: (value: any) => any, thisArg?: any): T; } @@ -6496,26 +6578,6 @@ declare module _ { create(properties?: Object): LoDashObjectWrapper; } - //_.clone - interface LoDashStatic { - /** - * Creates a clone of value. If deep is true nested objects will also be cloned, otherwise - * they will be assigned by reference. If a callback is provided it will be executed to produce - * the cloned values. If the callback returns undefined cloning will be handled by the method - * instead. The callback is bound to thisArg and invoked with one argument; (value). - * @param value The value to clone. - * @param deep Specify a deep clone. - * @param callback The function to customize cloning values. - * @param thisArg The this binding of callback. - * @return The cloned value. - **/ - clone( - value: T, - deep?: boolean, - callback?: (value: any) => any, - thisArg?: any): T; - } - //_.defaults interface LoDashStatic { /** From 3c79b26f0b7fd7b9fdac85c2ecd5fd470c490c67 Mon Sep 17 00:00:00 2001 From: Adam Martin Date: Fri, 21 Aug 2015 12:13:17 +0100 Subject: [PATCH 103/173] Allow for ES6 Import of Restangular --- restangular/restangular.d.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/restangular/restangular.d.ts b/restangular/restangular.d.ts index 0c5f698ca..bce357482 100644 --- a/restangular/restangular.d.ts +++ b/restangular/restangular.d.ts @@ -6,6 +6,13 @@ /// +// Support AMD require (copying angular.d.ts approach) +// allows for import {IRequestConfig} from 'restangular' ES6 approach +declare module 'restangular' { + export = restangular; +} + + declare module restangular { From c88d8c76f5f59da1b1af383cc1daad01331ff17b Mon Sep 17 00:00:00 2001 From: Ritzlgrmft Date: Fri, 21 Aug 2015 13:52:33 +0200 Subject: [PATCH 104/173] Property manufacturer added to Cordova.Device --- cordova/plugins/Device.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/cordova/plugins/Device.d.ts b/cordova/plugins/Device.d.ts index 8365ee70f..f8f0f7ca3 100644 --- a/cordova/plugins/Device.d.ts +++ b/cordova/plugins/Device.d.ts @@ -26,6 +26,8 @@ interface Device { uuid: string; /** Get the operating system version. */ version: string; + /** Get the device's manufacturer. */ + manufacturer: string; } declare var device: Device; \ No newline at end of file From ce9ebf79937f86a674f5425623437ed412c85a69 Mon Sep 17 00:00:00 2001 From: vvakame Date: Fri, 21 Aug 2015 21:08:03 +0900 Subject: [PATCH 105/173] refactor run method, use union types --- react-router/react-router.d.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/react-router/react-router.d.ts b/react-router/react-router.d.ts index 51664b03a..f43f56484 100644 --- a/react-router/react-router.d.ts +++ b/react-router/react-router.d.ts @@ -174,8 +174,7 @@ declare module ReactRouter { function create(options: RouterCreateOption): Router; function run(routes: Route, callback: RouterRunCallback): Router; - function run(routes: Route, location: LocationBase, callback: RouterRunCallback): Router; - function run(routes: Route, location: string, callback: RouterRunCallback): Router; + function run(routes: Route, location: LocationBase | string, callback: RouterRunCallback): Router; // From e0aba55050bb23630d5e09642546224cea65acca Mon Sep 17 00:00:00 2001 From: zenorbi Date: Fri, 21 Aug 2015 14:13:49 +0200 Subject: [PATCH 106/173] Rename apn-test to apn-tests --- apn/{apn-test.ts => apn-tests.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename apn/{apn-test.ts => apn-tests.ts} (100%) diff --git a/apn/apn-test.ts b/apn/apn-tests.ts similarity index 100% rename from apn/apn-test.ts rename to apn/apn-tests.ts From 3c18f330a6bd7864b75e8b6ead8141375fb71729 Mon Sep 17 00:00:00 2001 From: Martijn Schrage Date: Fri, 21 Aug 2015 13:54:18 +0200 Subject: [PATCH 107/173] Add typings & tests for oblo-util-0.6.4 --- oblo-util/oblo-util-tests.ts | 29 +++++++++++++++++++++++++++++ oblo-util/oblo-util.d.ts | 31 +++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 oblo-util/oblo-util-tests.ts create mode 100644 oblo-util/oblo-util.d.ts diff --git a/oblo-util/oblo-util-tests.ts b/oblo-util/oblo-util-tests.ts new file mode 100644 index 000000000..401611ce7 --- /dev/null +++ b/oblo-util/oblo-util-tests.ts @@ -0,0 +1,29 @@ +/// + +util.debug = false; + +util.log('Log message'); + +util.error('Error message'); + +util.clip(0, 100, -15); + +util.square(3); + +util.replicate(10, 'x'); + +util.pad(' ', 10, 'short'); + +util.padZero(4, 247); + +util.addslashes('\\"\''); + +util.showJSON({name: 'Clyde', color: 'orange'}, ' ', 7); + +util.showTime(new Date()); + +util.showDate(new Date()); + +util.readDate('15-10-2004'); + +util.setAttr($('#someElement'), 'attrName', false); diff --git a/oblo-util/oblo-util.d.ts b/oblo-util/oblo-util.d.ts new file mode 100644 index 000000000..431cf36b3 --- /dev/null +++ b/oblo-util/oblo-util.d.ts @@ -0,0 +1,31 @@ +// Type definitions for oblo-util v0.6.4 +// Project: https://github.com/Oblosys/oblo-util +// Definitions by: Martijn Schrage +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +/// + +interface ObloUtilStatic { + debug : boolean; + + log(...args: any[]) : void; + error(...args: any[]) : void; + clip(min : number, max : number, x : number) : number; + square(x : number) : number; + replicate(n : number, x : X) : X[]; + pad(c : string, l : number, str : any) : string; + padZero(l : number, n : number) : string; + addslashes(str : string) : string; + showJSON(json : any, indentStr? : string, maxDepth? : number) : string; + showTime(date : Date) : string; + showDate(date : Date) : string; + readDate(dateStr : string) : Date; + setAttr($elt : JQuery, attrName : string, isSet : boolean) : void; +} + +declare var util: ObloUtilStatic; + +declare module "oblo-util" { + export = util; +} From 712b9068033dc6708f17cb526af2bfc4f4f125f5 Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Fri, 21 Aug 2015 14:35:27 +0100 Subject: [PATCH 108/173] Type definitions and tests for upper-case-first --- upper-case-first/upper-case-first.d.ts | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 upper-case-first/upper-case-first.d.ts diff --git a/upper-case-first/upper-case-first.d.ts b/upper-case-first/upper-case-first.d.ts new file mode 100644 index 000000000..21af3d676 --- /dev/null +++ b/upper-case-first/upper-case-first.d.ts @@ -0,0 +1,9 @@ +// Type definitions for upper-case-first +// Project: https://github.com/blakeembrey/upper-case-first +// Definitions by: Sam Saint-Pettersen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "upper-case-first" { + function upperCaseFirst(string: string): string; + export = upperCaseFirst; +} From 46f889f66674fcfe00787df8bf53696b1799fbd2 Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Fri, 21 Aug 2015 14:36:29 +0100 Subject: [PATCH 109/173] Type definitions and tests for upper-case-first --- upper-case-first/upper-case-first-tests.ts | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 upper-case-first/upper-case-first-tests.ts diff --git a/upper-case-first/upper-case-first-tests.ts b/upper-case-first/upper-case-first-tests.ts new file mode 100644 index 000000000..2ca02dd74 --- /dev/null +++ b/upper-case-first/upper-case-first-tests.ts @@ -0,0 +1,6 @@ +/// + +import upperCaseFirst = require('upper-case-first'); + +console.log(upperCaseFirst(null)); // => "" +console.log(upperCaseFirst('string')); // => "String" From 8a1945e638a64ac9985e558420b9d1d31148b691 Mon Sep 17 00:00:00 2001 From: tkQubo Date: Fri, 21 Aug 2015 04:05:44 +0900 Subject: [PATCH 110/173] Add Orchestrator --- orchestrator/orchestrator-test.ts | 106 ++++++++++++++++++++++++++ orchestrator/orchestrator.d.ts | 122 ++++++++++++++++++++++++++++++ 2 files changed, 228 insertions(+) create mode 100644 orchestrator/orchestrator-test.ts create mode 100644 orchestrator/orchestrator.d.ts diff --git a/orchestrator/orchestrator-test.ts b/orchestrator/orchestrator-test.ts new file mode 100644 index 000000000..af9af745c --- /dev/null +++ b/orchestrator/orchestrator-test.ts @@ -0,0 +1,106 @@ +/// +/// + +'use strict'; + +import Orchestrator from 'orchestrator'; + +var orchestrator = new Orchestrator(); + + +// API: + +// +// orchestrator.add(name[, deps][, function]); +// + +orchestrator.add('thing1', function() { + // do stuff +}); +orchestrator.add('thing2', function() { + // do stuff +}); +orchestrator.add('mytask', ['array', 'of', 'task', 'names'], function() { + // Do stuff +}); +orchestrator.add('thing2', function(callback){ + var err: any = null; + // do stuff + callback(err); +}); + + +var Q = require('q'); + +orchestrator.add('thing3', function(){ + var deferred = Q.defer(); + + // do async stuff + setTimeout(function () { + deferred.resolve(); + }, 1); + + return deferred.promise; +}); + + +//TODO: map-stream currently not on DefinitelyTyped +//var map = require('map-stream'); +// +//orchestrator.add('thing4', function(){ +// var stream = map(function (args, cb) { +// cb(null, args); +// }); +// // do stream stuff +// return stream; +//}); + +// +// orchestrator.hasTask(name); +// + +orchestrator.hasTask('thing1'); + +// +// orchestrator.start(tasks...[, cb]); +// + +orchestrator.start('thing1', 'thing2', 'thing3', 'thing4', function (err) { + // all done +}); +orchestrator.start(['thing1','thing2'], ['thing3','thing4']); + + +// +// orchestrator.stop() +// + +orchestrator.stop(); + +// +// orchestrator.on(event, cb); +// + +orchestrator.on('task_start', function (e) { + var message: string = e.message; + var task: string = e.task; + var err: any = e.err; +}); +orchestrator.on('task_stop', function (e) { + var message: string = e.message; + var task: string = e.task; + var duration: number = e.duration; +}); + +// +// orchestrator.onAll(cb); +// + +orchestrator.onAll(function (e) { + var message: string = e.message; + var task: string = e.task; + var err: any = e.err; + var src: string = e.src; +}); + + diff --git a/orchestrator/orchestrator.d.ts b/orchestrator/orchestrator.d.ts new file mode 100644 index 000000000..2948aa927 --- /dev/null +++ b/orchestrator/orchestrator.d.ts @@ -0,0 +1,122 @@ +// Type definitions for Orchestrator +// Project: https://github.com/orchestrator/orchestrator +// Definitions by: Qubo +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare type Strings = string|string[]; + +export interface AddMethodCallback { + /** + * Accept a callback + * @param callback + */ + (callback?: Function): any; + /** + * Return a promise + */ + (): Q.Promise; + /** + * Return a stream: (task is marked complete when stream ends) + */ + (): any; //TODO: stream type should be here e.g. map-stream +} + +/** + * Define a task + */ +export interface AddMethod { + /** + * Define a task + * @param name The name of the task. + * @param deps An array of task names to be executed and completed before your task will run. + * @param fn The function that performs the task's operations. For asynchronous tasks, you need to provide a hint when the task is complete: + *
      + *
    • Take in a callback
    • + *
    • Return a stream or a promise
    • + *
    + */ + (name: string, deps?: string[], fn?: AddMethodCallback|Function): Orchestrator; + /** + * Define a task + * @param name The name of the task. + * @param fn The function that performs the task's operations. For asynchronous tasks, you need to provide a hint when the task is complete: + *
      + *
    • Take in a callback
    • + *
    • Return a stream or a promise
    • + *
    + */ + (name: string, fn?: AddMethodCallback|Function): Orchestrator; +} + +/** + * Start running the tasks + */ +export interface StartMethod { + /** + * Start running the tasks + * @param tasks Tasks to be executed. You may pass any number of tasks as individual arguments. + * @param cb Callback to call after run completed. + */ + (tasks: Strings, cb?: (error?: any) => any): Orchestrator; + /** + * Start running the tasks + * @param tasks Tasks to be executed. You may pass any number of tasks as individual arguments. + * @param cb Callback to call after run completed. + */ + (...tasks: Strings[]/*, cb?: (error: any) => any */): Orchestrator; + //TODO: TypeScript 1.5.3 cannot express varargs followed by callback as a last argument... + (task1: Strings, task2: Strings, cb?: (error?: any) => any): Orchestrator; + (task1: Strings, task2: Strings, task3: Strings, cb?: (error?: any) => any): Orchestrator; + (task1: Strings, task2: Strings, task3: Strings, task4: Strings, cb?: (error?: any) => any): Orchestrator; + (task1: Strings, task2: Strings, task3: Strings, task4: Strings, task5: Strings, cb?: (error?: any) => any): Orchestrator; + (task1: Strings, task2: Strings, task3: Strings, task4: Strings, task5: Strings, task6: Strings, cb?: (error?: any) => any): Orchestrator; +} + +export interface OnCallbackEvent { + message: string; + task: string; + err: any; + duration?: number; +} + +export interface OnAllCallbackEvent extends OnCallbackEvent { + src: string; +} + +declare class Orchestrator { + add: AddMethod; + /** + * Have you defined a task with this name? + * @param name The task name to query + */ + hasTask(name: string): boolean; + start: StartMethod; + stop(): void; + + /** + * Listen to orchestrator internals + * @param event Event name to listen to: + *
      + *
    • start: from start() method, shows you the task sequence + *
    • stop: from stop() method, the queue finished successfully + *
    • err: from stop() method, the queue was aborted due to a task error + *
    • task_start: from _runTask() method, task was started + *
    • task_stop: from _runTask() method, task completed successfully + *
    • task_err: from _runTask() method, task errored + *
    • task_not_found: from start() method, you're trying to start a task that doesn't exist + *
    • task_recursion: from start() method, there are recursive dependencies in your task list + *
    + * @param cb Passes single argument: e: event details + */ + on(event: string, cb: (e: OnCallbackEvent) => any): Orchestrator; + + /** + * Listen to all orchestrator events from one callback + * @param cb Passes single argument: e: event details + */ + onAll(cb: (e: OnAllCallbackEvent) => any): void; +} + +export default Orchestrator; From 8cc0285d3428eed76c01a9c76b27238b59d7ace8 Mon Sep 17 00:00:00 2001 From: tkQubo Date: Fri, 21 Aug 2015 04:13:03 +0900 Subject: [PATCH 111/173] Add missing type annotations --- orchestrator/orchestrator-test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/orchestrator/orchestrator-test.ts b/orchestrator/orchestrator-test.ts index af9af745c..047e00047 100644 --- a/orchestrator/orchestrator-test.ts +++ b/orchestrator/orchestrator-test.ts @@ -23,7 +23,7 @@ orchestrator.add('thing2', function() { orchestrator.add('mytask', ['array', 'of', 'task', 'names'], function() { // Do stuff }); -orchestrator.add('thing2', function(callback){ +orchestrator.add('thing2', function(callback: any){ var err: any = null; // do stuff callback(err); @@ -65,7 +65,7 @@ orchestrator.hasTask('thing1'); // orchestrator.start(tasks...[, cb]); // -orchestrator.start('thing1', 'thing2', 'thing3', 'thing4', function (err) { +orchestrator.start('thing1', 'thing2', 'thing3', 'thing4', function (err: any) { // all done }); orchestrator.start(['thing1','thing2'], ['thing3','thing4']); From 422b006d39dd37fc667ce5464967ee3ff6135092 Mon Sep 17 00:00:00 2001 From: tkQubo Date: Fri, 21 Aug 2015 12:06:21 +0900 Subject: [PATCH 112/173] Use external module --- orchestrator/orchestrator-test.ts | 3 +- orchestrator/orchestrator.d.ts | 229 +++++++++++++++--------------- 2 files changed, 119 insertions(+), 113 deletions(-) diff --git a/orchestrator/orchestrator-test.ts b/orchestrator/orchestrator-test.ts index 047e00047..6f1a4a79b 100644 --- a/orchestrator/orchestrator-test.ts +++ b/orchestrator/orchestrator-test.ts @@ -3,7 +3,7 @@ 'use strict'; -import Orchestrator from 'orchestrator'; +import Orchestrator = require('orchestrator'); var orchestrator = new Orchestrator(); @@ -104,3 +104,4 @@ orchestrator.onAll(function (e) { }); + diff --git a/orchestrator/orchestrator.d.ts b/orchestrator/orchestrator.d.ts index 2948aa927..24ebec8cb 100644 --- a/orchestrator/orchestrator.d.ts +++ b/orchestrator/orchestrator.d.ts @@ -7,116 +7,121 @@ declare type Strings = string|string[]; -export interface AddMethodCallback { - /** - * Accept a callback - * @param callback - */ - (callback?: Function): any; - /** - * Return a promise - */ - (): Q.Promise; - /** - * Return a stream: (task is marked complete when stream ends) - */ - (): any; //TODO: stream type should be here e.g. map-stream +declare module "orchestrator" { + class Orchestrator { + add: Orchestrator.AddMethod; + /** + * Have you defined a task with this name? + * @param name The task name to query + */ + hasTask(name: string): boolean; + start: Orchestrator.StartMethod; + stop(): void; + + /** + * Listen to orchestrator internals + * @param event Event name to listen to: + *
      + *
    • start: from start() method, shows you the task sequence + *
    • stop: from stop() method, the queue finished successfully + *
    • err: from stop() method, the queue was aborted due to a task error + *
    • task_start: from _runTask() method, task was started + *
    • task_stop: from _runTask() method, task completed successfully + *
    • task_err: from _runTask() method, task errored + *
    • task_not_found: from start() method, you're trying to start a task that doesn't exist + *
    • task_recursion: from start() method, there are recursive dependencies in your task list + *
    + * @param cb Passes single argument: e: event details + */ + on(event: string, cb: (e: Orchestrator.OnCallbackEvent) => any): Orchestrator; + + /** + * Listen to all orchestrator events from one callback + * @param cb Passes single argument: e: event details + */ + onAll(cb: (e: Orchestrator.OnAllCallbackEvent) => any): void; + } + + namespace Orchestrator { + interface AddMethodCallback { + /** + * Accept a callback + * @param callback + */ + (callback?: Function): any; + /** + * Return a promise + */ + (): Q.Promise; + /** + * Return a stream: (task is marked complete when stream ends) + */ + (): any; //TODO: stream type should be here e.g. map-stream + } + + /** + * Define a task + */ + interface AddMethod { + /** + * Define a task + * @param name The name of the task. + * @param deps An array of task names to be executed and completed before your task will run. + * @param fn The function that performs the task's operations. For asynchronous tasks, you need to provide a hint when the task is complete: + *
      + *
    • Take in a callback
    • + *
    • Return a stream or a promise
    • + *
    + */ + (name: string, deps?: string[], fn?: AddMethodCallback|Function): Orchestrator; + /** + * Define a task + * @param name The name of the task. + * @param fn The function that performs the task's operations. For asynchronous tasks, you need to provide a hint when the task is complete: + *
      + *
    • Take in a callback
    • + *
    • Return a stream or a promise
    • + *
    + */ + (name: string, fn?: AddMethodCallback|Function): Orchestrator; + } + + /** + * Start running the tasks + */ + interface StartMethod { + /** + * Start running the tasks + * @param tasks Tasks to be executed. You may pass any number of tasks as individual arguments. + * @param cb Callback to call after run completed. + */ + (tasks: Strings, cb?: (error?: any) => any): Orchestrator; + /** + * Start running the tasks + * @param tasks Tasks to be executed. You may pass any number of tasks as individual arguments. + * @param cb Callback to call after run completed. + */ + (...tasks: Strings[]/*, cb?: (error: any) => any */): Orchestrator; + //TODO: TypeScript 1.5.3 cannot express varargs followed by callback as a last argument... + (task1: Strings, task2: Strings, cb?: (error?: any) => any): Orchestrator; + (task1: Strings, task2: Strings, task3: Strings, cb?: (error?: any) => any): Orchestrator; + (task1: Strings, task2: Strings, task3: Strings, task4: Strings, cb?: (error?: any) => any): Orchestrator; + (task1: Strings, task2: Strings, task3: Strings, task4: Strings, task5: Strings, cb?: (error?: any) => any): Orchestrator; + (task1: Strings, task2: Strings, task3: Strings, task4: Strings, task5: Strings, task6: Strings, cb?: (error?: any) => any): Orchestrator; + } + + interface OnCallbackEvent { + message: string; + task: string; + err: any; + duration?: number; + } + + interface OnAllCallbackEvent extends OnCallbackEvent { + src: string; + } + + } + + export = Orchestrator; } - -/** - * Define a task - */ -export interface AddMethod { - /** - * Define a task - * @param name The name of the task. - * @param deps An array of task names to be executed and completed before your task will run. - * @param fn The function that performs the task's operations. For asynchronous tasks, you need to provide a hint when the task is complete: - *
      - *
    • Take in a callback
    • - *
    • Return a stream or a promise
    • - *
    - */ - (name: string, deps?: string[], fn?: AddMethodCallback|Function): Orchestrator; - /** - * Define a task - * @param name The name of the task. - * @param fn The function that performs the task's operations. For asynchronous tasks, you need to provide a hint when the task is complete: - *
      - *
    • Take in a callback
    • - *
    • Return a stream or a promise
    • - *
    - */ - (name: string, fn?: AddMethodCallback|Function): Orchestrator; -} - -/** - * Start running the tasks - */ -export interface StartMethod { - /** - * Start running the tasks - * @param tasks Tasks to be executed. You may pass any number of tasks as individual arguments. - * @param cb Callback to call after run completed. - */ - (tasks: Strings, cb?: (error?: any) => any): Orchestrator; - /** - * Start running the tasks - * @param tasks Tasks to be executed. You may pass any number of tasks as individual arguments. - * @param cb Callback to call after run completed. - */ - (...tasks: Strings[]/*, cb?: (error: any) => any */): Orchestrator; - //TODO: TypeScript 1.5.3 cannot express varargs followed by callback as a last argument... - (task1: Strings, task2: Strings, cb?: (error?: any) => any): Orchestrator; - (task1: Strings, task2: Strings, task3: Strings, cb?: (error?: any) => any): Orchestrator; - (task1: Strings, task2: Strings, task3: Strings, task4: Strings, cb?: (error?: any) => any): Orchestrator; - (task1: Strings, task2: Strings, task3: Strings, task4: Strings, task5: Strings, cb?: (error?: any) => any): Orchestrator; - (task1: Strings, task2: Strings, task3: Strings, task4: Strings, task5: Strings, task6: Strings, cb?: (error?: any) => any): Orchestrator; -} - -export interface OnCallbackEvent { - message: string; - task: string; - err: any; - duration?: number; -} - -export interface OnAllCallbackEvent extends OnCallbackEvent { - src: string; -} - -declare class Orchestrator { - add: AddMethod; - /** - * Have you defined a task with this name? - * @param name The task name to query - */ - hasTask(name: string): boolean; - start: StartMethod; - stop(): void; - - /** - * Listen to orchestrator internals - * @param event Event name to listen to: - *
      - *
    • start: from start() method, shows you the task sequence - *
    • stop: from stop() method, the queue finished successfully - *
    • err: from stop() method, the queue was aborted due to a task error - *
    • task_start: from _runTask() method, task was started - *
    • task_stop: from _runTask() method, task completed successfully - *
    • task_err: from _runTask() method, task errored - *
    • task_not_found: from start() method, you're trying to start a task that doesn't exist - *
    • task_recursion: from start() method, there are recursive dependencies in your task list - *
    - * @param cb Passes single argument: e: event details - */ - on(event: string, cb: (e: OnCallbackEvent) => any): Orchestrator; - - /** - * Listen to all orchestrator events from one callback - * @param cb Passes single argument: e: event details - */ - onAll(cb: (e: OnAllCallbackEvent) => any): void; -} - -export default Orchestrator; From 0089d2ac52903d4e676414632cb69cdffb71894d Mon Sep 17 00:00:00 2001 From: tkQubo Date: Fri, 21 Aug 2015 20:00:13 +0900 Subject: [PATCH 113/173] Add node-notifier --- node-notifier/node-notifier-test.ts | 162 +++++++++++++++++++++++++++ node-notifier/node-notifier.d.ts | 167 ++++++++++++++++++++++++++++ 2 files changed, 329 insertions(+) create mode 100644 node-notifier/node-notifier-test.ts create mode 100644 node-notifier/node-notifier.d.ts diff --git a/node-notifier/node-notifier-test.ts b/node-notifier/node-notifier-test.ts new file mode 100644 index 000000000..dfc4963ac --- /dev/null +++ b/node-notifier/node-notifier-test.ts @@ -0,0 +1,162 @@ +/// +'use strict'; + +import notifier = require('node-notifier'); +import * as path from 'path'; + +notifier.notify({ + title: 'My awesome title', + message: 'Hello from node, Mr. User!', + icon: path.join(__dirname, 'coulson.jpg'), // absolute path (not balloons) + sound: true, // Only Notification Center or Windows Toasters + wait: true // wait with callback until user action is taken on notification +}, function (err: any, response: any) { + // response is response from notification +}); + +notifier.on('click', function (notifierObject: any, options: any) { + // Happens if `wait: true` and user clicks notification +}); + +notifier.on('timeout', function (notifierObject: any, options: any) { + // Happens if `wait: true` and notification closes +}); + +const options = { }; + + +import NotificationCenter = require('node-notifier/notifiers/notificationcenter'); +new NotificationCenter(options).notify(); + +import NotifySend = require('node-notifier/notifiers/notifysend'); +new NotifySend(options).notify(); + +import WindowsToaster = require('node-notifier/notifiers/toaster'); +new WindowsToaster(options).notify(); + +import Growl = require('node-notifier/notifiers/growl'); +new Growl(options).notify(); + +import WindowsBalloon = require('node-notifier/notifiers/balloon'); +new WindowsBalloon(options).notify(); + + +var nn = require('node-notifier'); + +new nn.NotificationCenter(options).notify(); +new nn.NotifySend(options).notify(); +new nn.WindowsToaster(options).notify(options); +new nn.WindowsBalloon(options).notify(options); +new nn.Growl(options).notify(options); + + +// +// All notification options with their defaults: +// + +var NotificationCenter2 = require('node-notifier').NotificationCenter; + +var notifier2 = new NotificationCenter2({ + withFallback: false, // use Growl if <= 10.8? + customPath: void 0 // Relative path if you want to use your fork of terminal-notifier +}); + +notifier2.notify({ + 'title': void 0, + 'subtitle': void 0, + 'message': void 0, + 'sound': false, // Case Sensitive string of sound file (see below) + 'icon': 'Terminal Icon', // Set icon? (Absolute path to image) + 'contentImage': void 0, // Attach image? (Absolute path) + 'open': void 0, // URL to open on click + 'wait': false // if wait for notification to end +}, function(error: any, response: any) { + console.log(response); +}); + +// +// Usage WindowsToaster +// + +var WindowsToaster2 = require('node-notifier').WindowsToaster; + +var notifier3 = new WindowsToaster2({ + withFallback: false, // Fallback to Growl or Balloons? + customPath: void 0 // Relative path if you want to use your fork of toast.exe +}); + +notifier3.notify({ + title: void 0, + message: void 0, + icon: void 0, // absolute path to an icon + sound: false, // true | false. + wait: false, // if wait for notification to end +}, function(error: any, response: any) { + console.log(response); +}); + +// +// Usage Growl +// + +var Growl2 = require('node-notifier').Growl; +import * as fs from 'fs'; + +var notifier4 = new Growl2({ + name: 'Growl Name Used', // Defaults as 'Node' + host: 'localhost', + port: 23053 +}); + +notifier4.notify({ + title: 'Foo', + message: 'Hello World', + icon: fs.readFileSync(__dirname + "/coulson.jpg"), + wait: false, // if wait for user interaction + + // and other growl options like sticky etc. + sticky: false, + label: void 0, + priority: void 0 +}); + +// +// Usage WindowsBalloon +// + +var WindowsBalloon2 = require('node-notifier').WindowsBalloon; + +var notifier5 = new WindowsBalloon2({ + withFallback: false, // Try Windows 8 and Growl first? + customPath: void 0 // Relative path if you want to use your fork of notifu +}); + +notifier5.notify({ + title: void 0, + message: void 0, + sound: false, // true | false. + time: 5000, // How long to show balloons in ms + wait: false, // if wait for notification to end +}, function(error: any, response: any) { + console.log(response); +}); + +// +// Usage NotifySend +// + +var NotifySend2 = require('node-notifier').NotifySend; + +var notifier6 = new NotifySend2(); + +notifier6.notify({ + title: 'Foo', + message: 'Hello World', + icon: __dirname + "/coulson.jpg", + + // .. and other notify-send flags: + urgency: void 0, + time: void 0, + category: void 0, + hint: void 0, +}); diff --git a/node-notifier/node-notifier.d.ts b/node-notifier/node-notifier.d.ts new file mode 100644 index 000000000..d003001a3 --- /dev/null +++ b/node-notifier/node-notifier.d.ts @@ -0,0 +1,167 @@ +// Type definitions for node-notifier +// Project: https://github.com/mikaelbr/node-notifier +// Definitions by: Qubo +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare module "node-notifier" { + import NotificationCenter = require('node-notifier/notifiers/notificationcenter'); + import NotifySend = require("node-notifier/notifiers/notifysend"); + import WindowsToaster = require("node-notifier/notifiers/toaster"); + import WindowsBalloon = require("node-notifier/notifiers/balloon"); + import Growl = require("node-notifier/notifiers/growl"); + + namespace nodeNotifier { + interface NodeNotifier extends NodeJS.EventEmitter { + notify(notification?: Notification, callback?: NotificationCallback): NodeNotifier; + NotificationCenter: NotificationCenter; + NotifySend: NotifySend; + WindowsToaster: WindowsToaster; + WindowsBalloon: WindowsBalloon; + Growl: Growl; + } + + interface Notification { + title?: string; + message?: string; + /** Absolute path (not balloons) */ + icon?: string; + /** Only Notification Center or Windows Toasters */ + sound?: boolean; + /** Wait with callback until user action is taken on notification */ + wait?: boolean; + } + + interface NotificationCallback { + (err: any, response: any): any; + } + + interface Option { + withFallback?: boolean; + customPath?: string; + } + } + + var nodeNotifier: nodeNotifier.NodeNotifier; + + export = nodeNotifier; +} + +declare module "node-notifier/notifiers/notificationcenter" { + import notifier = require('node-notifier'); + + class NotificationCenter { + constructor(option?: notifier.Option); + notify(notification?: NotificationCenter.Notification, callback?: notifier.NotificationCallback): NotificationCenter; + } + + namespace NotificationCenter { + interface Notification extends notifier.Notification { + subtitle?: string; + /** Attach image? (Absolute path) */ + contentImage?: string; + /** URL to open on click */ + open?: string; + } + } + + export = NotificationCenter; +} + +declare module "node-notifier/notifiers/notifysend" { + import notifier = require('node-notifier'); + + class NotifySend { + constructor(option?: notifier.Option); + notify(notification?: NotifySend.Notification, callback?: notifier.NotificationCallback): NotifySend; + } + + namespace NotifySend { + interface Notification { + title?: string; + message?: string; + icon?: string; + /** Specifies the urgency level (low, normal, critical). */ + urgency?: string; + /** Specifies the timeout in milliseconds at which to expire the notification */ + time?: number; + /** Specifies the notification category */ + category?: string; + /** Specifies basic extra data to pass. Valid types are int, double, string and byte. */ + hint?: string; + } + } + + export = NotifySend; +} + +declare module "node-notifier/notifiers/toaster" { + import notifier = require('node-notifier'); + + class WindowsToaster { + constructor(option?: notifier.Option); + notify(notification?: notifier.Notification, callback?: notifier.NotificationCallback): WindowsToaster; + } + + export = WindowsToaster; +} + +declare module "node-notifier/notifiers/growl" { + import notifier = require('node-notifier'); + + class Growl { + constructor(option?: Growl.Option); + notify(notification?: Growl.Notification, callback?: notifier.NotificationCallback): Growl; + } + + namespace Growl { + interface Option { + name?: string; + host?: string; + port?: number; + } + + interface Notification { + title?: string; + message?: string; + /** Absolute path (not balloons) */ + icon?: string; + /** Wait with callback until user action is taken on notification */ + wait?: boolean; + /** whether or not to sticky the notification (defaults to false) */ + sticky?: boolean; + /** type of notification to use (defaults to the first registered type) */ + label: string; + /** the priority of the notification from lowest (-2) to highest (2) */ + priority: number; + } + } + + export = Growl; +} + +declare module "node-notifier/notifiers/balloon" { + import notifier = require('node-notifier'); + + class WindowsBalloon { + constructor(option?: notifier.Option); + notify(notification?: WindowsBalloon.Notification, callback?: notifier.NotificationCallback): WindowsBalloon; + } + + namespace WindowsBalloon { + interface Notification { + title?: string; + message?: string; + /** Only Notification Center or Windows Toasters */ + sound?: boolean; + /** How long to show balloons in ms */ + time?: number; + /** Wait with callback until user action is taken on notification */ + wait?: boolean; + } + } + + export = WindowsBalloon; +} From 0a9004eb587c8143a65a5eeb48171681e8552a6b Mon Sep 17 00:00:00 2001 From: Nick Chang Date: Mon, 10 Aug 2015 17:44:44 -0700 Subject: [PATCH 114/173] CodeMirror: EditorConfiguration.lint can be boolean --- codemirror/codemirror.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/codemirror/codemirror.d.ts b/codemirror/codemirror.d.ts index 86c01141e..06361684d 100644 --- a/codemirror/codemirror.d.ts +++ b/codemirror/codemirror.d.ts @@ -787,7 +787,7 @@ declare module CodeMirror { viewportMargin?: number; /** Optional lint configuration to be used in conjunction with CodeMirror's linter addon. */ - lint?: LintOptions; + lint?: boolean | LintOptions; } interface TextMarkerOptions { From 58fe0b0e72fbea01c059d507512cdedf30d5272d Mon Sep 17 00:00:00 2001 From: Joe Skeen Date: Fri, 21 Aug 2015 09:17:54 -0600 Subject: [PATCH 115/173] Definitions for gulp-plumber --- gulp-plumber/gulp-plumber-tests.ts | 36 +++++++++++++++++++++ gulp-plumber/gulp-plumber.d.ts | 51 ++++++++++++++++++++++++++++++ 2 files changed, 87 insertions(+) create mode 100644 gulp-plumber/gulp-plumber-tests.ts create mode 100644 gulp-plumber/gulp-plumber.d.ts diff --git a/gulp-plumber/gulp-plumber-tests.ts b/gulp-plumber/gulp-plumber-tests.ts new file mode 100644 index 000000000..cf055dad5 --- /dev/null +++ b/gulp-plumber/gulp-plumber-tests.ts @@ -0,0 +1,36 @@ +/// +/// +/// + +import gulp = require('gulp'); +import plumber = require('gulp-plumber'); + +//default behavior +gulp.src('./src/*.ext') + .pipe(plumber()) + .pipe(gulp.dest('./dist')); + +//error handler function +gulp.src('./src/*.ext') + .pipe(plumber((error) => { + console.log(error); + })) + .pipe(gulp.dest('./dist')); + +gulp.src('./src/*.ext') + .pipe(plumber({})) + .pipe(gulp.dest('./dist')); + +gulp.src('./src/*.ext') + .pipe(plumber({ inherit: false })) + .pipe(gulp.dest('./dist')); + +gulp.src('./src/*.ext') + .pipe(plumber({ errorHandler: (error) => console.log(error) })) + .pipe(gulp.dest('./dist')); + +//plumber.stop() +gulp.src('./src/*.scss') + .pipe(plumber()) + .pipe(plumber.stop()) + .pipe(gulp.dest('./dist')); \ No newline at end of file diff --git a/gulp-plumber/gulp-plumber.d.ts b/gulp-plumber/gulp-plumber.d.ts new file mode 100644 index 000000000..0301affd6 --- /dev/null +++ b/gulp-plumber/gulp-plumber.d.ts @@ -0,0 +1,51 @@ +// Type definitions for gulp-plumber +// Project: https://github.com/floatdrop/gulp-plumber +// Definitions by: Joe Skeen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +/** Prevent pipe breaking caused by errors from gulp plugins */ +declare module 'gulp-plumber' { + + /** Prevent pipe breaking caused by errors from gulp plugins */ + interface GulpPlumber { + /** + * Returns Stream, that fixes pipe methods on Streams that are next in pipeline. + * + * @param options Sets options as described in the Options interface + */ + (options?: Options): NodeJS.ReadWriteStream; + /** + * Returns Stream, that fixes pipe methods on Streams that are next in pipeline. + * + * @param errorHandler the function to be attached to the stream on('error') + */ + (errorHandler: ErrorHandlerFunction): NodeJS.ReadWriteStream; + /** returns default behaviour for pipeline after it was piped */ + stop(): NodeJS.ReadWriteStream; + } + + interface Options { + /** + * Handle errors in underlying streams and output them to console. Default true. + * If function passed, it will be attached to stream on('error') + * If false passed, error handler will not be attached + * If undefined passed, default error handler will be attached + */ + errorHandler?: ErrorHandlerFunction | boolean; + /** Monkeypatch pipe functions in underlying streams in pipeline. Default true. */ + inherit?: boolean; + } + + /** an error handler function to be attached to the stream on('error') */ + interface ErrorHandlerFunction { + /** an error handler function to be attached to the stream on('error') */ + (error): void; + } + + /** Prevent pipe breaking caused by errors from gulp plugins */ + var gulpPlumber: GulpPlumber; + + export = gulpPlumber; +} From 4e950fdf8cbd5a8b001be640046f98935c08ce61 Mon Sep 17 00:00:00 2001 From: Joe Skeen Date: Fri, 21 Aug 2015 09:26:23 -0600 Subject: [PATCH 116/173] add explicit any type for error handler parameter (since any type can be thrown in JS) --- gulp-plumber/gulp-plumber.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gulp-plumber/gulp-plumber.d.ts b/gulp-plumber/gulp-plumber.d.ts index 0301affd6..693c4cbf9 100644 --- a/gulp-plumber/gulp-plumber.d.ts +++ b/gulp-plumber/gulp-plumber.d.ts @@ -41,7 +41,7 @@ declare module 'gulp-plumber' { /** an error handler function to be attached to the stream on('error') */ interface ErrorHandlerFunction { /** an error handler function to be attached to the stream on('error') */ - (error): void; + (error: any): void; } /** Prevent pipe breaking caused by errors from gulp plugins */ From 7ff45ed3e3aa9a01f87461d631b4578139cde287 Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Sat, 22 Aug 2015 00:27:35 +0900 Subject: [PATCH 117/173] Add my name --- selenium-webdriver/selenium-webdriver.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index d54ea62fa..61a920f30 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -1,6 +1,6 @@ // Type definitions for Selenium WebDriverJS 2.44.0 // Project: https://code.google.com/p/selenium/ -// Definitions by: Bill Armstrong +// Definitions by: Bill Armstrong , Yuki Kokubun // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module chrome { From 6de08d270c37a0c5c026c1c2b029b1b552ccc927 Mon Sep 17 00:00:00 2001 From: vvakame Date: Sat, 22 Aug 2015 00:31:02 +0900 Subject: [PATCH 118/173] fix imagesloaded/imagesloaded-tests.ts --- imagesloaded/imagesloaded-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/imagesloaded/imagesloaded-tests.ts b/imagesloaded/imagesloaded-tests.ts index ad9d3a3db..7ab773822 100644 --- a/imagesloaded/imagesloaded-tests.ts +++ b/imagesloaded/imagesloaded-tests.ts @@ -1,4 +1,4 @@ -/// +/// function test_ctor() { // element From 00db3ad4b0261ff513a7b688263fffb70bdfc972 Mon Sep 17 00:00:00 2001 From: tkQubo Date: Sat, 22 Aug 2015 00:49:45 +0900 Subject: [PATCH 119/173] Rename test file --- orchestrator/{orchestrator-test.ts => orchestrator-tests.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename orchestrator/{orchestrator-test.ts => orchestrator-tests.ts} (100%) diff --git a/orchestrator/orchestrator-test.ts b/orchestrator/orchestrator-tests.ts similarity index 100% rename from orchestrator/orchestrator-test.ts rename to orchestrator/orchestrator-tests.ts From 3455df2c1449774b389c9052a2fa7e7fdac11898 Mon Sep 17 00:00:00 2001 From: tkQubo Date: Sat, 22 Aug 2015 00:51:02 +0900 Subject: [PATCH 120/173] Rename test file --- node-notifier/{node-notifier-test.ts => node-notifier-tests.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename node-notifier/{node-notifier-test.ts => node-notifier-tests.ts} (100%) diff --git a/node-notifier/node-notifier-test.ts b/node-notifier/node-notifier-tests.ts similarity index 100% rename from node-notifier/node-notifier-test.ts rename to node-notifier/node-notifier-tests.ts From 69c5732a871ce4934b76c7a9c3abce5ef306a08d Mon Sep 17 00:00:00 2001 From: tkQubo Date: Sat, 22 Aug 2015 01:11:43 +0900 Subject: [PATCH 121/173] Add envify --- envify/envify-tests.ts | 21 +++++++++++++++++++++ envify/envify.d.ts | 14 ++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 envify/envify-tests.ts create mode 100644 envify/envify.d.ts diff --git a/envify/envify-tests.ts b/envify/envify-tests.ts new file mode 100644 index 000000000..a8dba932e --- /dev/null +++ b/envify/envify-tests.ts @@ -0,0 +1,21 @@ +/// +/// + +import browserify = require('browserify') +import envify = require('envify/custom'); +import fs = require('fs'); + + +var b = browserify('main.js') + , output = fs.createWriteStream('bundle.js'); + +b.transform(envify({ + NODE_ENV: 'development' +})); +b.bundle().pipe(output); + +b.transform(envify({ + _: 'purge' + , NODE_ENV: 'development' +})); + diff --git a/envify/envify.d.ts b/envify/envify.d.ts new file mode 100644 index 000000000..39479f503 --- /dev/null +++ b/envify/envify.d.ts @@ -0,0 +1,14 @@ +// Type definitions for envify +// Project: https://github.com/hughsk/envify +// Definitions by: Qubo +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "envify" { + var envify: Function; + export = envify; +} + +declare module "envify/custom" { + function envify(environment: { [name: string]: any }): Function; + export = envify; +} From 0472794599e36a5ffd3e70e71c24d11e0a3c43fb Mon Sep 17 00:00:00 2001 From: tkQubo Date: Sat, 22 Aug 2015 01:13:31 +0900 Subject: [PATCH 122/173] Add missing semicolon --- envify/envify-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/envify/envify-tests.ts b/envify/envify-tests.ts index a8dba932e..52387a3e6 100644 --- a/envify/envify-tests.ts +++ b/envify/envify-tests.ts @@ -1,7 +1,7 @@ /// /// -import browserify = require('browserify') +import browserify = require('browserify'); import envify = require('envify/custom'); import fs = require('fs'); From 371ffebdb032cdaf67d9dcc175a62b8a71946f86 Mon Sep 17 00:00:00 2001 From: tpodolak Date: Fri, 21 Aug 2015 23:21:45 +0200 Subject: [PATCH 123/173] Added support for authenticateAndContinue --- winrt/winrt.d.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/winrt/winrt.d.ts b/winrt/winrt.d.ts index b8b40f7cd..f3be7feac 100644 --- a/winrt/winrt.d.ts +++ b/winrt/winrt.d.ts @@ -1541,6 +1541,7 @@ declare module Windows { device, printTaskSettings, cameraSettings, + webAuthenticationBrokerContinuation } export interface IActivatedEventArgs { kind: Windows.ApplicationModel.Activation.ActivationKind; @@ -8489,11 +8490,17 @@ declare module Windows { export interface IWebAuthenticationBrokerStatics { authenticateAsync(options: Windows.Security.Authentication.Web.WebAuthenticationOptions, requestUri: Windows.Foundation.Uri, callbackUri: Windows.Foundation.Uri): Windows.Foundation.IAsyncOperation; authenticateAsync(options: Windows.Security.Authentication.Web.WebAuthenticationOptions, requestUri: Windows.Foundation.Uri): Windows.Foundation.IAsyncOperation; + authenticateAndContinue(requestUri: Windows.Foundation.Uri): void; + authenticateAndContinue(requestUri: Windows.Foundation.Uri, callbackUri: Windows.Foundation.Uri): void; + authenticateAndContinue(requestUri: Windows.Foundation.Uri, callbackUri: Windows.Foundation.Uri, continuationData: Windows.Foundation.Collections.ValueSet, options: Windows.Security.Authentication.Web.WebAuthenticationOptions): void; getCurrentApplicationCallbackUri(): Windows.Foundation.Uri; } export class WebAuthenticationBroker { static authenticateAsync(options: Windows.Security.Authentication.Web.WebAuthenticationOptions, requestUri: Windows.Foundation.Uri, callbackUri: Windows.Foundation.Uri): Windows.Foundation.IAsyncOperation; static authenticateAsync(options: Windows.Security.Authentication.Web.WebAuthenticationOptions, requestUri: Windows.Foundation.Uri): Windows.Foundation.IAsyncOperation; + static authenticateAndContinue(requestUri: Windows.Foundation.Uri): void; + static authenticateAndContinue(requestUri: Windows.Foundation.Uri, callbackUri: Windows.Foundation.Uri): void; + static authenticateAndContinue(requestUri: Windows.Foundation.Uri, callbackUri: Windows.Foundation.Uri, continuationData: Windows.Foundation.Collections.ValueSet, options: Windows.Security.Authentication.Web.WebAuthenticationOptions): void; static getCurrentApplicationCallbackUri(): Windows.Foundation.Uri; } } From 9cca17f21da895e45d04b1618b74ac160910f08c Mon Sep 17 00:00:00 2001 From: Michael Randolph Date: Fri, 21 Aug 2015 17:36:40 -0400 Subject: [PATCH 124/173] Fixed fabric so noImplicitAny would stop complaining --- fabricjs/fabricjs-tests.ts | 38 +++++++++++++++--------------- fabricjs/fabricjs.d.ts | 48 +++++++++++++++++++------------------- 2 files changed, 43 insertions(+), 43 deletions(-) diff --git a/fabricjs/fabricjs-tests.ts b/fabricjs/fabricjs-tests.ts index 89c882b05..5800879f3 100644 --- a/fabricjs/fabricjs-tests.ts +++ b/fabricjs/fabricjs-tests.ts @@ -34,8 +34,8 @@ function sample1() { function sample2() { - var dot, i, - t1, t2, + var dot: fabric.ICircle, i: number, + t1: number, t2: number, startTimer = function() { t1 = new Date().getTime(); return t1; @@ -89,16 +89,16 @@ function sample2() { function sample3() { - var $ = function(id) { return document.getElementById(id) }; + var $: (id: string) => HTMLElement = function(id: string) { return document.getElementById(id) }; - function applyFilter(index, filter) { - var obj = canvas.getActiveObject(); + function applyFilter(index: number, filter: any) { + var obj: fabric.IImage = canvas.getActiveObject(); obj.filters[index] = filter; obj.applyFilters(canvas.renderAll.bind(canvas)); } - function applyFilterValue(index, prop, value) { - var obj = canvas.getActiveObject(); + function applyFilterValue(index: number, prop: string, value: any) { + var obj: fabric.IImage = canvas.getActiveObject(); if (obj.filters[index]) { obj.filters[index][prop] = value; obj.applyFilters(canvas.renderAll.bind(canvas)); @@ -214,7 +214,7 @@ function sample3() { function sample4() { var canvas = new fabric.Canvas('c'); - var $ = function(id) { return document.getElementById(id); }; + var $: (id: string) => HTMLElement = function(id: string) { return document.getElementById(id); }; var rect = new fabric.Rect({ width: 100, @@ -339,10 +339,10 @@ function sample6() { canvas.centerObject(obj); canvas.add(obj); - canvas.add(obj.clone(() => {}).set({ left: 100, top: 100, angle: -15 })); - canvas.add(obj.clone(() => {}).set({ left: 480, top: 100, angle: 15 })); - canvas.add(obj.clone(() => {}).set({ left: 100, top: 400, angle: -15 })); - canvas.add(obj.clone(() => {}).set({ left: 480, top: 400, angle: 15 })); + canvas.add(obj.clone(() => { }).set({ left: 100, top: 100, angle: -15 })); + canvas.add(obj.clone(() => { }).set({ left: 480, top: 100, angle: 15 })); + canvas.add(obj.clone(() => { }).set({ left: 100, top: 400, angle: -15 })); + canvas.add(obj.clone(() => { }).set({ left: 480, top: 400, angle: 15 })); canvas.on('mouse:move', function(options) { var p = canvas.getPointer(options.e); @@ -456,7 +456,7 @@ function sample8() { top = fabric.util.getRandomInt(0 + offset, 500 - offset), angle = fabric.util.getRandomInt(-20, 40), width = fabric.util.getRandomInt(30, 50), - opacity = (function(min, max) { return Math.random() * (max - min) + min; })(0.5, 1); + opacity = (function(min: number, max: number) { return Math.random() * (max - min) + min; })(0.5, 1); switch (className) { @@ -522,7 +522,7 @@ function sample8() { break; case 'shape': - var id = element.id, match; + var id: any = element.id, match: RegExpExecArray; if (match = /\d+$/.exec(id)) { fabric.loadSVGFromURL('../assets/' + match[0] + '.svg', function(objects, options) { var loadedObject = fabric.util.groupSVGElements(objects, options); @@ -586,7 +586,7 @@ function sample8() { } }; - var supportsInputOfType = function(type) { + var supportsInputOfType = function(type: string) { return function() { var el = document.createElement('input'); try { @@ -746,7 +746,7 @@ function sample8() { canvas.on('object:selected', onObjectSelected); canvas.on('group:selected', onObjectSelected); - function onObjectSelected(e) { + function onObjectSelected(e: fabric.IEvent) { var selectedObject = e.target; for (var i = activeObjectButtons.length; i--;) { @@ -1033,7 +1033,7 @@ function sample8() { }; canvas.on('object:selected', function(e: fabric.IEvent) { - slider.value = String((e.target).lineHeight ); + slider.value = String((e.target).lineHeight); }); })(); } @@ -1050,6 +1050,6 @@ function sample8() { function sample9() { var canvas = new fabric.Canvas('c'); - canvas.setBackgroundImage('yolo.jpg',() => { "a" }, { opacity: 45 }); - canvas.setBackgroundImage('yolo.jpg',() => { "a" }); + canvas.setBackgroundImage('yolo.jpg', () => { "a" }, { opacity: 45 }); + canvas.setBackgroundImage('yolo.jpg', () => { "a" }); } diff --git a/fabricjs/fabricjs.d.ts b/fabricjs/fabricjs.d.ts index 503b8c7db..0eb6bacb7 100644 --- a/fabricjs/fabricjs.d.ts +++ b/fabricjs/fabricjs.d.ts @@ -1,6 +1,6 @@ // Type definitions for FabricJS v1.5.0 // Project: http://fabricjs.com/ -// Definitions by: Oliver Klemencic , Joseph Livecchi +// Definitions by: Oliver Klemencic , Joseph Livecchi , Michael Randolph // Definitions: https://github.com/borisyankov/DefinitelyTyped /* tslint:disable:no-unused-variable */ @@ -41,7 +41,7 @@ declare module fabric { * @param {Function} callback * @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created. */ - function loadSVGFromString(string: string, callback: (results: IObject[], options: any) => void, reviver?: Function); + function loadSVGFromString(string: string, callback: (results: IObject[], options: any) => void, reviver?: Function): void; /** * Takes url corresponding to an SVG document, and parses it into a set of fabric objects. * Note that SVG is fetched via XMLHttpRequest, so it needs to conform to SOP (Same Origin Policy) @@ -49,14 +49,14 @@ declare module fabric { * @param {Function} callback * @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created. */ - function loadSVGFromURL(url: string, callback: (results: IObject[], options: any) => void, reviver?: Function); + function loadSVGFromURL(url: string, callback: (results: IObject[], options: any) => void, reviver?: Function): void; /** * Returns CSS rules for a given SVG document * @param {SVGDocument} doc SVG document to parse */ function getCSSRules(doc: SVGElement): any; - function parseElements(elements: any[], callback: Function, options: any, reviver?: Function); + function parseElements(elements: any[], callback: Function, options: any, reviver?: Function): void; /** * Parses "points" attribute, returning an array of values * @param {String} points points attribute string @@ -99,7 +99,7 @@ declare module fabric { * @param {Function} callback Callback to call when parsing is finished; It's being passed an array of elements (parsed from a document). * @param {Function} [reviver] Method for further parsing of SVG elements, called after each fabric object created. */ - function parseSVGDocument(doc: SVGElement, callback: (results: IObject[], options: any) => void, reviver?: Function); + function parseSVGDocument(doc: SVGElement, callback: (results: IObject[], options: any) => void, reviver?: Function): void; /** * Parses "transform" attribute, returning an array of values * @param {String} attributeValue String containing attribute value @@ -111,11 +111,11 @@ declare module fabric { /** * Wrapper around `console.log` (when available) */ - function log(...values: any[]); + function log(...values: any[]): void; /** * Wrapper around `console.warn` (when available) */ - function warn(...values: any[]); + function warn(...values: any[]): void; //////////////////////////////////////////////////// // Classes @@ -438,7 +438,7 @@ declare module fabric { /** * Sets source of this color (where source is an array representation; ex: [200, 200, 100, 1]) */ - setSource(source: number[]); + setSource(source: number[]): void; /** * Returns color represenation in RGB format ex: rgb(0-255,0-255,0-255) @@ -474,7 +474,7 @@ declare module fabric { * Sets value of alpha channel for this color * @param {Number} alpha Alpha value 0-1 */ - setAlpha(alpha: number); + setAlpha(alpha: number): void; /** * Transforms color to its grayscale representation @@ -627,17 +627,17 @@ declare module fabric { /** * Appends a point to intersection */ - appendPoint(point: IPoint); + appendPoint(point: IPoint): void; /** * Appends points to intersection */ - appendPoints(points: IPoint[]); + appendPoints(points: IPoint[]): void; } interface IIntersectionStatic { /** * Intersection class */ - new (status?: string); + new (status?: string): void; /** * Checks if polygon intersects another polygon */ @@ -1313,7 +1313,7 @@ declare module fabric { /** * Callback; invoked right before object is about to be scaled/rotated */ - onBeforeScaleRotate(target: IObject); + onBeforeScaleRotate(target: IObject): void; // Functions from object straighten mixin // -------------------------------------------------------------------------------------------------------------------------------- @@ -1839,12 +1839,12 @@ declare module fabric { filters: IBaseFilter[]; } interface IImage extends IObject, IImageOptions { - initialize(element?: string|HTMLImageElement, options?: IImageOptions); + initialize(element?: string|HTMLImageElement, options?: IImageOptions): void; /** * Applies filters assigned to this image (from "filters" array) * @param {Function} callback Callback is invoked when all filters have been applied and new image is generated */ - applyFilters(callback: Function); + applyFilters(callback: Function): void; /** * Returns a clone of an instance * @param {Function} callback Callback is invoked with a clone as a first argument @@ -1871,7 +1871,7 @@ declare module fabric { * @return {String} Source of an image */ getSrc(): string; - render(ctx: CanvasRenderingContext2D, noTransform: boolean); + render(ctx: CanvasRenderingContext2D, noTransform: boolean): void; /** * Sets image element for this instance to a specified one. @@ -2539,7 +2539,7 @@ declare module fabric { * Sets object's properties from options * @param {Object} [options] Options object */ - setOptions(options: any); + setOptions(options: any): void; /** * Sets sourcePath of an object * @param {String} value Value to set sourcePath to @@ -2850,7 +2850,7 @@ declare module fabric { } interface IPathGroup extends IObject { - initialize(paths: IPath[], options?: IObjectOptions); + initialize(paths: IPath[], options?: IObjectOptions): void; /** * Returns number representation of object's complexity * @return {Number} complexity @@ -2865,7 +2865,7 @@ declare module fabric { * Renders this group on a specified context * @param {CanvasRenderingContext2D} ctx Context to render this instance on */ - render(ctx: CanvasRenderingContext2D); + render(ctx: CanvasRenderingContext2D): void; /** * Returns dataless object representation of this path group * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output @@ -2993,7 +2993,7 @@ declare module fabric { minY?: number; } interface IPolyline extends IObject, IPolylineOptions { - initialize(points: IPoint[], options?: IPolylineOptions); + initialize(points: IPoint[], options?: IPolylineOptions): void; /** * Returns complexity of an instance * @return {Number} complexity of this instance @@ -3158,7 +3158,7 @@ declare module fabric { * Renders text instance on a specified context * @param {CanvasRenderingContext2D} ctx Context to render on */ - render(ctx: CanvasRenderingContext2D, noTransform: boolean); + render(ctx: CanvasRenderingContext2D, noTransform: boolean): void; /** * Returns object representation of an instance * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output @@ -3347,7 +3347,7 @@ declare module fabric { * Returns true if object has no styling */ isEmptyStyles(): boolean; - render(ctx: CanvasRenderingContext2D, noTransform: boolean); + render(ctx: CanvasRenderingContext2D, noTransform: boolean): void; /** * Returns object representation of an instance * @method toObject @@ -4360,13 +4360,13 @@ declare module fabric { * @param {Object} [properties] Properties shared by all instances of this class * (be careful modifying objects defined here as this would affect all instances) */ - createClass(parent: Function, properties?: any); + createClass(parent: Function, properties?: any): void; /** * Helper for creation of "classes". * @param {Object} [properties] Properties shared by all instances of this class * (be careful modifying objects defined here as this would affect all instances) */ - createClass(properties?: any); + createClass(properties?: any): void; } From 95ff8e6916c93b40562dc2c427907f46fc115146 Mon Sep 17 00:00:00 2001 From: David Sidlinger Date: Fri, 21 Aug 2015 16:49:48 -0500 Subject: [PATCH 125/173] Remove implicit `any` from Dropzone --- dropzone/dropzone.d.ts | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/dropzone/dropzone.d.ts b/dropzone/dropzone.d.ts index 106e10313..1702ae484 100644 --- a/dropzone/dropzone.d.ts +++ b/dropzone/dropzone.d.ts @@ -33,7 +33,7 @@ interface DropzoneOptions { resize?: ( file?: any ) => any; init?: () => void; acceptedFiles?: string; - accept?: ( file: DropzoneFile, doneCallback: ( ...args ) => void ) => void; + accept?: ( file: DropzoneFile, doneCallback: ( ...args: any[] ) => void ) => void; autoProcessQueue?: boolean; previewTemplate?: string; forceFallback?: boolean; @@ -67,9 +67,9 @@ declare class Dropzone { disable(): void; destroy(): Dropzone; - on( eventName, callback: ( ...args ) => any ); + on( eventName: string, callback: ( ...args: any[] ) => any ): void; - off( eventName ): void; + off( eventName: string ): void; addFile( file: DropzoneFile ): void; @@ -99,24 +99,24 @@ declare class Dropzone { getFilesWithStatus( status: string ): DropzoneFile[]; enqueueFile( file: DropzoneFile ): void; enqueueFiles( file: DropzoneFile[] ): void; - createThumbnail( file: DropzoneFile, callback?: (...any) => {}): any; - createThumbnailFromUrl( file: DropzoneFile, url: string, callback?: ( ...any ) => any ): any; + createThumbnail( file: DropzoneFile, callback?: (...any: any[]) => {}): any; + createThumbnailFromUrl( file: DropzoneFile, url: string, callback?: ( ...any: any[] ) => any ): any; - emit( eventName: string, file: DropzoneFile, str?: string ); - emit( eventName: "thumbnail", file: DropzoneFile, path: string ); - emit( eventName: "addedfile", file: DropzoneFile ); - emit( eventName: "removedfile", file: DropzoneFile ); - emit( eventName: "processing", file: DropzoneFile ); - emit( eventName: "canceled", file: DropzoneFile ); - emit( eventName: "complete", file: DropzoneFile ); + emit( eventName: string, file: DropzoneFile, str?: string ): void; + emit( eventName: "thumbnail", file: DropzoneFile, path: string ): void; + emit( eventName: "addedfile", file: DropzoneFile ): void; + emit( eventName: "removedfile", file: DropzoneFile ): void; + emit( eventName: "processing", file: DropzoneFile ): void; + emit( eventName: "canceled", file: DropzoneFile ): void; + emit( eventName: "complete", file: DropzoneFile ): void; - emit( eventName: string, e: Event ); - emit( eventName: "drop", e: Event ); - emit( eventName: "dragstart", e: Event ); - emit( eventName: "dragend", e: Event ); - emit( eventName: "dragenter", e: Event ); - emit( eventName: "dragover", e: Event ); - emit( eventName: "dragleave", e: Event ); + emit( eventName: string, e: Event ): void; + emit( eventName: "drop", e: Event ): void; + emit( eventName: "dragstart", e: Event ): void; + emit( eventName: "dragend", e: Event ): void; + emit( eventName: "dragenter", e: Event ): void; + emit( eventName: "dragover", e: Event ): void; + emit( eventName: "dragleave", e: Event ): void; } interface JQuery { From 7d8e08c9b53ecba5e8988ea5cd386d0eadd322df Mon Sep 17 00:00:00 2001 From: "chocolatechipui@sourcebits.com" Date: Fri, 21 Aug 2015 15:42:09 -0700 Subject: [PATCH 126/173] Updated types for ChocolateChipJS to 4.0.3. Updated types to match refactored versions of "prop" and "removeProp". --- chocolatechipjs/chocolatechipjs-tests.ts | 6 ++++-- chocolatechipjs/chocolatechipjs.d.ts | 25 +++++++++++++++--------- 2 files changed, 20 insertions(+), 11 deletions(-) diff --git a/chocolatechipjs/chocolatechipjs-tests.ts b/chocolatechipjs/chocolatechipjs-tests.ts index 06b581769..111e69f63 100644 --- a/chocolatechipjs/chocolatechipjs-tests.ts +++ b/chocolatechipjs/chocolatechipjs-tests.ts @@ -102,12 +102,14 @@ $('ul').insert("
  • 1
  • 2
  • 3
  • ", 3); $('ul').insert("
  • 1
  • 2
  • 3
  • "); $('ul').html('
  • 1
  • <2/li>
  • 3
  • '); $('ul').html(''); +var listContent = $('ul').html(); $('ul').prepend('
  • The title
  • '); $('ul').append('
  • The Last Item
  • '); var inputName = $('input').attr('name'); $('input').attr('name', 'wobba'); -var inputName = $('input').prop('name'); -$('input').prop('name', 'wobba'); +var inputProperty = $('input').prop('disabled'); +$('input[type=checked]').prop('checked', true); +$('input').removeProp('disabled'); $('input').hasAttr('disabled').css('border', 'solid 1px red'); $('input').removeAttr('disabled'); $('article').hasClass('current').css('display', 'block'); diff --git a/chocolatechipjs/chocolatechipjs.d.ts b/chocolatechipjs/chocolatechipjs.d.ts index 3c84558af..6a45863b0 100644 --- a/chocolatechipjs/chocolatechipjs.d.ts +++ b/chocolatechipjs/chocolatechipjs.d.ts @@ -1,4 +1,4 @@ -// Type definitions for chocolatechip v4.0.2 +// Type definitions for chocolatechip v4.0.3 // Project: https://github.com/chocolatechipui/ChocolateChipJS // Definitions by: Robert Biggs // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -176,7 +176,8 @@ interface ChocolateChipStatic { * @param response The response from a Promise. * @result */ - json(reponse: Response): JSON; + json(reponse: Response): JSON; + /** * This method will defer the execution of a function until the call stack is clear. * @@ -198,7 +199,7 @@ interface ChocolateChipStatic { * This method makes sure a method always returns an array. If no values are available to return, it returns and empty array. This is to make sure that methods that expect a chainable array will not throw and exception. * * @param result The result of a method to test if it can be returned in an array. - * @return An array hold the results of a method, otherwise an empty array. + * @return An array holding the results of a method, otherwise an empty array. */ returnResult(result: HTMLElement[]): any[]; @@ -836,12 +837,12 @@ interface ChocolateChipElementArray extends Array { hasAttr(attributeName: string): ChocolateChipElementArray; /** - * Get the value of an attribute for the first element in the set of matched elements. + * Test whether an attribute exists on the first element in the set of matched elements. The value returned is a boolean. * * @param attributeName The name of the attribute to get. - * @return string + * @return boolean */ - prop(attributeName: string): string; + prop(propertyName: string): boolean; /** * Set an property for the set of matched elements. @@ -850,7 +851,15 @@ interface ChocolateChipElementArray extends Array { * @param value A string indicating the value to set the property to. * @return HTMLElement[] */ - prop(propertyName: string, value: string): ChocolateChipElementArray; + prop(propertyName: string, value: any | boolean): ChocolateChipElementArray; + + /** + * Remove an element property. + * + * @param property The property to remove. + * @return HTMLElement[] + */ + removeProp(property: string): ChocolateChipElementArray; /** * Adds the specified class(es) to each of the set of matched elements. @@ -1471,5 +1480,3 @@ interface Window { } declare var $: ChocolateChipStatic; declare var fetch: fetch; - -declare var chocolatechipjs: ChocolateChipStatic; \ No newline at end of file From 85a7ed0fec48ed5e3c0ba85faf91b4b7f6d311eb Mon Sep 17 00:00:00 2001 From: Scott Southwood Date: Fri, 21 Aug 2015 16:21:59 -0700 Subject: [PATCH 127/173] update to version 0.15.5 --- applicationinsights/applicationinsights.d.ts | 40 ++++++++++++++++++-- 1 file changed, 36 insertions(+), 4 deletions(-) diff --git a/applicationinsights/applicationinsights.d.ts b/applicationinsights/applicationinsights.d.ts index 6b80adc2a..12dffdd81 100644 --- a/applicationinsights/applicationinsights.d.ts +++ b/applicationinsights/applicationinsights.d.ts @@ -4,21 +4,25 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped interface AutoCollectConsole { + constructor(client: Client): AutoCollectConsole; enable(isEnabled: boolean): void; isInitialized(): boolean; } interface AutoCollectExceptions { + constructor(client:Client): AutoCollectExceptions; isInitialized(): boolean; enable(isEnabled:boolean): void; } interface AutoCollectPerformance { + constructor(client: Client): AutoCollectPerformance; enable(isEnabled: boolean): void; isInitialized(): boolean; } interface AutoCollectRequests { + constructor(client: Client): AutoCollectRequests; enable(isEnabled: boolean): void; isInitialized(): boolean; } @@ -85,14 +89,17 @@ declare module ContractsModule { sampleRate: string; internalSdkVersion: string; internalAgentVersion: string; + constructor(): ContextTagKeys; } interface Domain { ver: number; properties: any; + constructor(): Domain; } interface Data { baseType: string; baseData: TDomain; + constructor(): Data; } interface Envelope { ver: number; @@ -112,18 +119,21 @@ declare module ContractsModule { [key: string]: string; }; data: Data; + constructor(): Envelope; } interface EventData extends ContractsModule.Domain { ver: number; name: string; properties: any; measurements: any; + constructor(): EventData; } interface MessageData extends ContractsModule.Domain { ver: number; message: string; severityLevel: ContractsModule.SeverityLevel; properties: any; + constructor(): MessageData; } interface ExceptionData extends ContractsModule.Domain { ver: number; @@ -134,6 +144,7 @@ declare module ContractsModule { crashThreadId: number; properties: any; measurements: any; + constructor(): ExceptionData; } interface StackFrame { level: number; @@ -141,6 +152,7 @@ declare module ContractsModule { assembly: string; fileName: string; line: number; + constructor(): StackFrame; } interface ExceptionDetails { id: number; @@ -150,6 +162,7 @@ declare module ContractsModule { hasFullStack: boolean; stack: string; parsedStack: StackFrame[]; + constructor(): ExceptionDetails; } interface DataPoint { name: string; @@ -159,11 +172,13 @@ declare module ContractsModule { min: number; max: number; stdDev: number; + constructor(): DataPoint; } interface MetricData extends ContractsModule.Domain { ver: number; metrics: DataPoint[]; properties: any; + constructor(): MetricData; } interface PageViewData extends ContractsModule.EventData { ver: number; @@ -172,6 +187,7 @@ declare module ContractsModule { duration: string; properties: any; measurements: any; + constructor(): PageViewData; } interface PageViewPerfData extends ContractsModule.PageViewData { ver: number; @@ -185,6 +201,7 @@ declare module ContractsModule { domProcessing: string; properties: any; measurements: any; + constructor(): PageViewPerfData; } interface RemoteDependencyData extends ContractsModule.Domain { ver: number; @@ -202,6 +219,7 @@ declare module ContractsModule { commandName: string; dependencyTypeName: string; properties: any; + constructor(): RemoteDependencyData; } interface AjaxCallData extends ContractsModule.PageViewData { ver: number; @@ -218,6 +236,7 @@ declare module ContractsModule { success: boolean; properties: any; measurements: any; + constructor(): AjaxCallData; } interface RequestData extends ContractsModule.Domain { ver: number; @@ -231,10 +250,12 @@ declare module ContractsModule { url: string; properties: any; measurements: any; + constructor(): RequestData; } interface SessionStateData extends ContractsModule.Domain { ver: number; state: ContractsModule.SessionState; + constructor(): SessionStateData; } interface PerformanceCounterData extends ContractsModule.Domain { ver: number; @@ -248,6 +269,7 @@ declare module ContractsModule { stdDev: number; value: number; properties: any; + constructor(): PerformanceCounterData; } } @@ -309,10 +331,14 @@ interface Client { * Log a numeric value that is not associated with a specific event. Typically used to send regular reports of performance indicators. * To send a single measurement, use just the first two parameters. If you take measurements very frequently, you can reduce the * telemetry bandwidth by aggregating multiple measurements and sending the resulting average at intervals. - * @param name A string that identifies the metric. - * @param value The value of the metric + * @param name A string that identifies the metric. + * @param value The value of the metric + * @param count the number of samples used to get this value + * @param min the min sample for this set + * @param max the max sample for this set + * @param stdDev the standard deviation of the set */ - trackMetric(name: string, value: number): void; + trackMetric(name: string, value: number, count?:number, min?: number, max?: number, stdDev?: number): void; trackRequest(request: any /* http.ServerRequest */, response: any /* http.ServerResponse */, properties?: { [key: string]: string; }): void; @@ -381,10 +407,16 @@ declare class ApplicationInsights { private static _performance; private static _requests; private static _isStarted; + /** + * Initializes a client with the given instrumentation key, if this is not specified, the value will be + * read from the environment variable APPINSIGHTS_INSTRUMENTATIONKEY + * @returns {ApplicationInsights/Client} a new client + */ + static getClient(instrumentationKey?: string): Client; /** * Initializes the default client of the client and sets the default configuration * @param instrumentationKey the instrumentation key to use. Optional, if this is not specified, the value will be - * read from the environment variable APPINSIGHTS_INSTRUMENTATION_KEY + * read from the environment variable APPINSIGHTS_INSTRUMENTATIONKEY * @returns {ApplicationInsights} this interface */ static setup(instrumentationKey?: string): typeof ApplicationInsights; From 35380afde2b007834344b6d1c9213ca8ab9369d3 Mon Sep 17 00:00:00 2001 From: Scott Southwood Date: Fri, 21 Aug 2015 17:13:02 -0700 Subject: [PATCH 128/173] adding definitions for project oxford --- project-oxford/project-oxford-tests.ts | 480 +++++++++++++++++++++++ project-oxford/project-oxford.d.ts | 522 +++++++++++++++++++++++++ 2 files changed, 1002 insertions(+) create mode 100644 project-oxford/project-oxford-tests.ts create mode 100644 project-oxford/project-oxford.d.ts diff --git a/project-oxford/project-oxford-tests.ts b/project-oxford/project-oxford-tests.ts new file mode 100644 index 000000000..3d662d504 --- /dev/null +++ b/project-oxford/project-oxford-tests.ts @@ -0,0 +1,480 @@ +/// +/// +/// +/// + +import oxford = require("project-oxford"); + +import assert = require('assert'); +import _Promise = require('bluebird'); +import fs = require('fs'); + +var client = new oxford.Client(process.env.OXFORD_KEY); + +// Store variables, no point in calling the api too often +var billFaces = []; +var personGroupId = "uuid.v4()"; +var personGroupId2 = "uuid.v4()"; +var billPersonId: string; + +describe('Project Oxford Face API Test', function () { + afterEach(function() { + // delay after each test to prevent throttling + var now = +new Date() + 250; + while(now > +new Date()); + }); + + describe('#detect()', function () { + it('detects a face in a stream', function (done) { + client.face.detect({ + stream: fs.createReadStream('./test/images/face1.jpg'), + analyzesFaceLandmarks: true, + analyzesAge: true, + analyzesGender: true, + analyzesHeadPose: true + }).then(function (response) { + assert.ok(response[0].faceId); + assert.ok(response[0].faceRectangle); + assert.ok(response[0].faceLandmarks); + assert.ok(response[0].attributes.gender); + assert.ok(response[0].attributes.headPose); + + assert.equal(response[0].attributes.gender, 'male'); + done(); + }); + }); + + it('detects a face in a local file', function (done) { + client.face.detect({ + path: './test/images/face1.jpg', + analyzesFaceLandmarks: true, + analyzesAge: true, + analyzesGender: true, + analyzesHeadPose: true + }).then(function (response) { + assert.ok(response[0].faceId); + assert.ok(response[0].faceRectangle); + assert.ok(response[0].faceLandmarks); + assert.ok(response[0].attributes.gender); + assert.ok(response[0].attributes.headPose); + + assert.equal(response[0].attributes.gender, 'male'); + done(); + }); + }); + + it('detects a face in a remote file', function (done) { + client.face.detect({ + url: 'https://upload.wikimedia.org/wikipedia/commons/1/19/Bill_Gates_June_2015.jpg', + analyzesFaceLandmarks: true, + analyzesAge: true, + analyzesGender: true, + analyzesHeadPose: true + }).then(function (response) { + assert.ok(response[0].faceId); + assert.ok(response[0].faceRectangle); + assert.ok(response[0].faceLandmarks); + assert.ok(response[0].attributes.gender); + assert.ok(response[0].attributes.headPose); + + assert.equal(response[0].attributes.gender, 'male'); + done(); + }); + }); + }); + + describe('#similar()', function () { + it('detects similar faces', function (done) { + var detects = []; + + this.timeout(10000); + + detects.push(client.face.detect({ + path: './test/images/face1.jpg', + }).then(function(response) { + assert.ok(response[0].faceId) + billFaces.push(response[0].faceId); + })); + + detects.push(client.face.detect({ + path: './test/images/face2.jpg', + }).then(function(response) { + assert.ok(response[0].faceId) + billFaces.push(response[0].faceId); + })); + + _Promise.all(detects).then(function() { + client.face.similar(billFaces[0], [billFaces[1]]).then(function(response) { + done(); + }); + }); + }); + }); + + describe('#grouping()', function () { + it('detects groups faces', function (done) { + var faceIds = []; + + this.timeout(10000); + + client.face.detect({ + path: './test/images/face-group.jpg', + }).then(function(response) { + response.forEach(function (face) { + faceIds.push(face.faceId); + }); + + assert.equal(faceIds.length, 6); + }).then(function() { + client.face.grouping(faceIds).then(function (response) { + assert.ok(response.messyGroup); + done(); + }); + }); + }); + }); + + describe('#verify()', function () { + it('verifies a face against another face', function (done) { + this.timeout(10000); + + assert.equal(billFaces.length, 2); + + client.face.verify(billFaces).then(function (response) { + assert.ok(response); + assert.ok((response.isIdentical === true || response.isIdentical === false)); + assert.ok(response.confidence); + done(); + }); + }); + }); + + describe('#PersonGroup', function () { + before(function(done) { + this.timeout(5000); + // In order to test the + // training feature, we have to start trainign - sadly, we can't + // delete the group then. So we clean up before we run tests - and to wait + // for cleanup to finish, we're just using done(). + client.face.personGroup.list().then(function (response) { + var promises = []; + + response.forEach(function (personGroup) { + if (personGroup.name.indexOf('po-node-test-group') > -1) { + promises.push(client.face.personGroup.delete(personGroup.personGroupId)); + } + }); + + _Promise.all(promises).then(function () { + done(); + }); + }); + }); + + it('creates a PersonGroup', function (done) { + client.face.personGroup.create(personGroupId, 'po-node-test-group', 'test-data').then(function (response) { + assert.ok(true, "void response expected"); + done(); + }) + .catch(function (error) { + assert.ok(false, JSON.stringify(error)); + done(); + }); + }); + + it('lists PersonGroups', function (done) { + client.face.personGroup.list().then(function (response) { + assert.ok(response); + assert.ok((response.length > 0)); + assert.ok(response[0].personGroupId); + done(); + }); + }); + + it('gets a PersonGroup', function (done) { + client.face.personGroup.get(personGroupId).then(function (response) { + assert.equal(response.personGroupId, personGroupId); + assert.equal(response.name, 'po-node-test-group'); + assert.equal(response.userData, 'test-data'); + done(); + }); + }); + + it('updates a PersonGroup', function (done) { + client.face.personGroup.update(personGroupId, 'po-node-test-group2', 'test-data2').then(function (response) { + assert.ok(true, "void response expected");; + done(); + }).catch(function (response) { + assert.equal(response, 'PersonGroupTrainingNotFinished') + }); + }); + + it('gets a PersonGroup\'s training status', function (done) { + client.face.personGroup.trainingStatus(personGroupId).then(function (response) { + done(); + }).catch(function (response) { + assert.equal(response.code, 'PersonGroupNotTrained'); + done(); + }); + }); + + it('starts a PersonGroup\'s training', function (done) { + client.face.personGroup.trainingStart(personGroupId).then(function (response) { + assert.equal(response.status, 'running'); + done(); + }).catch(function (response) { + assert.equal(response.status, 'running'); + done(); + }); + }); + + it('deletes a PersonGroup', function (done) { + client.face.personGroup.delete(personGroupId).then(function (response) { + assert.ok(true, "void response"); + done(); + }).catch(function (response) { + assert.equal(response.code, 'PersonGroupTrainingNotFinished'); + done(); + }); + }); + }); + + describe('#Person', function () { + + it('creates a PersonGroup for the Person', function (done) { + client.face.personGroup.create(personGroupId2, 'po-node-test-group', 'test-data') + .then(function (response) { + assert.ok(true, "void response expected"); + done(); + }) + .catch(function (error) { + assert.ok(false, JSON.stringify(error)); + done(); + }); + }); + + it('creates a Person', function (done) { + client.face.person.create(personGroupId2, [billFaces[0]], 'test-bill', 'test-data') + .then(function (response) { + assert.ok(response.personId); + billPersonId = response.personId; + done(); + }) + .catch(function (error) { + assert.ok(false, JSON.stringify(error)); + done(); + }); + }); + + it('gets a Person', function (done) { + client.face.person.get(personGroupId2, billPersonId).then(function (response) { + assert.ok(response.personId); + done(); + }) + .catch(function (error) { + assert.ok(false, JSON.stringify(error)); + done(); + }); + }); + + it('updates a Person', function (done) { + client.face.person.update(personGroupId2, billPersonId, [billFaces[0]], 'test-bill', 'test-data') + .then(function (response) { + assert.ok(true, "void response expected"); + done(); + }) + }); + + it('adds a face to a Person', function (done) { + client.face.person.addFace(personGroupId2, billPersonId, billFaces[1], 'test-data') + .then(function (response) { + assert.ok(true, "void response expected"); + done(); + }) + .catch(function (error) { + assert.ok(false, JSON.stringify(error)); + done(); + }); + }); + + it('gets a face from a Person', function (done) { + client.face.person.getFace(personGroupId2, billPersonId, billFaces[1]) + .then(function (response) { + assert.ok(response.userData); + assert.equal(response.userData, 'test-data'); + done(); + }) + .catch(function (error) { + assert.ok(false, JSON.stringify(error)); + done(); + }); + }); + + it('updates a face on a Person', function (done) { + client.face.person.updateFace(personGroupId2, billPersonId, billFaces[1], 'test-data') + .then(function (response) { + assert.ok(true, "void response expected"); + done(); + }) + .catch(function (error) { + assert.ok(false, JSON.stringify(error)); + done(); + }); + }); + + it('deletes a face on a Person', function (done) { + client.face.person.deleteFace(personGroupId2, billPersonId, billFaces[1]) + .then(function (response) { + assert.ok(true, "void response expected"); + done(); + }) + .catch(function (error) { + assert.ok(false, JSON.stringify(error)); + done(); + }); + }); + + it('lists Persons', function (done) { + client.face.person.list(personGroupId2) + .then(function (response) { + assert.ok(response[0].personId); + done(); + }) + .catch(function (error) { + assert.ok(false, JSON.stringify(error)); + done(); + }); + }); + + it('deletes a Person', function (done) { + client.face.person.delete(personGroupId2, billPersonId) + .then(function (response) { + assert.ok(true, "void response expected"); + done(); + }) + .catch(function (error) { + assert.ok(false, JSON.stringify(error)); + done(); + }); + }); + }); +}); + +describe('Project Oxford Vision API Test', function () { + before(function() { + // ensure the output directory exists + if(!fs.existsSync('./test/output')){ + fs.mkdirSync('./test/output', 0766); + } + }); + + afterEach(function() { + // delay after each test to prevent throttling + var now = +new Date() + 250; + while(now > +new Date()); + }); + + it('analyzes a local image', function (done) { + this.timeout(10000); + client.vision.analyzeImage({ + path: './test/images/vision.jpg', + ImageType: true, + Color: true, + Faces: true, + Adult: true, + Categories: true + }) + .then(function (response) { + assert.ok(response); + assert.ok(response.categories); + assert.ok(response.adult); + assert.ok(response.metadata); + assert.ok(response.faces); + assert.ok(response.color); + assert.ok(response.imageType); + done(); + }) + }); + + it('analyzes an online image', function (done) { + this.timeout(10000); + client.vision.analyzeImage({ + url: 'https://upload.wikimedia.org/wikipedia/commons/1/19/Bill_Gates_June_2015.jpg', + ImageType: true, + Color: true, + Faces: true, + Adult: true, + Categories: true + }) + .then(function (response) { + assert.ok(response); + assert.ok(response.categories); + assert.ok(response.adult); + assert.ok(response.metadata); + assert.ok(response.faces); + assert.ok(response.color); + assert.ok(response.imageType); + done(); + }); + }); + + it('creates a thumbnail for a local image', function (done) { + this.timeout(10000); + client.vision.thumbnail({ + path: './test/images/vision.jpg', + pipe: fs.createWriteStream('./test/output/thumb2.jpg'), + width: 100, + height: 100, + smartCropping: true + }) + .then(function (response) { + var stats = fs.statSync('./test/output/thumb2.jpg'); + assert.ok((stats.size > 0)); + done(); + }); + }); + + it('creates a thumbnail for an online image', function (done) { + this.timeout(10000); + client.vision.thumbnail({ + url: 'https://upload.wikimedia.org/wikipedia/commons/1/19/Bill_Gates_June_2015.jpg', + pipe: fs.createWriteStream('./test/output/thumb1.jpg'), + width: 100, + height: 100, + smartCropping: true + }) + .then(function (response) { + var stats = fs.statSync('./test/output/thumb1.jpg'); + assert.ok((stats.size > 0)); + done(); + }); + }); + + it('runs OCR on a local image', function (done) { + this.timeout(10000); + client.vision.ocr({ + path: './test/images/vision.jpg', + language: 'en', + detectOrientation: true + }) + .then(function (response) { + assert.ok(response.language); + assert.ok(response.regions); + done(); + }); + }); + + it('runs OCR on an online image', function (done) { + this.timeout(10000); + client.vision.ocr({ + url: 'https://upload.wikimedia.org/wikipedia/commons/1/19/Bill_Gates_June_2015.jpg', + language: 'en', + detectOrientation: true + }) + .then(function (response) { + assert.ok(response.language); + assert.ok(response.orientation); + done(); + }); + }); +}); \ No newline at end of file diff --git a/project-oxford/project-oxford.d.ts b/project-oxford/project-oxford.d.ts new file mode 100644 index 000000000..dffecc361 --- /dev/null +++ b/project-oxford/project-oxford.d.ts @@ -0,0 +1,522 @@ +// Type definitions for project-oxford v0.1.3 +// Project: https://github.com/felixrieseberg/project-oxford +// Definitions by: Scott Southwood +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare module "project-oxford" { + import Promise = require("bluebird"); + import stream = require("stream"); + + export class Client { + constructor(apiKey: string); + private _key: string; + public face: FaceAPI; + public vision: VisionAPI; + } + + export class FaceAPI { + + /** + * Call the Face Detected API + * Detects human faces in an image and returns face locations, face landmarks, and + * optional attributes including head-pose, gender, and age. Detection is an essential + * API that provides faceId to other APIs like Identification, Verification, + * and Find Similar. + * + * @param {object} options - Options object + * @param {string} options.url - URL to image to be used + * @param {string} options.path - Path to image to be used + * @param {stream} options.stream - Stream for image to be used + * @param {boolean} options.analyzesFaceLandmarks - Analyze face landmarks? + * @param {boolean} options.analyzesAge - Analyze age? + * @param {boolean} options.analyzesGender - Analyze gender? + * @param {boolean} options.analyzesHeadPose - Analyze headpose? + * @return {Promise} - Promise resolving with the resulting JSON + */ + public detect(options: Options.Detect): Promise<[FaceResponses.Detect]>; + + /** + * Detect similar faces using faceIds (as returned from the detect API) + * @param {string} sourceFace - String of faceId for the source face + * @param {string[]} candidateFaces - Array of faceIds to use as candidates + * @return {Promise} - Promise resolving with the resulting JSON + */ + public similar(sourceFaceId: string, candidateFacesIds: string[]): Promise; + + /** + * Divides candidate faces into groups based on face similarity using faceIds. + * The output is one or more disjointed face groups and a MessyGroup. + * A face group contains the faces that have similar looking, often of the same person. + * There will be one or more face groups ranked by group size, i.e. number of face. + * Faces belonging to the same person might be split into several groups in the result. + * The MessyGroup is a special face group that each face is not similar to any other + * faces in original candidate faces. The messyGroup will not appear in the result if + * all faces found their similar counterparts. The candidate face list has a + * limit of 100 faces. + * + * @param {string[]} faces - Array of faceIds to use + * @return {Promise} - Promise resolving with the resulting JSON + */ + public grouping(faces: string[]): Promise; + + /** + * Identifies persons from a person group by one or more input faces. + * To recognize which person a face belongs to, Face Identification needs a person group + * that contains number of persons. Each person contains one or more faces. After a person + * group prepared, it should be trained to make it ready for identification. Then the + * identification API compares the input face to those persons' faces in person group and + * returns the best-matched candidate persons, ranked by confidence. + * + * @param {string[]} faces - Array of faceIds to use + * @return {Promise} - Promise resolving with the resulting JSON + */ + public identify(faceIDs: string[], options: Options.Identify): Promise; + + /** + * Analyzes two faces and determine whether they are from the same person. + * Verification works well for frontal and near-frontal faces. + * For the scenarios that are sensitive to accuracy please use with own judgment. + * @param {string[]} faces - Array containing two faceIds to use + * @return {Promise} - Promise resolving with the resulting JSON + */ + public verify(faces: string[]): Promise; + + /** + * @namespace + * @memberof face + */ + public personGroup: PersonGroup; + public person: Person; + } + + export class VisionAPI { + /** + * This operation does a deep analysis on the given image and then extracts a + * set of rich visual features based on the image content. + * + * @param {Object} options - Options object describing features to extract + * @param {string} options.url - Url to image to be analyzed + * @param {string} options.path - Path to image to be analyzed + * @param {boolean} options.ImageType - Detects if image is clipart or a line drawing. + * @param {boolean} options.Color - Determines the accent color, dominant color, if image is black&white. + * @param {boolean} options.Faces - Detects if faces are present. If present, generate coordinates, gender and age. + * @param {boolean} options.Adult - Detects if image is pornographic in nature (nudity or sex act). Sexually suggestive content is also detected. + * @param {boolean} options.Categories - Image categorization; taxonomy defined in documentation. + * @return {Promise} - Promise resolving with the resulting JSON + */ + public analyzeImage(options: Options.Analyze): Promise; + + /** + * Generate a thumbnail image to the user-specified width and height. By default, the + * service analyzes the image, identifies the region of interest (ROI), and generates + * smart crop coordinates based on the ROI. Smart cropping is designed to help when you + * specify an aspect ratio that differs from the input image. + * + * @param {Object} options - Options object describing features to extract + * @param {string} options.url - Url to image to be thumbnailed + * @param {string} options.path - Path to image to be thumbnailed + * @param {number} options.width - Width of the thumb in pixels + * @param {number} options.height - Height of the thumb in pixels + * @param {boolean} options.smartCropping - Should SmartCropping be enabled? + * @param {Object} options.pipe - We'll pipe the returned image to this object + * @return {Promise} - Promise resolving with the resulting JSON + */ + public thumbnail(options: Options.Thumbnail): Promise; + + /** + * Optical Character Recognition (OCR) detects text in an image and extracts the recognized + * characters into a machine-usable character stream. + * + * @param {Object} options - Options object describing features to extract + * @param {string} options.url - Url to image to be analyzed + * @param {string} options.path - Path to image to be analyzed + * @param {string} options.language - BCP-47 language code of the text to be detected in the image. Default value is "unk", then the service will auto detect the language of the text in the image. + * @param {string} options.detectOrientation - Detect orientation of text in the image + * @return {Promise} - Promise resolving with the resulting JSON + */ + public ocr(options: Options.Ocr): Promise; + } + + export class PersonGroup { + /** + * Creates a new person group with a user-specified ID. + * A person group is one of the most important parameters for the Identification API. + * The Identification searches person faces in a specified person group. + * + * @param {string} personGroupId - Numbers, en-us letters in lower case, '-', '_'. Max length: 64 + * @param {string} name - Person group display name. The maximum length is 128. + * @param {string} userData - User-provided data attached to the group. The size limit is 16KB. + * @return {Promise} - Promise resolving with the resulting JSON + */ + public create(personGroupId: string, name: string, userData: string): Promise; + + /** + * Deletes an existing person group. + * + * @param {string} personGroupId - Name of person group to delete + * @return {Promise} - Promise resolving with the resulting JSON + */ + public delete(personGroupId: string): Promise; + + /** + * Gets an existing person group. + * + * @param {string} personGroupId - Name of person group to get + * @return {Promise} - Promise resolving with the resulting JSON + */ + public get(personGroupId: string): Promise; + + /** + * Retrieves the training status of a person group. Training is triggered by the Train PersonGroup API. + * The training will process for a while on the server side. This API can query whether the training + * is completed or ongoing. + * + * @param {string} personGroupId - Name of person group to get + * @return {Promise} - Promise resolving with the resulting JSON + */ + public trainingStatus(personGroupId: string): Promise; + + /** + * Starts a person group training. + * Training is a necessary preparation process of a person group before identification. + * Each person group needs to be trained in order to call Identification. The training + * will process for a while on the server side even after this API has responded. + * + * @param {string} personGroupId - Name of person group to get + * @return {Promise} - Promise resolving with the resulting JSON + */ + public trainingStart(personGroupId: string): Promise; + + /** + * Updates an existing person group's display name and userData. + * + * @param {string} personGroupId - Numbers, en-us letters in lower case, '-', '_'. Max length: 64 + * @param {string} name - Person group display name. The maximum length is 128. + * @param {string} userData - User-provided data attached to the group. The size limit is 16KB. + * @return {Promise} - Promise resolving with the resulting JSON + */ + public update(personGroupId: string, name: string, userData: string): Promise; + + /** + * Lists all person groups in the current subscription. + * @return {Promise} - Promise resolving with the resulting JSON + */ + public list(): Promise; + } + + export class Person { + /** + * Adds a face to a person for identification. The maximum face count for each person is 32. + * The face ID must be added to a person before its expiration. Typically a face ID expires + * 24 hours after detection. + * + * @param {string} personGroupId - The target person's person group. + * @param {string} personId - The target person that the face is added to. + * @param {string} faceId - The ID of the face to be added. The maximum face amount for each person is 32. + * @param {string} userData - Optional. Attach user data to person's face. The maximum length is 1024. + * @return {Promise} - Promise resolving with the resulting JSON + */ + public addFace(personGroupId: string, personId: string, faceId: string, userData?: string): Promise; + + /** + * Deletes a face from a person. + * + * @param {string} personGroupId - The target person's person group. + * @param {string} personId - The target person that the face is removed from. + * @param {string} faceId - The ID of the face to be deleted. + * @return {Promise} - Promise resolving with the resulting JSON + */ + public deleteFace(personGroupId: string, personId: string, faceId: string): Promise; + + /** + * Updates a face for a person. + * + * @param {string} personGroupId - The target person's person group. + * @param {string} personId - The target person that the face is updated on. + * @param {string} faceId - The ID of the face to be updated. + * @param {string} userData - Optional. Attach user data to person's face. The maximum length is 1024. + * @return {Promise} - Promise resolving with the resulting JSON + */ + public updateFace(personGroupId: string, personId: string, faceId: string, userData: string): Promise; + + /** + * Get a face for a person. + * + * @param {string} personGroupId - The target person's person group. + * @param {string} personId - The target person that the face is to get from. + * @param {string} faceId - The ID of the face to get. + * @return {Promise} - Promise resolving with the resulting JSON + */ + public getFace(personGroupId: string, personId: string, faceId: string): Promise; + + /** + * Creates a new person in a specified person group for identification. + * The number of persons has a subscription limit. Free subscription amount is 1000 persons. + * The maximum face count for each person is 32. + * + * @param {string} personGroupId - The target person's person group. + * @param {string[]} faces - Array of face id's for the target person + * @param {string} name - Target person's display name. The maximum length is 128. + * @param {string} userData - Optional fields for user-provided data attached to a person. Size limit is 16KB. + * @return {Promise} - Promise resolving with the resulting JSON + */ + public create(personGroupId: string, faces: string[], name: string, userData: string): Promise<{ personId: string }>; + + /** + * Deletes an existing person from a person group. + * + * @param {string} personGroupId - The target person's person group. + * @param {string} personId - The target person to delete. + * @return {Promise} - Promise resolving with the resulting JSON + */ + public delete(personGroupId: string, personId: string): Promise; + + /** + * Gets an existing person from a person group. + * + * @param {string} personGroupId - The target person's person group. + * @param {string} personId - The target person to get. + * @return {Promise} - Promise resolving with the resulting JSON + */ + public get(personGroupId: string, personId: string): Promise; + + /** + * Updates a person's information. + * + * @param {string} personGroupId - The target person's person group. + * @param {string[]} faces - Array of face id's for the target person + * @param {string} name - Target person's display name. The maximum length is 128. + * @param {string} userData - Optional fields for user-provided data attached to a person. Size limit is 16KB. + * @return {Promise} - Promise resolving with the resulting JSON + */ + public update(personGroupId: string, personId: string, faces: string[], name: string, userData: string): Promise; + + /** + * Lists all persons in a person group, with the person information. + * + * @param {string} personGroupId - The target person's person group. + * @return {Promise} - Promise resolving with the resulting JSON + */ + public list(personGroupId: string): Promise; + } + + module Options { + interface Detect { + url?: string; // URL to image to be used + path?: string; // Path to image to be used + stream?: stream.Stream; // Stream of an image to be used + analyzesFaceLandmarks?: boolean; // Analyze face landmarks? + analyzesAge?: boolean; // Analyze age? + analyzesGender?: boolean; // Analyze gender? + analyzesHeadPose?: boolean; //Analyze headpose? + } + + interface Identify { + personGroupId: string; + maxNumOfCandidatesReturned: number; // range is 1-10 + } + + interface Analyze { + url?: string; // Url to image to be analyzed + path?: string; // Path to image to be analyzed + ImageType?: boolean; // Detects if image is clipart or a line drawing. + Color?: boolean; // Determines the accent color, dominant color, if image is black& white. + Faces?: boolean; // Detects if faces are present.If present, generate coordinates, gender and age. + Adult?: boolean; // Detects if image is pornographic in nature(nudity or sex act).Sexually suggestive content is also detected. + Categories?: boolean; // Image categorization; taxonomy defined in documentation. + } + + interface Thumbnail { + url?: string; // Url to image to be thumbnailed + path?: string; // Path to image to be thumbnailed + width?: number; // Width of the thumb in pixels + height?: number; // Height of the thumb in pixels + smartCropping?: boolean; // Should SmartCropping be enabled? + pipe?: stream.Writable; // We'll pipe the returned image to this object + } + + interface Ocr { + url?: string; // URL to image to be analyzed + path?: string; // Path to image to be analyzed + language?: string; //BCP - 47 language code of the text to be detected in the image.Default value is "unk", then the service will auto detect the language of the text in the image. + detectOrientation?: boolean; // Detect orientation of text in the image + } + } + + module FaceResponses { + interface FaceRectangle { + top: number; + left: number; + width: number; + height: number; + } + + interface point { + x: number; + y: number; + } + + interface FaceLandmarks { + "pupilLeft": point; + "pupilRight": point; + "noseTip": point; + "mouthLeft": point; + "mouthRight": point; + "eyebrowLeftOuter": point; + "eyebrowLeftInner": point; + "eyeLeftOuter": point; + "eyeLeftTop": point; + "eyeLeftBottom": point; + "eyeLeftInner": point; + "eyebrowRightInner": point; + "eyebrowRightOuter": point; + "eyeRightInner": point; + "eyeRightTop": point; + "eyeRightBottom": point; + "eyeRightOuter": point; + "noseRootLeft": point; + "noseRootRight": point; + "noseLeftAlarTop": point; + "noseRightAlarTop": point; + "noseLeftAlarOutTip": point; + "noseRightAlarOutTip": point; + "upperLipTop": point; + "upperLipBottom": point; + "underLipTop": point; + "underLipBottom": point; + } + + interface Attributes { + "headPose": { "pitch": number, "roll": number, "yaw": number }; + "gender": string; + "age": number; + } + + export interface Detect { + "faceId": string; + "faceRectangle": FaceRectangle; + "faceLandmarks": FaceLandmarks; + "attributes": Attributes; + } + + export interface Similar { + "faceIds": string[]; + } + + export interface Grouping { + "groups": string[]; + "messyGroup": string[]; + } + + export interface Identify { + "faceId": string; + "candidates": [{ + personId: string; + confidence: number; + }]; + } + + export interface Verify { + "isIdentical": boolean; + "confidence": number; + } + } + + module PersonGroupResponses { + + export interface PersonGroup { + "personGroupId": string; + "name": string; + "userData": string; + } + + export interface TrainingStatus { + "personGroupId": string; + "status": string; + "startTime": string; + "endTime": string; + } + } + + module PersonResponses { + export interface Create { + "personId": string; + } + + export interface Person { + "personId": string; + "faceIds": string[]; + "name": string; + "userData": string; + } + + export interface Face { + "faceId": string; + "userData": string; + } + } + + module VisionResponses { + export interface Analyze { + "categories": [{ + "name": string; + "score": number; + }], + "adult": { + "isAdultContent": boolean; + "isRacyContent": boolean; + "adultScore": number; + "racyScore": number; + }, + "requestId": string; + "metadata": { + "width": number; + "height": number; + "format": string; + }, + "faces": [ + { + "age": number; + "gender": string; + "faceRectangle": { + "left": number; + "top": number; + "width": number; + "height": number; + } + } + ], + "color": { + "dominantColorForeground": string; + "dominantColorBackground": string; + "dominantColors": string[]; + "accentColor": string; + "isBWImg": boolean; + }, + "imageType": { + "clipArtType": number; + "lineDrawingType": number; + } + } + + + export interface Ocr { + "language": string; + "textAngle": number; + "orientation": string; + "regions": [{ + "boundingBox": string; + "lines": [{ + "boundingBox": string; + "words": [{ + "boundingBox": string; + "text": string; + }] + }] + }] + } + } +} \ No newline at end of file From 59797782303f5a2eeaede3dc2b1680ae1cb41179 Mon Sep 17 00:00:00 2001 From: Oguzhan Ergin Date: Sat, 22 Aug 2015 03:25:06 +0300 Subject: [PATCH 129/173] Added fs-ext tests --- fs-ext/fs-ext-tests.ts | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 fs-ext/fs-ext-tests.ts diff --git a/fs-ext/fs-ext-tests.ts b/fs-ext/fs-ext-tests.ts new file mode 100644 index 000000000..aba507c6d --- /dev/null +++ b/fs-ext/fs-ext-tests.ts @@ -0,0 +1,28 @@ +/// +/// + +import fs = require('fs-ext'); + +var num:number; +var str:string; + +//from node.js 'fs' module +fs.appendFileSync(str, "data"); + +fs.flock(num, str, (err)=>{ +}); +fs.flockSync(num, str); + +fs.fcntl(num, str, num, (err, res)=>{ +}); +fs.fcntl(num, str, (err, res)=>{ +}); +fs.fcntlSync(num, str, num); + +fs.seek(num, num, num, (err, pos)=>{ +}); +fs.seekSync(num, num, num); + +fs.utime(str, num, num, (err)=>{ +}); +fs.utimeSync(str, num, num); From 0871a4a59731d96e77bd4c41a6e025ca23378b96 Mon Sep 17 00:00:00 2001 From: zgmnkv Date: Sat, 22 Aug 2015 13:07:42 +0400 Subject: [PATCH 130/173] Added 'defaultFormat' to Moment.js definition --- moment/moment-node.d.ts | 2 ++ moment/moment-tests.ts | 2 ++ 2 files changed, 4 insertions(+) diff --git a/moment/moment-node.d.ts b/moment/moment-node.d.ts index 48f00ed98..b109893a3 100644 --- a/moment/moment-node.d.ts +++ b/moment/moment-node.d.ts @@ -467,6 +467,8 @@ declare module moment { */ ISO_8601(): void; + defaultFormat: string; + } } diff --git a/moment/moment-tests.ts b/moment/moment-tests.ts index 04c075352..29712c115 100644 --- a/moment/moment-tests.ts +++ b/moment/moment-tests.ts @@ -459,3 +459,5 @@ moment.locale('en', { }); console.log(moment.version); + +moment.defaultFormat = 'YYYY-MM-DD HH:mm'; From e78260ef9b39498a6a1bb513eeb4e0ba37203c25 Mon Sep 17 00:00:00 2001 From: Marcin Porebski Date: Sat, 22 Aug 2015 14:31:43 +0200 Subject: [PATCH 131/173] added empty module to string_score --- string_score/string_score.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/string_score/string_score.d.ts b/string_score/string_score.d.ts index 5e3ee05d5..6b3944c4e 100644 --- a/string_score/string_score.d.ts +++ b/string_score/string_score.d.ts @@ -3,6 +3,11 @@ // Definitions by: Marcin Porębski // Definitions: https://github.com/borisyankov/DefinitelyTyped +declare module "string_score" +{ + // nothing here as it's only extending the build in String class +} + interface String { score: (word: string, fuzzy?: number) => number; } From 762a789651c795de9a2669a812ec45dbaca3604a Mon Sep 17 00:00:00 2001 From: Aya Morisawa Date: Sun, 23 Aug 2015 00:20:29 +0900 Subject: [PATCH 132/173] Add gulp-dtsm.d.ts --- gulp-dtsm/gulp-dtsm-tests.ts | 11 +++++++++++ gulp-dtsm/gulp-dtsm.d.ts | 13 +++++++++++++ 2 files changed, 24 insertions(+) create mode 100644 gulp-dtsm/gulp-dtsm-tests.ts create mode 100644 gulp-dtsm/gulp-dtsm.d.ts diff --git a/gulp-dtsm/gulp-dtsm-tests.ts b/gulp-dtsm/gulp-dtsm-tests.ts new file mode 100644 index 000000000..f97f8705e --- /dev/null +++ b/gulp-dtsm/gulp-dtsm-tests.ts @@ -0,0 +1,11 @@ +/// +/// +/// + +import dtsm = require('gulp-dtsm'); +import gulp = require('gulp'); + +var stream: NodeJS.WritableStream = dtsm(); + +gulp.task('dtsm', () => gulp.src('./dtsm.json').pipe(dtsm())); + diff --git a/gulp-dtsm/gulp-dtsm.d.ts b/gulp-dtsm/gulp-dtsm.d.ts new file mode 100644 index 000000000..a8fe7878f --- /dev/null +++ b/gulp-dtsm/gulp-dtsm.d.ts @@ -0,0 +1,13 @@ +// Type definitions for gulp-dtsm 0.0.0 +// Project: https://github.com/9joneg/gulp-dtsm +// Definitions by: Aya Morisawa +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "gulp-dtsm" { + function dtsm(): NodeJS.WritableStream; + + export = dtsm; +} + From 06274a0a71092026b61d4cf764a0b84bbcf9bc97 Mon Sep 17 00:00:00 2001 From: TeamworkGuy2 Date: Sat, 22 Aug 2015 18:51:52 +0000 Subject: [PATCH 133/173] Added type definition for translate() 'options' parameter based on the source code from https://github.com/jamuhl/i18next/ --- i18next/i18next.d.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/i18next/i18next.d.ts b/i18next/i18next.d.ts index 060335af0..feb6658c8 100644 --- a/i18next/i18next.d.ts +++ b/i18next/i18next.d.ts @@ -17,6 +17,10 @@ interface IResourceStoreKey { [key: string]: any; } +interface I18nTranslateOptions extends I18nextOptions { + defaultValue?: any; // normally a string +} + interface I18nextOptions { lng?: string; // Default value: undefined load?: string; // Default value: 'all' @@ -108,8 +112,8 @@ interface I18nextStatic { load: (languages: string[], options: I18nextOptions, callback: (err: Error, store: IResourceStore) => void ) => void; postMissing: (language: string, namespace: string, key: string, defaultValue: any, languages: string[]) => void; }; - t(key: string, options?: any): string; - translate(key: string, options?: any): string; + t(key: string, options?: I18nTranslateOptions): string; + translate(key: string, options?: I18nTranslateOptions): string; exists(key: string, options?: any): boolean; } From 24e08c7acccd80a1a9b87df9d1307f71422035fd Mon Sep 17 00:00:00 2001 From: Necroskillz Date: Sat, 22 Aug 2015 23:00:53 +0200 Subject: [PATCH 134/173] Update minimist definition to 1.1.3 - Add indexer to ParsedArgs - Add new options and options types --- minimist/minimist-tests.ts | 15 +++++++++++++++ minimist/minimist.d.ts | 16 ++++++++++++---- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/minimist/minimist-tests.ts b/minimist/minimist-tests.ts index 1f714fd3e..2266d2739 100644 --- a/minimist/minimist-tests.ts +++ b/minimist/minimist-tests.ts @@ -9,8 +9,12 @@ var strArr: string[]; var args: string[]; var obj: minimist.ParsedArgs; var opts: Opts; +var arg: any; +opts.string = str; opts.string = strArr; +opts.boolean = true; +opts.boolean = str; opts.boolean = strArr; opts.alias = { foo: strArr @@ -21,8 +25,19 @@ opts.default = { opts.default = { foo: num }; +opts.unknown = (arg: string) => { + if(/xyz/.test(arg)){ + return true; + } + + return false; +}; +opts.stopEarly = true; +opts['--'] = true; obj = minimist(); obj = minimist(strArr); obj = minimist(strArr, opts); var remainingArgCount = obj._.length; + +arg = obj['foo']; diff --git a/minimist/minimist.d.ts b/minimist/minimist.d.ts index 98d0f37a8..abbc5f028 100644 --- a/minimist/minimist.d.ts +++ b/minimist/minimist.d.ts @@ -1,6 +1,6 @@ -// Type definitions for minimist 0.0.8 +// Type definitions for minimist 1.1.3 // Project: https://github.com/substack/minimist -// Definitions by: Bart van der Schoor +// Definitions by: Bart van der Schoor , Necroskillz // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module 'minimist' { @@ -10,18 +10,26 @@ declare module 'minimist' { export interface Opts { // a string or array of strings argument names to always treat as strings // string?: string; - string?: string[]; + string?: string|string[]; // a string or array of strings to always treat as booleans // boolean?: string; - boolean?: string[]; + boolean?: boolean|string|string[]; // an object mapping string names to strings or arrays of string argument names to use // alias?: {[key:string]: string}; alias?: {[key:string]: string[]}; // an object mapping string argument names to default values default?: {[key:string]: any}; + // when true, populate argv._ with everything after the first non-option + stopEarly?: boolean; + // a function which is invoked with a command line parameter not defined in the opts configuration object. + // If the function returns false, the unknown option is not added to argv + unknown?: (arg: string) => boolean; + // when true, populate argv._ with everything before the -- and argv['--'] with everything after the -- + '--'?: boolean; } export interface ParsedArgs { + [arg: string]: any; _: string[]; } } From f13c2224e8fd065961b595b9dfa9d0dacfe56eb8 Mon Sep 17 00:00:00 2001 From: satoru kimura Date: Sun, 23 Aug 2015 17:28:53 +0900 Subject: [PATCH 135/173] Removed a reference to waa.d.ts in SoundJS definition. --- soundjs/soundjs.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/soundjs/soundjs.d.ts b/soundjs/soundjs.d.ts index 90e50200d..899063467 100644 --- a/soundjs/soundjs.d.ts +++ b/soundjs/soundjs.d.ts @@ -14,7 +14,6 @@ /// /// -/// declare module createjs { From c71755a6ab800b3776b9e23ce9817b5f0ccbb7e6 Mon Sep 17 00:00:00 2001 From: satoru kimura Date: Sun, 23 Aug 2015 17:32:56 +0900 Subject: [PATCH 136/173] Removed a reference to waa.d.ts in three.js definition. --- threejs/three.d.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/threejs/three.d.ts b/threejs/three.d.ts index 826d6332f..1e97210d5 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -3,8 +3,6 @@ // Definitions by: Kon , Satoru Kimura // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// - interface WebGLRenderingContext {} declare module THREE { From 690513a198642797773236fd1a3b667faa1dc463 Mon Sep 17 00:00:00 2001 From: vvakame Date: Sun, 23 Aug 2015 21:08:48 +0900 Subject: [PATCH 137/173] fix `npm run all` failed. sequelize-fixtures --- sequelize-fixtures/sequelize-fixtures-tests.ts | 3 ++- sequelize-fixtures/sequelize-fixtures.d.ts | 10 +++++----- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/sequelize-fixtures/sequelize-fixtures-tests.ts b/sequelize-fixtures/sequelize-fixtures-tests.ts index 567cf5967..c6edfd28f 100644 --- a/sequelize-fixtures/sequelize-fixtures-tests.ts +++ b/sequelize-fixtures/sequelize-fixtures-tests.ts @@ -15,7 +15,8 @@ SequelizeFixtures.loadFiles([], {}, { log: m => { } }).then(() => { }); SequelizeFixtures.loadFixture({}, {}).then(() => { }); sequelize.transaction(function (tx) { SequelizeFixtures.loadFixture({}, {}, { transaction: tx }).then(() => { }); + return null; }); SequelizeFixtures.loadFixtures([], {}).then(() => { }); -SequelizeFixtures.loadFixtures([], {}, { transformFixtureDataFn: (data) => { return data; } }).then(() => { }); \ No newline at end of file +SequelizeFixtures.loadFixtures([], {}, { transformFixtureDataFn: (data) => { return data; } }).then(() => { }); diff --git a/sequelize-fixtures/sequelize-fixtures.d.ts b/sequelize-fixtures/sequelize-fixtures.d.ts index 3cdf3fe8d..5358110f1 100644 --- a/sequelize-fixtures/sequelize-fixtures.d.ts +++ b/sequelize-fixtures/sequelize-fixtures.d.ts @@ -18,14 +18,14 @@ declare module "sequelize-fixtures" } interface SequelizeFixturesStatic { - loadFile(file: string, models: any, options?: Options): Sequelize.Promise; - loadFiles(files: string[], models: any, options?: Options): Sequelize.Promise; - loadFixture(fixture: any, models: any, options?: Options): Sequelize.Promise; - loadFixtures(fixtures: any[], models: any, options?: Options): Sequelize.Promise; + loadFile(file: string, models: any, options?: Options): Promise; + loadFiles(files: string[], models: any, options?: Options): Promise; + loadFixture(fixture: any, models: any, options?: Options): Promise; + loadFixtures(fixtures: any[], models: any, options?: Options): Promise; } } var sequelizeFixtures: SequelizeFixtures.SequelizeFixturesStatic; export = sequelizeFixtures; -} \ No newline at end of file +} From ae3ce43c89688bf0367f7649e578b4a7c47ee487 Mon Sep 17 00:00:00 2001 From: inker Date: Sun, 23 Aug 2015 19:51:32 +0300 Subject: [PATCH 138/173] A fix for the victor.js TS definition file The Victor class is now correctly exported as default. --- victor/victor.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/victor/victor.d.ts b/victor/victor.d.ts index 4206ffeb6..7812abcee 100644 --- a/victor/victor.d.ts +++ b/victor/victor.d.ts @@ -353,3 +353,7 @@ declare class Victor verticalAngleDeg():number; } + +declare module "victor" { + export = Victor; +} From c4e5067c3c3628828b6232deccc8e8cda87e3f0c Mon Sep 17 00:00:00 2001 From: Paulo Cesar Date: Sun, 23 Aug 2015 15:54:58 -0300 Subject: [PATCH 139/173] add bowser --- bowser/bowser-tests.ts | 7 ++++++ bowser/bowser.d.ts | 54 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 bowser/bowser-tests.ts create mode 100644 bowser/bowser.d.ts diff --git a/bowser/bowser-tests.ts b/bowser/bowser-tests.ts new file mode 100644 index 000000000..07d9f18cb --- /dev/null +++ b/bowser/bowser-tests.ts @@ -0,0 +1,7 @@ +import Bowser = require('bowser'); + +Bowser.msedge === true; +Bowser.test(['msie']) === true; +Bowser.a === Bowser.c; +Bowser.osversion > 10; +Bowser.osversion === '10.1A'; \ No newline at end of file diff --git a/bowser/bowser.d.ts b/bowser/bowser.d.ts new file mode 100644 index 000000000..afd15fa5d --- /dev/null +++ b/bowser/bowser.d.ts @@ -0,0 +1,54 @@ +// Type definitions for Bowser 1.x +// Project: https://github.com/ded/bowser +// Definitions by: Paulo Cesar +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module 'bowser' { + var def: BowserModule.IBowser; + export = def; +} + +declare module BowserModule { + + export interface IBowserUA { + msie: boolean; + chrome: boolean; + webkit: boolean; + phantom: boolean; + opera: boolean; + safari: boolean; + android: boolean; + ios: boolean; + webos: boolean; + msedge: boolean; + seamonkey: boolean; + firefox: boolean; + yandexbrowser: boolean; + blackberry: boolean; + tablet: boolean; + mobile: boolean; + silk: boolean; + bada: boolean; + tizen: boolean; + windowsphone: boolean; + firefoxos: boolean; + gecko: boolean; + sailfish: boolean; + chromeBook: boolean; + /** Grade A browser */ + a: boolean; + /** Grade C browser */ + c: boolean; + /** Grade X browser */ + x: boolean; + name: string; + version: string; + osversion: string|number; + } + + export interface IBowser extends IBowserUA { + test(browserList: string[]): boolean; + _detect(ua: string): IBowser; + } + +} From 62d90e23aa0c0855c0959052e561170832a86e94 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Sun, 23 Aug 2015 06:35:29 +0500 Subject: [PATCH 140/173] lodash: changed _.camelCase() method --- lodash/lodash-tests.ts | 3 +++ lodash/lodash.d.ts | 18 +++++++++++++++++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 00ca144fd..cd74cd625 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1725,7 +1725,10 @@ result = _.uniqueId(); * String *********/ +// _.camelCase result = _.camelCase('Foo Bar'); +result = _('Foo Bar').camelCase(); + result = _.capitalize('fred'); // _.deburr diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 77daeca2a..719247480 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -7525,8 +7525,24 @@ declare module _ { * String * **********/ + //_.camelCase + interface LoDashStatic { + /** + * Converts string to camel case. + * @param string The string to convert. + * @return Returns the camel cased string. + */ + camelCase(string?: string): string; + } + + interface LoDashWrapper { + /** + * @see _.camelCase + */ + camelCase(): string; + } + interface LoDashStatic { - camelCase(str?: string): string; capitalize(str?: string): string; } From 5b205217f73ee21a84d7936f770ccf67875ce278 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Sat, 22 Aug 2015 14:29:59 +0500 Subject: [PATCH 141/173] lodash: changed _.isDate() method --- lodash/lodash-tests.ts | 8 ++++++-- lodash/lodash.d.ts | 27 +++++++++++++++++---------- 2 files changed, 23 insertions(+), 12 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 00ca144fd..61fb8170e 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1201,6 +1201,12 @@ result = _(1).isArray(); result = _([]).isArray(); result = _({}).isArray(); +// _.isDate +result = _.isDate(any); +result = _(42).isDate(); +result = _([]).isDate(); +result = _({}).isDate(); + // _.isEmpty result = _.isEmpty([1, 2, 3]); result = _.isEmpty({}); @@ -1441,8 +1447,6 @@ result = _.invert({ 'first': 'moe', 'second': 'larry' }); result = _.isBoolean(null); -result = _.isDate(new Date()); - result = _.isElement(document.body); // _.isEqual (alias: _.eq) diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 77daeca2a..8da8a1938 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -6179,6 +6179,23 @@ declare module _ { isArray(): boolean; } + //_.isDate + interface LoDashStatic { + /** + * Checks if value is classified as a Date object. + * @param value The value to check. + * @return Returns true if value is correctly classified, else false. + **/ + isDate(value?: any): boolean; + } + + interface LoDashWrapperBase { + /** + * @see _.isDate + */ + isDate(): boolean; + } + //_.isEmpty interface LoDashStatic { /** @@ -6979,16 +6996,6 @@ declare module _ { isBoolean(value?: any): boolean; } - //_.isDate - interface LoDashStatic { - /** - * Checks if value is a date. - * @param value The value to check. - * @return True if the value is a date, else false. - **/ - isDate(value?: any): boolean; - } - //_.isElement interface LoDashStatic { /** From f569128818c2b4bb9a7f3e7243edf618f213eae1 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Sat, 22 Aug 2015 14:38:19 +0500 Subject: [PATCH 142/173] lodash: changed _.isNumber() method --- lodash/lodash-tests.ts | 8 ++++++-- lodash/lodash.d.ts | 30 ++++++++++++++++++------------ 2 files changed, 24 insertions(+), 14 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 00ca144fd..860af6550 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1236,6 +1236,12 @@ result = _(undefined).isNaN(); result = _.isNative(Array.prototype.push); result = _(Array.prototype.push).isNative(); +// _.isNumber +result = _.isNumber(any); +result = _(1).isNumber(); +result = _([]).isNumber(); +result = _({}).isNumber(); + // _.isRegExp result = _.isRegExp(any); result = _(1).isRegExp(); @@ -1475,8 +1481,6 @@ result = _.isFunction(_); result = _.isNull(null); result = _.isNull(undefined); -result = _.isNumber(8.4 * 5); - result = _.isObject({}); result = _.isObject([1, 2, 3]); result = _.isObject(1); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 77daeca2a..b275a5b33 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -6277,6 +6277,24 @@ declare module _ { isNative(): boolean; } + //_.isNumber + interface LoDashStatic { + /** + * Checks if value is classified as a Number primitive or object. + * Note: To exclude Infinity, -Infinity, and NaN, which are classified as numbers, use the _.isFinite method. + * @param value The value to check. + * @return Returns true if value is correctly classified, else false. + */ + isNumber(value?: any): boolean; + } + + interface LoDashWrapperBase { + /** + * see _.isNumber + */ + isNumber(): boolean; + } + //_.isRegExp interface LoDashStatic { /** @@ -7110,18 +7128,6 @@ declare module _ { isNull(value?: any): boolean; } - //_.isNumber - interface LoDashStatic { - /** - * Checks if value is a number. - * - * Note: NaN is considered a number. See http://es5.github.io/#x8.5. - * @param value The value to check. - * @return True if the value is a number, else false. - **/ - isNumber(value?: any): boolean; - } - //_.isObject interface LoDashStatic { /** From 3bb67023949e0a303efaaeca7e59357cf14782a5 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Sat, 22 Aug 2015 14:47:40 +0500 Subject: [PATCH 143/173] lodash: changed _.isString() method --- lodash/lodash-tests.ts | 8 ++++++-- lodash/lodash.d.ts | 27 +++++++++++++++++---------- 2 files changed, 23 insertions(+), 12 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 00ca144fd..f81217255 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1242,6 +1242,12 @@ result = _(1).isRegExp(); result = _([]).isRegExp(); result = _({}).isRegExp(); +// _.isString +result = _.isString(any); +result = _(1).isString(); +result = _([]).isString(); +result = _({}).isString(); + // _.isTypedArray result = _.isTypedArray([]); result = _([]).isTypedArray(); @@ -1492,8 +1498,6 @@ result = _.isPlainObject(new Stooge('moe', 40)); result = _.isPlainObject([1, 2, 3]); result = _.isPlainObject({ 'name': 'moe', 'age': 40 }); -result = _.isString('moe'); - result = _.keys({ 'one': 1, 'two': 2, 'three': 3 }); result = _({ 'one': 1, 'two': 2, 'three': 3 }).keys().value(); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 77daeca2a..b1082a459 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -6294,6 +6294,23 @@ declare module _ { isRegExp(): boolean; } + //_.isString + interface LoDashStatic { + /** + * Checks if value is classified as a String primitive or object. + * @param value The value to check. + * @return Returns true if value is correctly classified, else false. + **/ + isString(value?: any): boolean; + } + + interface LoDashWrapperBase { + /** + * see _.isString + */ + isString(): boolean; + } + //_.isTypedArray interface LoDashStatic { /** @@ -7143,16 +7160,6 @@ declare module _ { isPlainObject(value?: any): boolean; } - //_.isString - interface LoDashStatic { - /** - * Checks if value is a string. - * @param value The value to check. - * @return True if the value is a string, else false. - **/ - isString(value?: any): boolean; - } - //_.keys interface LoDashStatic { /** From 8fc36468726f50b2be2a7ef5e3dece312ba80f66 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Fri, 21 Aug 2015 06:19:06 +0500 Subject: [PATCH 144/173] lodash: changed _.repeat() method --- lodash/lodash-tests.ts | 6 ++++-- lodash/lodash.d.ts | 16 +++++++++++++++- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 00ca144fd..8183c54a5 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1768,14 +1768,16 @@ result = _('abc').padRight(); result = _('abc').padRight(6); result = _('abc').padRight(6, '_-'); -result = _.repeat('*', 3); - // _.parseInt result = _.parseInt('08'); result = _.parseInt('08', 10); result = _('08').parseInt(); result = _('08').parseInt(10); +// _.repeat +result = _.repeat('*', 3); +result = _('*').repeat(3); + // _.snakeCase result = _.snakeCase('Foo Bar'); result = _('Foo Bar').snakeCase(); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 77daeca2a..5c57d76f3 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -7672,8 +7672,22 @@ declare module _ { parseInt(radix?: number): number; } + //_.repeat interface LoDashStatic { - repeat(str?: string, n?: number): string; + /** + * Repeats the given string n times. + * @param string The string to repeat. + * @param n The number of times to repeat the string. + * @return Returns the repeated string. + */ + repeat(string?: string, n?: number): string; + } + + interface LoDashWrapper { + /** + * @see _.repeat + */ + repeat(n?: number): string; } //_.snakeCase From 527298c48e0ed3a84c46a58ea15c7c0ce27bf7ec Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Sun, 23 Aug 2015 06:30:41 +0500 Subject: [PATCH 145/173] lodash: changed _.startCase() method --- lodash/lodash-tests.ts | 2 ++ lodash/lodash.d.ts | 15 ++++++++++++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 00ca144fd..4369803ba 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1780,7 +1780,9 @@ result = _('08').parseInt(10); result = _.snakeCase('Foo Bar'); result = _('Foo Bar').snakeCase(); +// _.startCase result = _.startCase('--foo-bar'); +result = _('--foo-bar').startCase(); // _.startsWith result = _.startsWith('abc', 'a'); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 77daeca2a..188556e6e 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -7693,8 +7693,21 @@ declare module _ { snakeCase(): string; } + //_.startCase interface LoDashStatic { - startCase(str?: string): string; + /** + * Converts string to start case. + * @param string The string to convert. + * @return Returns the start cased string. + */ + startCase(string?: string): string; + } + + interface LoDashWrapper { + /** + * @see _.startCase + */ + startCase(): string; } //_.startsWith From cf410b943a4c55b3dab8f0b925c5790633244670 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Sun, 23 Aug 2015 06:23:09 +0500 Subject: [PATCH 146/173] lodash: changed _.words() method --- lodash/lodash-tests.ts | 3 +++ lodash/lodash.d.ts | 16 +++++++++++++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 00ca144fd..3bc21ed4e 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1825,8 +1825,11 @@ result = _('hi-diddly-ho there, neighborino').trunc({ 'omission': ' [… result = _.unescape('fred, barney, & pebbles'); result = _('fred, barney, & pebbles').unescape(); +// _.words result = _.words('fred, barney, & pebbles'); result = _.words('fred, barney, & pebbles', /[^, ]+/g); +result = _('fred, barney, & pebbles').words(); +result = _('fred, barney, & pebbles').words(/[^, ]+/g); /********** * Utilities * diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 77daeca2a..0e86d6651 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -7816,8 +7816,22 @@ declare module _ { unescape(): string; } + //_.words interface LoDashStatic { - words(str?: string, pattern?: string|RegExp): string[]; + /** + * Splits string into an array of its words. + * @param string The string to inspect. + * @param pattern The pattern to match words. + * @return Returns the words of string. + */ + words(string?: string, pattern?: string|RegExp): string[]; + } + + interface LoDashWrapper { + /** + * @see _.words + */ + words(pattern?: string|RegExp): string[]; } /*********** From 61c54e2b00b53570d2fbace9b59e2ff1240875e6 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Mon, 24 Aug 2015 00:25:56 +0500 Subject: [PATCH 147/173] lodash: changed _.isArguments() method --- lodash/lodash-tests.ts | 8 ++++++-- lodash/lodash.d.ts | 27 +++++++++++++++++---------- 2 files changed, 23 insertions(+), 12 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 00ca144fd..9003a5e00 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1195,6 +1195,12 @@ result = _(1).gte(2); result = _([]).gte(2); result = _({}).gte(2); +// _.isArguments +result = _.isArguments(any); +result = _(1).isArguments(); +result = _([]).isArguments(); +result = _({}).isArguments(); + // _.isArray result = _.isArray(any); result = _(1).isArray(); @@ -1437,8 +1443,6 @@ interface FirstSecond { } result = _.invert({ 'first': 'moe', 'second': 'larry' }); -(function (...args: any[]) { return _.isArguments(arguments); })(1, 2, 3); - result = _.isBoolean(null); result = _.isDate(new Date()); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 77daeca2a..62b5c0f89 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -6162,6 +6162,23 @@ declare module _ { gte(other: any): boolean; } + //_.isArguments + interface LoDashStatic { + /** + * Checks if value is classified as an arguments object. + * @param value The value to check. + * @return Returns true if value is correctly classified, else false. + */ + isArguments(value?: any): boolean; + } + + interface LoDashWrapperBase { + /** + * @see _.isArguments + */ + isArguments(): boolean; + } + //_.isArray interface LoDashStatic { /** @@ -6959,16 +6976,6 @@ declare module _ { invert(object: any): any; } - //_.isArguments - interface LoDashStatic { - /** - * Checks if value is an arguments object. - * @param value The value to check. - * @return True if the value is an arguments object, else false. - **/ - isArguments(value?: any): boolean; - } - //_.isBoolean interface LoDashStatic { /** From ac5487ad224705c215855ffd0fd322ba8c52d7f9 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Mon, 24 Aug 2015 00:33:26 +0500 Subject: [PATCH 148/173] lodash: changed _.isError() method --- lodash/lodash-tests.ts | 6 ++++++ lodash/lodash.d.ts | 29 ++++++++++++++++++----------- 2 files changed, 24 insertions(+), 11 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 00ca144fd..80f6f72ae 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1209,6 +1209,12 @@ result = _([1, 2, 3]).isEmpty(); result = _({}).isEmpty(); result = _('').isEmpty(); +// _.isError +result = _.isError(any); +result = _(1).isError(); +result = _([]).isError(); +result = _({}).isError(); + // _.isFinite result = _.isFinite(any); result = _(1).isFinite(); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 77daeca2a..cbd802e78 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -6197,6 +6197,24 @@ declare module _ { isEmpty(): boolean; } + //_.isError + interface LoDashStatic { + /** + * Checks if value is an Error, EvalError, RangeError, ReferenceError, SyntaxError, TypeError, or URIError + * object. + * @param value The value to check. + * @return Returns true if value is an error object, else false. + */ + isError(value: any): boolean; + } + + interface LoDashWrapperBase { + /** + * @see _.isError + */ + isError(): boolean; + } + //_.isFinite interface LoDashStatic { /** @@ -6999,17 +7017,6 @@ declare module _ { isElement(value?: any): boolean; } - //_.isError - interface LoDashStatic { - /** - * Checks if value is an Error, EvalError, RangeError, ReferenceError, SyntaxError, TypeError, - * or URIError object. - * @param value The value to check. - * @return True if value is an error object, else false. - */ - isError(value: any): boolean; - } - //_.isEqual interface EqCustomizer { (value: any, other: any, indexOrKey?: number|string): boolean; From e47ef31f9b1e46596a50ff5342d58f2fcf3203a0 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Mon, 24 Aug 2015 00:37:36 +0500 Subject: [PATCH 149/173] lodash: changed _.isFunction() method --- lodash/lodash-tests.ts | 8 ++++++-- lodash/lodash.d.ts | 27 +++++++++++++++++---------- 2 files changed, 23 insertions(+), 12 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 00ca144fd..544529d01 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1215,6 +1215,12 @@ result = _(1).isFinite(); result = _([]).isFinite(); result = _({}).isFinite(); +// _.isFunction +result = _.isFunction(any); +result = _(1).isFunction(); +result = _([]).isFunction(); +result = _({}).isFunction(); + // _.isMatch var testIsMatchCustiomizerFn: (value: any, other: any, indexOrKey: number|string) => boolean; result = _.isMatch({}, {}); @@ -1470,8 +1476,6 @@ result = _(testEqArray).isEqual(testEqOtherArray, testEqCustomizerFn); result = _.eq(testEqArray, testEqOtherArray, testEqCustomizerFn); result = _(testEqArray).eq(testEqOtherArray, testEqCustomizerFn); -result = _.isFunction(_); - result = _.isNull(null); result = _.isNull(undefined); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 77daeca2a..d5b6707f8 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -6215,6 +6215,23 @@ declare module _ { isFinite(): boolean; } + //_.isFunction + interface LoDashStatic { + /** + * Checks if value is classified as a Function object. + * @param value The value to check. + * @return Returns true if value is correctly classified, else false. + **/ + isFunction(value?: any): boolean; + } + + interface LoDashWrapperBase { + /** + * @see _.isFunction + */ + isFunction(): boolean; + } + //_.isMatch interface isMatchCustomizer { (value: any, other: any, indexOrKey?: number|string): boolean; @@ -7090,16 +7107,6 @@ declare module _ { thisArg?: any): boolean; } - //_.isFunction - interface LoDashStatic { - /** - * Checks if value is a function. - * @param value The value to check. - * @return True if the value is a function, else false. - **/ - isFunction(value?: any): boolean; - } - //_.isNull interface LoDashStatic { /** From 1c48442b68e06a817c8c9a2f8131bc91759970eb Mon Sep 17 00:00:00 2001 From: lp Date: Sat, 8 Aug 2015 00:08:41 +0100 Subject: [PATCH 150/173] Fixed param for dynatree and added tests Made includeRoot optional changed flag param from string -> boolean Added test file --- jquery.dynatree/jquery.dynatree-tests.ts | 15 +++++++++++++++ jquery.dynatree/jquery.dynatree.d.ts | 10 +++++----- 2 files changed, 20 insertions(+), 5 deletions(-) create mode 100644 jquery.dynatree/jquery.dynatree-tests.ts diff --git a/jquery.dynatree/jquery.dynatree-tests.ts b/jquery.dynatree/jquery.dynatree-tests.ts new file mode 100644 index 000000000..df1a17f10 --- /dev/null +++ b/jquery.dynatree/jquery.dynatree-tests.ts @@ -0,0 +1,15 @@ +/// + +var dynatree = $('element').dynatree(); + +dynatree.visit((node)=>{ + return false; +}); + +dynatree.visit((node)=>{ + return false; +}, true); + +var node = dynatree.getActiveNode(); + +node.select(true); \ No newline at end of file diff --git a/jquery.dynatree/jquery.dynatree.d.ts b/jquery.dynatree/jquery.dynatree.d.ts index c2dc0f928..e8604d2a0 100644 --- a/jquery.dynatree/jquery.dynatree.d.ts +++ b/jquery.dynatree/jquery.dynatree.d.ts @@ -41,7 +41,7 @@ interface DynaTree { selectKey(key: string, flag: string): DynaTreeNode; serializeArray(stopOnParents: boolean): any[]; toDict(includeRoot?: boolean): any; - visit(fn: (node: DynaTreeNode) =>boolean, includeRoot: boolean): void; + visit(fn: (node: DynaTreeNode) =>boolean, includeRoot?: boolean): void; } @@ -54,7 +54,7 @@ interface DynaTreeNode { appendAjax(ajaxOptions: JQueryAjaxSettings): void; countChildren(): number; deactivate(): void; - expand(flag: string): void; + expand(flag: boolean): void; focus(): void; getChildren(): DynaTreeNode[]; getEventTargetType(event: Event): string; @@ -83,11 +83,11 @@ interface DynaTreeNode { removeChildren(): void; render(useEffects: boolean, includeInvisible: boolean): void; resetLazy(): void; - scheduleAction(mode: string, ms: number); - select(flag: string): void; + scheduleAction(mode: string, ms: number): void; + select(flag: boolean): void; setLazyNodeStatus(status: number): void; setTitle(title: string): void; - sortChildren(cmp?: (a: DynaTreeNode, b: DynaTreeNode) =>number, deep?: boolean); + sortChildren(cmp?: (a: DynaTreeNode, b: DynaTreeNode) =>number, deep?: boolean): void; toDict(recursive: boolean, callback?: (node: any) =>any): any; toggleExpand(): void; toggleSelect(): void; From 637aaf1d9aeac46386a20f7f75256cd967552111 Mon Sep 17 00:00:00 2001 From: fpellet Date: Mon, 24 Aug 2015 00:43:23 +0200 Subject: [PATCH 151/173] Add jquery.ajaxfile definition --- jquery.ajaxfile/jquery.ajaxFile-tests.ts | 54 ++++++++++ jquery.ajaxfile/jquery.ajaxFile.d.ts | 119 +++++++++++++++++++++++ 2 files changed, 173 insertions(+) create mode 100644 jquery.ajaxfile/jquery.ajaxFile-tests.ts create mode 100644 jquery.ajaxfile/jquery.ajaxFile.d.ts diff --git a/jquery.ajaxfile/jquery.ajaxFile-tests.ts b/jquery.ajaxfile/jquery.ajaxFile-tests.ts new file mode 100644 index 000000000..4a98706a4 --- /dev/null +++ b/jquery.ajaxfile/jquery.ajaxFile-tests.ts @@ -0,0 +1,54 @@ +/// +/// +/// + +function testRawApi(){ + var inputElement:HTMLInputElement = null; + var resultPromise = AjaxFile.send({ + method: 'POST', + url: '/', + desiredResponseDataType: JQueryAjaxFile.DataType.Json, + files: [ + { name: 'joeFile', element: inputElement } + ], + data: { + name: 'joe' + }, + timeoutInSeconds: 30 + }) + .then(result => console.log('Result: ' + result.data), result => console.log('Error: ' + result.error)) + .done(result => console.log('Result: ' + result.data)) + .fail(result => console.log('Error: ' + result.error + " " + result.status.code + " " + result.status.text + " " + result.status.isSuccess)) + .always(result => console.log('end')) + .abord(); +} + +function testJQuery() { + var inputElement: HTMLInputElement = null; + var extension: JQueryAjaxFile.IAjaxFileJQueryExtension = $.fn.ajaxWithFile; + var option: JQueryAjaxFile.IJQueryOption = { + type: 'POST', + url: '/', + dataType: "json", + files: [ + { name: 'joeFile', element: inputElement } + ], + data: { + name: 'joe' + }, + success(result) { console.log('Result: ' + result); }, + error(jqXhr, textStatus, errorThrown) { console.log('Error: ' + errorThrown); }, + complete(jqXhr, textStatus) { console.log('end'); }, + global: true, + timeout: 60 + }; + extension.ajaxWithFile(option); +} + +function testKnockoutExtension(){ + var fileHandler:KnockoutBindingHandler = ko.bindingHandlers.file; +} + +testKnockoutExtension(); +testJQuery(); +testRawApi(); \ No newline at end of file diff --git a/jquery.ajaxfile/jquery.ajaxFile.d.ts b/jquery.ajaxfile/jquery.ajaxFile.d.ts new file mode 100644 index 000000000..459287a27 --- /dev/null +++ b/jquery.ajaxfile/jquery.ajaxFile.d.ts @@ -0,0 +1,119 @@ +// Type definitions for jquery.ajaxfile v0.1.0 +// Project: https://github.com/fpellet/jquery.ajaxFile +// Definitions by: Florent PELLET +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare namespace JQueryAjaxFile { + export enum DataType { + Json, + Xml, + Text + } + + interface IFileData { + name: string; + element: HTMLInputElement; + } + + interface IOption { + method?: string; + url?: string; + + data?: any; + files?: IFileData[]; + desiredResponseDataType?: DataType; + + timeoutInSeconds?: number; + } + + interface IResponseStatus { + code: number; + text: string; + isSuccess: boolean; + } + + interface IAjaxFileResult { + error?: any; + data?: any; + status?: IResponseStatus; + } + + interface IAjaxFileResultCallback { + (result: IAjaxFileResult): void; + } + + interface IAjaxFilePromise { + then(success: IAjaxFileResultCallback, error?: IAjaxFileResultCallback): IAjaxFilePromise; + done(success: IAjaxFileResultCallback): IAjaxFilePromise; + fail(error: IAjaxFileResultCallback): IAjaxFilePromise; + always(error: IAjaxFileResultCallback): IAjaxFilePromise; + + abord(): void; + } + + interface IAjaxFileStatic { + send(option: IOption): IAjaxFilePromise; + } + + interface IJQueryXHR { + readyState: any; + status: number; + statusText: string; + responseXML: Document; + responseText: string; + statusCode?: { [key: string]: any; }; + + abort(statusText?: string): void; + + setRequestHeader(header: string, value: string): void; + getAllResponseHeaders(): string; + getResponseHeader(header: string): string; + + beforeSend?(jqXHR: IJQueryXHR, settings: JQueryAjaxSettings): any; + dataFilter?(data: any, ty: any): any; + success?(data: any, textStatus: string, jqXHR: IJQueryXHR): any; + error?(jqXHR: IJQueryXHR, textStatus: string, errorThrown: string): any; + complete?(jqXHR: IJQueryXHR, textStatus: string): any; + } + + interface IJQueryOption { + type?: string; + url?: string; + + data?: any; + files?: IFileData[]; + dataType?: string; + + timeout?: number; + + global?: boolean; + + error?(jqXHR: IJQueryXHR, textStatus: string, errorThrown: string): any; + success?(data: any, textStatus: string, jqXHR: IJQueryXHR): any; + complete?(jqXHR: IJQueryXHR, textStatus: string): any; + } + + interface IAjaxFileJQueryExtension { + ajaxWithFile(jqueryOption: IJQueryOption): JQueryDeferred; + } +} + +declare var AjaxFile: JQueryAjaxFile.IAjaxFileStatic; + +declare module 'ajaxfile' { + export = AjaxFile; +} + +declare namespace AjaxFileKnockout { + interface IFileInputWrapper { + getElement(): HTMLInputElement; + fileSelected(): boolean; + } +} + +interface KnockoutBindingHandlers { + file: KnockoutBindingHandler; +} From fe2856e93dc82f65de501e061a63f792f09b9e0f Mon Sep 17 00:00:00 2001 From: xyb Date: Sun, 23 Aug 2015 15:38:12 -0700 Subject: [PATCH 152/173] Definitions for expression-less --- express-less/express-less-tests.ts | 12 ++++++++++++ express-less/express-less.d.ts | 21 +++++++++++++++++++++ 2 files changed, 33 insertions(+) create mode 100644 express-less/express-less-tests.ts create mode 100644 express-less/express-less.d.ts diff --git a/express-less/express-less-tests.ts b/express-less/express-less-tests.ts new file mode 100644 index 000000000..3fee687f2 --- /dev/null +++ b/express-less/express-less-tests.ts @@ -0,0 +1,12 @@ +/// + +import express = require('express'); +import expressLess = require('express-less'); + +var app = express(); +var lessOptions: expressLess.Options = {}; +lessOptions.compress = true; +lessOptions.debug = true; + +app.use('/less-css', expressLess(__dirname)); +app.use('/less-css-with-options', expressLess(__dirname + "/less", lessOptions)); diff --git a/express-less/express-less.d.ts b/express-less/express-less.d.ts new file mode 100644 index 000000000..b3c7008cd --- /dev/null +++ b/express-less/express-less.d.ts @@ -0,0 +1,21 @@ +// Type definitions for express-less +// Project: https://www.npmjs.com/package/express-less +// Definitions by: xyb +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "express-less" { + import express = require('express'); + + function less(root: string, options?: less.Options): express.RequestHandler; + + module less { + export interface Options { + debug?: boolean; + compress?: boolean; + } + } + + export = less; +} From 375b76186f0e0f04448c597ce448f8973656b60d Mon Sep 17 00:00:00 2001 From: Joe Herman Date: Sun, 23 Aug 2015 21:11:17 -0400 Subject: [PATCH 153/173] async: Corrected and updated to 1.4.2 --- async/async-tests.ts | 137 +++++++++++++++++--- async/async.d.ts | 291 ++++++++++++++++++++++++------------------- 2 files changed, 283 insertions(+), 145 deletions(-) diff --git a/async/async-tests.ts b/async/async-tests.ts index 4fddea875..a6dff0af8 100644 --- a/async/async-tests.ts +++ b/async/async-tests.ts @@ -5,8 +5,19 @@ var fs, path; function callback() {} async.map(['file1', 'file2', 'file3'], fs.stat, function (err, results) { }); +async.mapSeries(['file1', 'file2', 'file3'], fs.stat, function (err, results) { }); +async.mapLimit(['file1', 'file2', 'file3'], 2, fs.stat, function (err, results) { }); async.filter(['file1', 'file2', 'file3'], path.exists, function (results) { }); +async.filterSeries(['file1', 'file2', 'file3'], path.exists, function (results) { }); +async.filterLimit(['file1', 'file2', 'file3'], 2, path.exists, function (results) { }); +async.select(['file1', 'file2', 'file3'], path.exists, function (results) { }); +async.selectSeries(['file1', 'file2', 'file3'], path.exists, function (results) { }); +async.selectLimit(['file1', 'file2', 'file3'], 2, path.exists, function (results) { }); + +async.reject(['file1', 'file2', 'file3'], path.exists, function (results) { }); +async.rejectSeries(['file1', 'file2', 'file3'], path.exists, function (results) { }); +async.rejectLimit(['file1', 'file2', 'file3'], 2, path.exists, function (results) { }); async.parallel([ function () { }, @@ -25,6 +36,11 @@ async.map(data, asyncProcess, function (err, results) { }); var openFiles = ['file1', 'file2']; +var openFilesObj = { + file1: "fileOne", + file2: "fileTwo" +} + var saveFile = function () { } async.each(openFiles, saveFile, function (err) { }); async.eachSeries(openFiles, saveFile, function (err) { }); @@ -32,18 +48,34 @@ async.eachSeries(openFiles, saveFile, function (err) { }); var documents, requestApi; async.eachLimit(documents, 20, requestApi, function (err) { }); -async.map(['file1', 'file2', 'file3'], fs.stat, function (err, results) { }); - -async.filter(['file1', 'file2', 'file3'], path.exists, function (results) { }); +// forEachOf* functions. May accept array or object. +function forEachOfIterator(item, key, forEachOfIteratorCallback) { + console.log("ForEach: item=" + item + ", key=" + key); + forEachOfIteratorCallback(); +} +async.forEachOf(openFiles, forEachOfIterator, function (err) { }); +async.forEachOf(openFilesObj, forEachOfIterator, function (err) { }); +async.forEachOfSeries(openFiles, forEachOfIterator, function (err) { }); +async.forEachOfSeries(openFilesObj, forEachOfIterator, function (err) { }); +async.forEachOfLimit(openFiles, 2, forEachOfIterator, function (err) { }); +async.forEachOfLimit(openFilesObj, 2, forEachOfIterator, function (err) { }); var process; -async.reduce([1, 2, 3], 0, function (memo, item, callback) { +var numArray = [1, 2, 3]; +function reducer(memo, item, callback) { process.nextTick(function () { callback(null, memo + item) }); -}, function (err, result) { }); +} +async.reduce(numArray, 0, reducer, function (err, result) { }); +async.inject(numArray, 0, reducer, function (err, result) { }); +async.foldl(numArray, 0, reducer, function (err, result) { }); +async.reduceRight(numArray, 0, reducer, function (err, result) { }); +async.foldr(numArray, 0, reducer, function (err, result) { }); async.detect(['file1', 'file2', 'file3'], path.exists, function (result) { }); +async.detectSeries(['file1', 'file2', 'file3'], path.exists, function (result) { }); +async.detectLimit(['file1', 'file2', 'file3'], 2, path.exists, function (result) { }); async.sortBy(['file1', 'file2', 'file3'], function (file, callback) { fs.stat(file, function (err, stats) { @@ -52,10 +84,18 @@ async.sortBy(['file1', 'file2', 'file3'], function (file, callback) { }, function (err, results) { }); async.some(['file1', 'file2', 'file3'], path.exists, function (result) { }); +async.someLimit(['file1', 'file2', 'file3'], 2, path.exists, function (result) { }); +async.any(['file1', 'file2', 'file3'], path.exists, function (result) { }); async.every(['file1', 'file2', 'file3'], path.exists, function (result) { }); +async.everyLimit(['file1', 'file2', 'file3'], 2, path.exists, function (result) { }); +async.all(['file1', 'file2', 'file3'], path.exists, function (result) { }); async.concat(['dir1', 'dir2', 'dir3'], fs.readdir, function (err, files) { }); +async.concatSeries(['dir1', 'dir2', 'dir3'], fs.readdir, function (err, files) { }); + + +// Control Flow // async.series([ function (callback) { @@ -77,7 +117,6 @@ async.series([ ], function (err, results) { }); - async.series({ one: function (callback) { setTimeout(function () { @@ -173,21 +212,47 @@ async.parallel({ }, 100); }, }, -function (err, results) { }); + function (err, results) { }); - -var count = 0; - -async.whilst( - function () { return count < 5; }, - function (callback) { - count++; - setTimeout(callback, 1000); +async.parallelLimit({ + one: function (callback) { + setTimeout(function () { + callback(null, 1); + }, 200); }, - function (err) { } + two: function (callback) { + setTimeout(function () { + callback(null, 2); + }, 100); + }, +}, + 2, + function (err, results) { } ); +function whileFn(callback) { + count++; + setTimeout(callback, 1000); +} + +function whileTest() { return count < 5; } +var count = 0; +async.whilst(whileTest, whileFn, function (err) { }); +async.until(whileTest, whileFn, function (err) { }); +async.doWhilst(whileFn, whileTest, function (err) { }); +async.doUntil(whileFn, whileTest, function (err) { }); + +async.during(function (testCallback) { testCallback(new Error(), false); }, function (callback) { callback() }, function (error) { console.log(error) }); +async.doDuring(function (callback) { callback() }, function (testCallback) { testCallback(new Error(), false); }, function (error) { console.log(error) }); +async.forever(function (errBack) { + errBack(new Error("Not going on forever.")); +}, + function (error) { + console.log(error); + } +); + async.waterfall([ function (callback) { callback(null, 'one', 'two'); @@ -279,6 +344,26 @@ q2.unshift(['task3', 'task4', 'task5'], function (error) { console.log('Finished tasks'); }); +// create a cargo object with payload 2 +var cargo = async.cargo(function (tasks, callback) { + for (var i = 0; i < tasks.length; i++) { + console.log('hello ' + tasks[i].name); + } + callback(); +}, 2); + + +// add some items +cargo.push({ name: 'foo' }, function (err) { + console.log('finished processing foo'); +}); +cargo.push({ name: 'bar' }, function (err) { + console.log('finished processing bar'); +}); +cargo.push({ name: 'baz' }, function (err) { + console.log('finished processing baz'); +}); + var filename = ''; async.auto({ get_data: function (callback) { }, @@ -291,6 +376,9 @@ async.auto({ email_link: ['write_file', function (callback, results) { }] }); +async.retry(3, function (callback, results) { }, function (err, result) { }); +async.retry({ times: 3, interval: 200 }, function (callback, results) { }, function (err, result) { }); + async.parallel([ function (callback) { }, @@ -336,3 +424,20 @@ var slow_fn = function (name, callback) { }; var fn = async.memoize(slow_fn); fn('some name', function () {}); +async.unmemoize(fn); +async.ensureAsync(function () { }); +async.constant(42); +async.asyncify(function () { }); + +async.log(function (name, callback) { + setTimeout(function () { + callback(null, 'hello ' + name); + }, 0); +}, "world" + ); + +async.dir(function (name, callback) { + setTimeout(function () { + callback(null, { hello: name }); + }, 1000); +}, "world"); diff --git a/async/async.d.ts b/async/async.d.ts index 56370c15d..b90876915 100644 --- a/async/async.d.ts +++ b/async/async.d.ts @@ -1,132 +1,165 @@ -// Type definitions for Async 0.9.2 -// Project: https://github.com/caolan/async +// Type definitions for Async 1.4.2 +// Project: https://github.com/caolan/async // Definitions by: Boris Yankov , Arseniy Maximov -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -interface Dictionary { [key: string]: T; } - -// Common interface between Arrays and Array-like objects -interface List { - [index: number]: T; - length: number; +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface Dictionary { [key: string]: T; } + +interface ErrorCallback { (err?: Error): void; } +interface AsyncResultCallback { (err: Error, result: T): void; } +interface AsyncResultArrayCallback { (err: Error, results: T[]): void; } +interface AsyncResultObjectCallback { (err: Error, results: Dictionary): void; } + +interface AsyncFunction { (callback: (err: Error, result?: T) => void): void; } +interface AsyncIterator { (item: T, callback: ErrorCallback): void; } +interface AsyncForEachOfIterator { (item: T, key: number, callback: ErrorCallback): void; } +interface AsyncResultIterator { (item: T, callback: AsyncResultCallback): void; } +interface AsyncMemoIterator { (memo: R, item: T, callback: AsyncResultCallback): void; } +interface AsyncBooleanIterator { (item: T, callback: (truthValue: boolean) => void): void; } + +interface AsyncWorker { (task: T, callback: ErrorCallback): void; } +interface AsyncVoidFunction { (callback: ErrorCallback): void; } + +interface AsyncQueue { + length(): number; + started: boolean; + running(): number; + idle(): boolean; + concurrency: number; + push(task: T, callback?: ErrorCallback): void; + push(task: T[], callback?: ErrorCallback): void; + unshift(task: T, callback?: ErrorCallback): void; + unshift(task: T[], callback?: ErrorCallback): void; + saturated: () => any; + empty: () => any; + drain: () => any; + paused: boolean; + pause(): void + resume(): void; + kill(): void; } -interface ErrorCallback { (err?: Error): void; } -interface AsyncResultCallback { (err: Error, result: T): void; } -interface AsyncResultArrayCallback { (err: Error, results: T[]): void; } -interface AsyncResultObjectCallback { (err: Error, results: Dictionary): void; } - -interface AsyncIterator { (item: T, callback: ErrorCallback): void; } -interface AsyncForEachOfIterator { (item: T, index: number, callback: ErrorCallback): void; } -interface AsyncResultIterator { (item: T, callback: AsyncResultCallback): void; } -interface AsyncMemoIterator { (memo: R, item: T, callback: AsyncResultCallback): void; } - -interface AsyncWorker { (task: T, callback: ErrorCallback): void; } - -interface AsyncFunction { (callback: AsyncResultCallback): void; } -interface AsyncVoidFunction { (callback: ErrorCallback): void; } - -interface AsyncQueue { - length(): number; - concurrency: number; - started: boolean; - paused: boolean; - push(task: T, callback?: ErrorCallback): void; - push(task: T[], callback?: ErrorCallback): void; - unshift(task: T, callback?: ErrorCallback): void; - unshift(task: T[], callback?: ErrorCallback): void; - saturated: () => any; - empty: () => any; - drain: () => any; - running(): number; - idle(): boolean; - pause(): void; - resume(): void; - kill(): void; -} - -interface AsyncPriorityQueue { - length(): number; - concurrency: number; - started: boolean; - paused: boolean; - push(task: T, priority: number, callback?: AsyncResultArrayCallback): void; - push(task: T[], priority: number, callback?: AsyncResultArrayCallback): void; - saturated: () => any; - empty: () => any; - drain: () => any; - running(): number; - idle(): boolean; - pause(): void; - resume(): void; - kill(): void; -} - -interface Async { - - // Collections - each(arr: T[], iterator: AsyncIterator, callback: ErrorCallback): void; - eachSeries(arr: T[], iterator: AsyncIterator, callback: ErrorCallback): void; - eachLimit(arr: T[], limit: number, iterator: AsyncIterator, callback: ErrorCallback): void; - forEachOf(obj: List, iterator: AsyncForEachOfIterator, callback: ErrorCallback): void; - forEachOfSeries(obj: List, iterator: AsyncForEachOfIterator, callback: ErrorCallback): void; - forEachOfLimit(obj: List, limit: number, iterator: AsyncForEachOfIterator, callback: ErrorCallback): void; - map(arr: T[], iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): any; - mapSeries(arr: T[], iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): any; - mapLimit(arr: T[], limit: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): any; - filter(arr: T[], iterator: AsyncResultIterator, callback: (results: T[]) => any): any; - select(arr: T[], iterator: AsyncResultIterator, callback: (results: T[]) => any): any; - filterSeries(arr: T[], iterator: AsyncResultIterator, callback: (results: T[]) => any): any; - selectSeries(arr: T[], iterator: AsyncResultIterator, callback: (results: T[]) => any): any; - reject(arr: T[], iterator: AsyncResultIterator, callback: (results: T[]) => any): any; - rejectSeries(arr: T[], iterator: AsyncResultIterator, callback: (results: T[]) => any): any; - reduce(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncResultCallback): any; - inject(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncResultCallback): any; - foldl(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncResultCallback): any; - reduceRight(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncResultCallback): any; - foldr(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncResultCallback): any; - detect(arr: T[], iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): any; - detectSeries(arr: T[], iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): any; - sortBy(arr: T[], iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): any; - some(arr: T[], iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): any; - any(arr: T[], iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): any; - every(arr: T[], iterator: AsyncResultIterator, callback: (result: boolean) => any): any; - all(arr: T[], iterator: AsyncResultIterator, callback: (result: boolean) => any): any; - concat(arr: T[], iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): any; - concatSeries(arr: T[], iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): any; - - // Control Flow - series(tasks: Array>, callback?: AsyncResultArrayCallback): void; - series(tasks: Dictionary>, callback?: AsyncResultObjectCallback): void; - parallel(tasks: Array>, callback?: AsyncResultArrayCallback): void; - parallel(tasks: Dictionary>, callback?: AsyncResultObjectCallback): void; - parallelLimit(tasks: Array>, limit: number, callback?: AsyncResultArrayCallback): void; - parallelLimit(tasks: Dictionary>, limit: number, callback?: AsyncResultObjectCallback): void; - whilst(test: () => boolean, fn: AsyncVoidFunction, callback: (err: any) => void): void; - doWhilst(fn: AsyncVoidFunction, test: () => boolean, callback: (err: any) => void): void; - until(test: () => boolean, fn: AsyncVoidFunction, callback: (err: any) => void): void; - doUntil(fn: AsyncVoidFunction, test: () => boolean, callback: (err: any) => void): void; - waterfall(tasks: Function[], callback?: (err: any, ...arguments: any[]) => void): void; - queue(worker: AsyncWorker, concurrency: number): AsyncQueue; - priorityQueue(worker: AsyncWorker, concurrency: number): AsyncPriorityQueue; - auto(tasks: any, callback?: AsyncResultArrayCallback): void; - iterator(tasks: Function[]): Function; - apply(fn: Function, ...arguments: any[]): AsyncFunction; - nextTick(callback: Function): void; - - times (n: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; - timesSeries (n: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; - - // Utils - memoize(fn: Function, hasher?: Function): Function; - unmemoize(fn: Function): Function; - log(fn: Function, ...arguments: any[]): void; - dir(fn: Function, ...arguments: any[]): void; - noConflict(): Async; -} - -declare var async: Async; - -declare module "async" { - export = async; -} +interface AsyncPriorityQueue { + length(): number; + concurrency: number; + started: boolean; + paused: boolean; + push(task: T, priority: number, callback?: AsyncResultArrayCallback): void; + push(task: T[], priority: number, callback?: AsyncResultArrayCallback): void; + saturated: () => any; + empty: () => any; + drain: () => any; + running(): number; + idle(): boolean; + pause(): void; + resume(): void; + kill(): void; +} + +interface AsyncCargo { + length(): number; + payload: number; + push(task: any, callback? : Function): void; + push(task: any[], callback? : Function): void; + saturated(): void; + empty(): void; + drain(): void; + idle(): boolean; + pause(): void; + resume(): void; + kill(): void; +} + +interface Async { + + // Collections + each(arr: T[], iterator: AsyncIterator, callback?: ErrorCallback): void; + eachSeries(arr: T[], iterator: AsyncIterator, callback?: ErrorCallback): void; + eachLimit(arr: T[], limit: number, iterator: AsyncIterator, callback?: ErrorCallback): void; + forEachOf(obj: any, iterator: (item: any, key: [string|number], callback?: ErrorCallback) => void, callback: ErrorCallback): void; + forEachOf(obj: T[], iterator: AsyncForEachOfIterator, callback?: ErrorCallback): void; + forEachOfSeries(obj: any, iterator: (item: any, key: [string|number], callback?: ErrorCallback) => void, callback: ErrorCallback): void; + forEachOfSeries(obj: T[], iterator: AsyncForEachOfIterator, callback?: ErrorCallback): void; + forEachOfLimit(obj: any, limit: number, iterator: (item: any, key: [string|number], callback?: ErrorCallback) => void, callback: ErrorCallback): void; + forEachOfLimit(obj: T[], limit: number, iterator: AsyncForEachOfIterator, callback?: ErrorCallback): void; + map(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; + mapSeries(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; + mapLimit(arr: T[], limit: number, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; + filter(arr: T[], iterator: AsyncResultIterator, callback?: (results: T[]) => any): any; + select(arr: T[], iterator: AsyncResultIterator, callback?: (results: T[]) => any): any; + filterSeries(arr: T[], iterator: AsyncResultIterator, callback?: (results: T[]) => any): any; + selectSeries(arr: T[], iterator: AsyncResultIterator, callback?: (results: T[]) => any): any; + filterLimit(arr: T[], limit: number, iterator: AsyncResultIterator, callback?: (results: T[]) => any): any; + selectLimit(arr: T[], limit: number, iterator: AsyncResultIterator, callback?: (results: T[]) => any): any; + reject(arr: T[], iterator: AsyncResultIterator, callback?: (results: T[]) => any): any; + rejectSeries(arr: T[], iterator: AsyncResultIterator, callback?: (results: T[]) => any): any; + rejectLimit(arr: T[], limit: number, iterator: AsyncResultIterator, callback?: (results: T[]) => any): any; + reduce(arr: T[], memo: R, iterator: AsyncMemoIterator, callback?: AsyncResultCallback): any; + inject(arr: T[], memo: R, iterator: AsyncMemoIterator, callback?: AsyncResultCallback): any; + foldl(arr: T[], memo: R, iterator: AsyncMemoIterator, callback?: AsyncResultCallback): any; + reduceRight(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncResultCallback): any; + foldr(arr: T[], memo: R, iterator: AsyncMemoIterator, callback: AsyncResultCallback): any; + detect(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: T) => void): any; + detectSeries(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: T) => void): any; + detectLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: (result: T) => void): any; + sortBy(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; + some(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: boolean) => void): any; + someLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: (result: boolean) => void): any; + any(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: boolean) => void): any; + every(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: boolean) => any): any; + everyLimit(arr: T[], limit: number, iterator: AsyncBooleanIterator, callback?: (result: boolean) => any): any; + all(arr: T[], iterator: AsyncBooleanIterator, callback?: (result: boolean) => any): any; + concat(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; + concatSeries(arr: T[], iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): any; + + // Control Flow + series(tasks: AsyncFunction[], callback?: AsyncResultArrayCallback): void; + series(tasks: Dictionary>, callback?: AsyncResultObjectCallback): void; + parallel(tasks: Array>, callback?: AsyncResultArrayCallback): void; + parallel(tasks: Dictionary>, callback?: AsyncResultObjectCallback): void; + parallelLimit(tasks: Array>, limit: number, callback?: AsyncResultArrayCallback): void; + parallelLimit(tasks: Dictionary>, limit: number, callback?: AsyncResultObjectCallback): void; + whilst(test: () => boolean, fn: AsyncVoidFunction, callback: (err: any) => void): void; + doWhilst(fn: AsyncVoidFunction, test: () => boolean, callback: (err: any) => void): void; + until(test: () => boolean, fn: AsyncVoidFunction, callback: (err: any) => void): void; + doUntil(fn: AsyncVoidFunction, test: () => boolean, callback: (err: any) => void): void; + during(test: (testCallback : (error: Error, truth: boolean) => void) => void, fn: AsyncVoidFunction, callback: (err: any) => void): void; + doDuring(fn: AsyncVoidFunction, test: (testCallback: (error: Error, truth: boolean) => void) => void, callback: (err: any) => void): void; + forever(next: (errCallback : (err: Error) => void) => void, errBack: (err: Error) => void) : void; + waterfall(tasks: Function[], callback?: (err: Error, result: any) => void): void; + compose(...fns: Function[]): void; + seq(...fns: Function[]): void; + applyEach(fns: Function[], argsAndCallback: any[]): void; // applyEach(fns, args..., callback). TS does not support ... for a middle argument. Callback is optional. + applyEachSeries(fns: Function[], argsAndCallback: any[]): void; // applyEachSeries(fns, args..., callback). TS does not support ... for a middle argument. Callback is optional. + queue(worker: AsyncWorker, concurrency?: number): AsyncQueue; + priorityQueue(worker: AsyncWorker, concurrency: number): AsyncPriorityQueue; + cargo(worker : (tasks: any[], callback : ErrorCallback) => void, payload? : number) : AsyncCargo; + auto(tasks: any, callback?: (error: Error, results: any) => void): void; + retry(opts: number, task: (callback : AsyncResultCallback, results: any) => void, callback: (error: Error, results: any) => void): void; + retry(opts: { times: number, interval: number }, task: (callback: AsyncResultCallback, results : any) => void, callback: (error: Error, results: any) => void): void; + iterator(tasks: Function[]): Function; + apply(fn: Function, ...arguments: any[]): AsyncFunction; + nextTick(callback: Function): void; + setImmediate(callback: Function): void; + + times (n: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; + timesSeries(n: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; + timesLimit(n: number, limit: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; + + // Utils + memoize(fn: Function, hasher?: Function): Function; + unmemoize(fn: Function): Function; + ensureAsync(fn: (... argsAndCallback: any[]) => void): Function; + constant(...values: any[]): Function; + asyncify(fn: Function): Function; + wrapSync(fn: Function): Function; + log(fn: Function, ...arguments: any[]): void; + dir(fn: Function, ...arguments: any[]): void; + noConflict(): Async; +} + +declare var async: Async; + +declare module "async" { + export = async; +} From 55465434fd031109b131dd43a578eebb1d8f15d6 Mon Sep 17 00:00:00 2001 From: Basarat Syed Date: Mon, 24 Aug 2015 17:43:21 +1000 Subject: [PATCH 154/173] reactChidlren callbacks accept index ref https://github.com/facebook/react/blob/10c816604336d4b3ec4c2a4e0ac42061a37dd8ee/src/isomorphic/children/ReactChildren.js#L52 --- react/react-addons.d.ts | 4 ++-- react/react-global.d.ts | 4 ++-- react/react.d.ts | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/react/react-addons.d.ts b/react/react-addons.d.ts index d9915e502..822f370b8 100644 --- a/react/react-addons.d.ts +++ b/react/react-addons.d.ts @@ -748,8 +748,8 @@ declare module "react/addons" { // ---------------------------------------------------------------------- interface ReactChildren { - map(children: ReactNode, fn: (child: ReactChild) => T): { [key:string]: T }; - forEach(children: ReactNode, fn: (child: ReactChild) => any): void; + map(children: ReactNode, fn: (child: ReactChild, index: number) => T): { [key:string]: T }; + forEach(children: ReactNode, fn: (child: ReactChild, index: number) => any): void; count(children: ReactNode): number; only(children: ReactNode): ReactChild; } diff --git a/react/react-global.d.ts b/react/react-global.d.ts index f8b376355..d33d4268d 100644 --- a/react/react-global.d.ts +++ b/react/react-global.d.ts @@ -755,8 +755,8 @@ declare module React { // ---------------------------------------------------------------------- interface ReactChildren { - map(children: ReactNode, fn: (child: ReactChild) => T): { [key:string]: T }; - forEach(children: ReactNode, fn: (child: ReactChild) => any): void; + map(children: ReactNode, fn: (child: ReactChild, index: number) => T): { [key:string]: T }; + forEach(children: ReactNode, fn: (child: ReactChild, index: number) => any): void; count(children: ReactNode): number; only(children: ReactNode): ReactChild; } diff --git a/react/react.d.ts b/react/react.d.ts index 218c6c94a..f2697fd25 100644 --- a/react/react.d.ts +++ b/react/react.d.ts @@ -755,8 +755,8 @@ declare module __React { // ---------------------------------------------------------------------- interface ReactChildren { - map(children: ReactNode, fn: (child: ReactChild) => T): { [key:string]: T }; - forEach(children: ReactNode, fn: (child: ReactChild) => any): void; + map(children: ReactNode, fn: (child: ReactChild, index: number) => T): { [key:string]: T }; + forEach(children: ReactNode, fn: (child: ReactChild, index: number) => any): void; count(children: ReactNode): number; only(children: ReactNode): ReactChild; } From 1dbfd8a1641614248d3415dd319537d35f8cc9f0 Mon Sep 17 00:00:00 2001 From: tkQubo Date: Mon, 24 Aug 2015 19:50:57 +0900 Subject: [PATCH 155/173] Add gulp-coffeeify --- gulp-coffeeify/gulp-coffeeify-tests.ts | 53 ++++++++++++++++++++++++++ gulp-coffeeify/gulp-coffeeify.d.ts | 42 ++++++++++++++++++++ 2 files changed, 95 insertions(+) create mode 100644 gulp-coffeeify/gulp-coffeeify-tests.ts create mode 100644 gulp-coffeeify/gulp-coffeeify.d.ts diff --git a/gulp-coffeeify/gulp-coffeeify-tests.ts b/gulp-coffeeify/gulp-coffeeify-tests.ts new file mode 100644 index 000000000..662428563 --- /dev/null +++ b/gulp-coffeeify/gulp-coffeeify-tests.ts @@ -0,0 +1,53 @@ +/// +/// + +import gulp = require('gulp'); +import coffeeify = require('gulp-coffeeify'); + +// Basic usage +gulp.task('scripts', function() { + gulp.src('src/coffee/**/*.coffee') + .pipe(coffeeify()) + .pipe(gulp.dest('./build/js')); +}); + +gulp.task('scripts', function() { + gulp.src('src/coffee/**/*.coffee') + .pipe(coffeeify({ + options: { + debug: true, // source map + paths: [__dirname + '/node_modules', __dirname + '/src/coffee'] + } + })) + .pipe(gulp.dest('./build/js')); +}); + +gulp.task('scripts', function() { + gulp.src('src/coffee/**/*.coffee') + .pipe(coffeeify({ + aliases: [ + { + cwd: 'src/coffee/app', + base: 'app' + } + ] + })) + .pipe(gulp.dest('./build/js')); +}); + +var xform = function(data: string){ + return 'module.exports = "' + data + '"'; +}; +gulp.task('scripts', function() { + gulp.src('src/coffee/**/*.coffee') + .pipe(coffeeify({ + transforms: [ + { + ext: '.extension', + transform: xform + } + ] + })) + .pipe(gulp.dest('./build/js')); +}); + diff --git a/gulp-coffeeify/gulp-coffeeify.d.ts b/gulp-coffeeify/gulp-coffeeify.d.ts new file mode 100644 index 000000000..e47f863ac --- /dev/null +++ b/gulp-coffeeify/gulp-coffeeify.d.ts @@ -0,0 +1,42 @@ +// Type definitions for gulp-coffeeify +// Project: gulp-coffeeify +// Definitions by: Qubo +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "gulp-coffeeify" { + namespace coffeeify { + interface Coffeeify { + (option?: Option): NodeJS.ReadWriteStream; + } + + interface Option { + options?: { + debug?: boolean; + paths?: string[]; + }, + /** + * [DEPRECATED]: You should use a 'paths' options of browserify. + */ + aliases?: Aliases; + /** + * [DEPRECATED] + */ + transforms?: Transforms; + } + + interface Aliases { + cwd?: string; + base?: string; + } + + interface Transforms { + ext?: string; + transform?(data: string): string; + } + } + + var coffeeify: coffeeify.Coffeeify; + + export = coffeeify; +} + From 94fda366f42b0dccf2703579ffff0e2b5e4a065a Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Mon, 24 Aug 2015 19:51:24 +0900 Subject: [PATCH 156/173] Assertions should return Thenable --- .../chai-as-promised-tests-with-bluebird.ts | 7 + .../chai-as-promised-tests-with-q.ts | 7 + chai-as-promised/chai-as-promised-tests.ts | 58 +++- chai-as-promised/chai-as-promised.d.ts | 283 +++++++++++++++++- 4 files changed, 326 insertions(+), 29 deletions(-) create mode 100644 chai-as-promised/chai-as-promised-tests-with-bluebird.ts create mode 100644 chai-as-promised/chai-as-promised-tests-with-q.ts diff --git a/chai-as-promised/chai-as-promised-tests-with-bluebird.ts b/chai-as-promised/chai-as-promised-tests-with-bluebird.ts new file mode 100644 index 000000000..e27205c41 --- /dev/null +++ b/chai-as-promised/chai-as-promised-tests-with-bluebird.ts @@ -0,0 +1,7 @@ +/// +/// + +// Compatibility check for Promise/A+ valid libraries +var thenableNum: Chai.Thenable; +import Bluebird = require('bluebird'); +thenableNum = Bluebird.resolve(1); diff --git a/chai-as-promised/chai-as-promised-tests-with-q.ts b/chai-as-promised/chai-as-promised-tests-with-q.ts new file mode 100644 index 000000000..91fe676cd --- /dev/null +++ b/chai-as-promised/chai-as-promised-tests-with-q.ts @@ -0,0 +1,7 @@ +/// +/// + +// Compatibility check for Promise/A+ valid libraries +var thenableNum: Chai.Thenable; +import Q = require('q'); +thenableNum = Q.resolve(1); diff --git a/chai-as-promised/chai-as-promised-tests.ts b/chai-as-promised/chai-as-promised-tests.ts index 95a433517..dd528e9f6 100644 --- a/chai-as-promised/chai-as-promised-tests.ts +++ b/chai-as-promised/chai-as-promised-tests.ts @@ -1,23 +1,53 @@ /// +/// import chai = require('chai'); import chaiAsPromised = require('chai-as-promised'); +import Q = require('q'); chai.use(chaiAsPromised); // ReSharper disable WrongExpressionStatement -var promise: any; -chai.expect(promise).to.eventually.equal(3); -chai.expect(promise).to.become(3); -chai.expect(promise).to.be.fulfilled; -chai.expect(promise).to.be.rejected; -chai.expect(promise).to.be.rejectedWith(Error); -chai.expect(promise).to.notify(() => console.log('done')); +// BDD API (expect) +var thenableNum: Chai.Thenable; +thenableNum = chai.expect(thenableNum).to.eventually.equal(3); +thenableNum = chai.expect(thenableNum).to.eventually.have.property('foo'); +thenableNum = chai.expect(thenableNum).to.become(3); +thenableNum = chai.expect(thenableNum).to.be.fulfilled; +thenableNum = chai.expect(thenableNum).to.be.rejected; +thenableNum = chai.expect(thenableNum).to.be.rejectedWith(Error); +thenableNum = chai.expect(thenableNum).to.notify(() => console.log('done')); -chai.assert.eventually.equal(promise, 4, 'Message'); -chai.assert.isFulfilled(promise, "optional message"); -chai.assert.becomes(promise, "foo", "optional message"); -chai.assert.doesNotBecome(promise, "foo", "optional message"); -chai.assert.isRejected(promise, "optional message"); -chai.assert.isRejected(promise, Error, "optional message"); -chai.assert.isRejected(promise, /error message matcher/, "optional message"); +// BDD API (should) +thenableNum = thenableNum.should.be.fulfilled; +thenableNum = thenableNum.should.eventually.deep.equal(3); +thenableNum = thenableNum.should.become(3); +thenableNum = thenableNum.should.be.rejected; +thenableNum = thenableNum.should.be.rejectedWith(Error); +thenableNum = thenableNum.should.eventually.equal(3).notify(() => console.log('done')); +thenableNum = thenableNum.should.be.fulfilled.and.notify(() => console.log('done')); + +// Complex examples on https://github.com/domenic/chai-as-promised#working-with-non-promisefriendly-test-runners +thenableNum.should.be.fulfilled.then(function () { + thenableNum.should.equal("after"); +}).should.notify(() => console.log('done')); + +Q.all([ + thenableNum.should.become("happy"), + thenableNum.should.eventually.have.property("fun times"), + thenableNum.should.be.rejectedWith(TypeError, "only joyful types are allowed") +]).should.notify(() => console.log('done')); + +// Assert API +var thenableVoid: Chai.Thenable; +thenableVoid = chai.assert.eventually.equal(thenableNum, 4, 'Message'); +thenableVoid = chai.assert.isFulfilled(thenableNum, "optional message"); +thenableVoid = chai.assert.becomes(thenableNum, "foo", "optional message"); +thenableVoid = chai.assert.doesNotBecome(thenableNum, "foo", "optional message"); +thenableVoid = chai.assert.isRejected(thenableNum, "optional message"); +thenableVoid = chai.assert.isRejected(thenableNum, Error, "optional message"); +thenableVoid = chai.assert.isRejected(thenableNum, /error message matcher/, "optional message"); + +// Check that original chai assertions are not broken +var undef: void; +undef = chai.assert.equal(10, 4, 'Message'); diff --git a/chai-as-promised/chai-as-promised.d.ts b/chai-as-promised/chai-as-promised.d.ts index 106bbf41e..5b68b0b5d 100644 --- a/chai-as-promised/chai-as-promised.d.ts +++ b/chai-as-promised/chai-as-promised.d.ts @@ -12,25 +12,278 @@ declare module 'chai-as-promised' { declare module Chai { - interface Assertion { - become(expected: any): Assertion; - fulfilled: Assertion; - rejected: Assertion; - rejectedWith(expected: any): Assertion; - notify(fn: Function): Assertion; + // chai-as-promised can take Promise/A+ valid promises. + interface Thenable { + then(onFulfilled?: (value: R) => U | Thenable, onRejected?: (error: any) => U | Thenable): Thenable; + then(onFulfilled?: (value: R) => U | Thenable, onRejected?: (error: any) => void): Thenable; } - interface LanguageChains { - eventually: Assertion; + // For BDD API + interface Assertion extends LanguageChains, NumericComparison, TypeComparison { + eventually: PromisedAssertion; + become(expected: any): PromisedAssertion; + fulfilled: PromisedAssertion; + rejected: PromisedAssertion; + rejectedWith(expected: any, message?: string): PromisedAssertion; + notify(fn: Function): PromisedAssertion; } + // Eventually does not have .then(), but PromisedAssertion have. + interface Eventually extends PromisedLanguageChains, PromisedNumericComparison, PromisedTypeComparison { + // From chai-as-promised + become(expected: Thenable): PromisedAssertion; + fulfilled: PromisedAssertion; + rejected: PromisedAssertion; + rejectedWith(expected: any): PromisedAssertion; + notify(fn: Function): PromisedAssertion; + + // From chai + not: PromisedAssertion; + deep: PromisedDeep; + a: PromisedTypeComparison; + an: PromisedTypeComparison; + include: PromisedInclude; + contain: PromisedInclude; + ok: PromisedAssertion; + true: PromisedAssertion; + false: PromisedAssertion; + null: PromisedAssertion; + undefined: PromisedAssertion; + exist: PromisedAssertion; + empty: PromisedAssertion; + arguments: PromisedAssertion; + Arguments: PromisedAssertion; + equal: PromisedEqual; + equals: PromisedEqual; + eq: PromisedEqual; + eql: PromisedEqual; + eqls: PromisedEqual; + property: PromisedProperty; + ownProperty: PromisedOwnProperty; + haveOwnProperty: PromisedOwnProperty; + length: PromisedLength; + lengthOf: PromisedLength; + match(regexp: RegExp|string, message?: string): PromisedAssertion; + string(string: string, message?: string): PromisedAssertion; + keys: PromisedKeys; + key(string: string): PromisedAssertion; + throw: PromisedThrow; + throws: PromisedThrow; + Throw: PromisedThrow; + respondTo(method: string, message?: string): PromisedAssertion; + itself: PromisedAssertion; + satisfy(matcher: Function, message?: string): PromisedAssertion; + closeTo(expected: number, delta: number, message?: string): PromisedAssertion; + members: PromisedMembers; + } + + interface PromisedAssertion extends Eventually, Thenable { + } + + interface PromisedLanguageChains { + eventually: Eventually; + + // From chai + to: PromisedAssertion; + be: PromisedAssertion; + been: PromisedAssertion; + is: PromisedAssertion; + that: PromisedAssertion; + which: PromisedAssertion; + and: PromisedAssertion; + has: PromisedAssertion; + have: PromisedAssertion; + with: PromisedAssertion; + at: PromisedAssertion; + of: PromisedAssertion; + same: PromisedAssertion; + } + + interface PromisedNumericComparison { + above: PromisedNumberComparer; + gt: PromisedNumberComparer; + greaterThan: PromisedNumberComparer; + least: PromisedNumberComparer; + gte: PromisedNumberComparer; + below: PromisedNumberComparer; + lt: PromisedNumberComparer; + lessThan: PromisedNumberComparer; + most: PromisedNumberComparer; + lte: PromisedNumberComparer; + within(start: number, finish: number, message?: string): PromisedAssertion; + } + + interface PromisedNumberComparer { + (value: number, message?: string): PromisedAssertion; + } + + interface PromisedTypeComparison { + (type: string, message?: string): PromisedAssertion; + instanceof: PromisedInstanceOf; + instanceOf: PromisedInstanceOf; + } + + interface PromisedInstanceOf { + (constructor: Object, message?: string): PromisedAssertion; + } + + interface PromisedDeep { + equal: PromisedEqual; + include: PromisedInclude; + property: PromisedProperty; + } + + interface PromisedEqual { + (value: any, message?: string): PromisedAssertion; + } + + interface PromisedProperty { + (name: string, value?: any, message?: string): PromisedAssertion; + } + + interface PromisedOwnProperty { + (name: string, message?: string): PromisedAssertion; + } + + interface PromisedLength extends PromisedLanguageChains, PromisedNumericComparison { + (length: number, message?: string): PromisedAssertion; + } + + interface PromisedInclude { + (value: Object, message?: string): PromisedAssertion; + (value: string, message?: string): PromisedAssertion; + (value: number, message?: string): PromisedAssertion; + keys: PromisedKeys; + members: PromisedMembers; + } + + interface PromisedKeys { + (...keys: string[]): PromisedAssertion; + (keys: any[]): PromisedAssertion; + } + + interface PromisedThrow { + (): PromisedAssertion; + (expected: string, message?: string): PromisedAssertion; + (expected: RegExp, message?: string): PromisedAssertion; + (constructor: Error, expected?: string, message?: string): PromisedAssertion; + (constructor: Error, expected?: RegExp, message?: string): PromisedAssertion; + (constructor: Function, expected?: string, message?: string): PromisedAssertion; + (constructor: Function, expected?: RegExp, message?: string): PromisedAssertion; + } + + interface PromisedMembers { + (set: any[], message?: string): PromisedAssertion; + } + + // For Assert API interface Assert { - eventually: Assert; - isFulfilled(promise: any, message?: string): void; - becomes(promise: any, expected: any, message?: string): void; - doesNotBecome(promise: any, expected: any, message?: string): void; - isRejected(promise: any, message?: string): void; - isRejected(promise: any, expected: any, message?: string): void; - isRejected(promise: any, match: RegExp, message?: string): void; + eventually: PromisedAssert; + isFulfilled(promise: Thenable, message?: string): Thenable; + becomes(promise: Thenable, expected: any, message?: string): Thenable; + doesNotBecome(promise: Thenable, expected: any, message?: string): Thenable; + isRejected(promise: Thenable, message?: string): Thenable; + isRejected(promise: Thenable, expected: any, message?: string): Thenable; + isRejected(promise: Thenable, match: RegExp, message?: string): Thenable; + notify(fn: Function): Thenable; + } + + export interface PromisedAssert { + fail(actual?: any, expected?: any, msg?: string, operator?: string): Thenable; + + ok(val: any, msg?: string): Thenable; + notOk(val: any, msg?: string): Thenable; + + equal(act: any, exp: any, msg?: string): Thenable; + notEqual(act: any, exp: any, msg?: string): Thenable; + + strictEqual(act: any, exp: any, msg?: string): Thenable; + notStrictEqual(act: any, exp: any, msg?: string): Thenable; + + deepEqual(act: any, exp: any, msg?: string): Thenable; + notDeepEqual(act: any, exp: any, msg?: string): Thenable; + + isTrue(val: any, msg?: string): Thenable; + isFalse(val: any, msg?: string): Thenable; + + isNull(val: any, msg?: string): Thenable; + isNotNull(val: any, msg?: string): Thenable; + + isUndefined(val: any, msg?: string): Thenable; + isDefined(val: any, msg?: string): Thenable; + + isFunction(val: any, msg?: string): Thenable; + isNotFunction(val: any, msg?: string): Thenable; + + isObject(val: any, msg?: string): Thenable; + isNotObject(val: any, msg?: string): Thenable; + + isArray(val: any, msg?: string): Thenable; + isNotArray(val: any, msg?: string): Thenable; + + isString(val: any, msg?: string): Thenable; + isNotString(val: any, msg?: string): Thenable; + + isNumber(val: any, msg?: string): Thenable; + isNotNumber(val: any, msg?: string): Thenable; + + isBoolean(val: any, msg?: string): Thenable; + isNotBoolean(val: any, msg?: string): Thenable; + + typeOf(val: any, type: string, msg?: string): Thenable; + notTypeOf(val: any, type: string, msg?: string): Thenable; + + instanceOf(val: any, type: Function, msg?: string): Thenable; + notInstanceOf(val: any, type: Function, msg?: string): Thenable; + + include(exp: string, inc: any, msg?: string): Thenable; + include(exp: any[], inc: any, msg?: string): Thenable; + + notInclude(exp: string, inc: any, msg?: string): Thenable; + notInclude(exp: any[], inc: any, msg?: string): Thenable; + + match(exp: any, re: RegExp, msg?: string): Thenable; + notMatch(exp: any, re: RegExp, msg?: string): Thenable; + + property(obj: Object, prop: string, msg?: string): Thenable; + notProperty(obj: Object, prop: string, msg?: string): Thenable; + deepProperty(obj: Object, prop: string, msg?: string): Thenable; + notDeepProperty(obj: Object, prop: string, msg?: string): Thenable; + + propertyVal(obj: Object, prop: string, val: any, msg?: string): Thenable; + propertyNotVal(obj: Object, prop: string, val: any, msg?: string): Thenable; + + deepPropertyVal(obj: Object, prop: string, val: any, msg?: string): Thenable; + deepPropertyNotVal(obj: Object, prop: string, val: any, msg?: string): Thenable; + + lengthOf(exp: any, len: number, msg?: string): Thenable; + //alias frenzy + throw(fn: Function, msg?: string): Thenable; + throw(fn: Function, regExp: RegExp): Thenable; + throw(fn: Function, errType: Function, msg?: string): Thenable; + throw(fn: Function, errType: Function, regExp: RegExp): Thenable; + + throws(fn: Function, msg?: string): Thenable; + throws(fn: Function, regExp: RegExp): Thenable; + throws(fn: Function, errType: Function, msg?: string): Thenable; + throws(fn: Function, errType: Function, regExp: RegExp): Thenable; + + Throw(fn: Function, msg?: string): Thenable; + Throw(fn: Function, regExp: RegExp): Thenable; + Throw(fn: Function, errType: Function, msg?: string): Thenable; + Throw(fn: Function, errType: Function, regExp: RegExp): Thenable; + + doesNotThrow(fn: Function, msg?: string): Thenable; + doesNotThrow(fn: Function, regExp: RegExp): Thenable; + doesNotThrow(fn: Function, errType: Function, msg?: string): Thenable; + doesNotThrow(fn: Function, errType: Function, regExp: RegExp): Thenable; + + operator(val: any, operator: string, val2: any, msg?: string): Thenable; + closeTo(act: number, exp: number, delta: number, msg?: string): Thenable; + + sameMembers(set1: any[], set2: any[], msg?: string): Thenable; + includeMembers(set1: any[], set2: any[], msg?: string): Thenable; + + ifError(val: any, msg?: string): Thenable; } } From 1781feb65cdf1fdf505aef85a00beccbe32f119d Mon Sep 17 00:00:00 2001 From: tkQubo Date: Mon, 24 Aug 2015 19:56:16 +0900 Subject: [PATCH 157/173] Fix project url --- gulp-coffeeify/gulp-coffeeify.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gulp-coffeeify/gulp-coffeeify.d.ts b/gulp-coffeeify/gulp-coffeeify.d.ts index e47f863ac..6973b38cc 100644 --- a/gulp-coffeeify/gulp-coffeeify.d.ts +++ b/gulp-coffeeify/gulp-coffeeify.d.ts @@ -1,5 +1,5 @@ // Type definitions for gulp-coffeeify -// Project: gulp-coffeeify +// Project: https://github.com/nariyu/gulp-coffeeify // Definitions by: Qubo // Definitions: https://github.com/borisyankov/DefinitelyTyped From 49c153d83b8f70d4dbf77fa3beab6b9dcf4891fa Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Mon, 24 Aug 2015 19:57:24 +0900 Subject: [PATCH 158/173] Add Kuniwak to credits --- chai-as-promised/chai-as-promised.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chai-as-promised/chai-as-promised.d.ts b/chai-as-promised/chai-as-promised.d.ts index 5b68b0b5d..e6644b03c 100644 --- a/chai-as-promised/chai-as-promised.d.ts +++ b/chai-as-promised/chai-as-promised.d.ts @@ -1,6 +1,6 @@ // Type definitions for chai-as-promised // Project: https://github.com/domenic/chai-as-promised/ -// Definitions by: jt000 +// Definitions by: jt000 , Yuki Kokubun // Definitions: https://github.com/borisyankov/DefinitelyTyped /// From 8abef0fcb5676b38159adb6f93af4385092998c4 Mon Sep 17 00:00:00 2001 From: tkQubo Date: Mon, 24 Aug 2015 21:57:54 +0900 Subject: [PATCH 159/173] Add vinyl-buffer --- vinyl-buffer/vinyl-buffer-tests.ts | 14 ++++++++++++++ vinyl-buffer/vinyl-buffer.d.ts | 17 +++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 vinyl-buffer/vinyl-buffer-tests.ts create mode 100644 vinyl-buffer/vinyl-buffer.d.ts diff --git a/vinyl-buffer/vinyl-buffer-tests.ts b/vinyl-buffer/vinyl-buffer-tests.ts new file mode 100644 index 000000000..6a36d0f52 --- /dev/null +++ b/vinyl-buffer/vinyl-buffer-tests.ts @@ -0,0 +1,14 @@ +/// +/// +/// + +import buffer = require('vinyl-buffer'); +import gulp = require('gulp') +import browserify = require('browserify'); + +gulp.task('build', function() { + return browserify('./index.js') + .bundle() + .pipe(buffer()) + .pipe(gulp.dest('dist/')); +}); diff --git a/vinyl-buffer/vinyl-buffer.d.ts b/vinyl-buffer/vinyl-buffer.d.ts new file mode 100644 index 000000000..dd868eb80 --- /dev/null +++ b/vinyl-buffer/vinyl-buffer.d.ts @@ -0,0 +1,17 @@ +// Type definitions for vinyl-buffer +// Project: https://github.com/hughsk/vinyl-buffer +// Definitions by: Qubo +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "vinyl-buffer" { + namespace buffer { + interface Buffer { + (): NodeJS.ReadWriteStream; + } + } + + var buffer: buffer.Buffer; + + export = buffer; +} + From 44fdc4c19b75a5b6018ad4553898154136719fbe Mon Sep 17 00:00:00 2001 From: tkQubo Date: Mon, 24 Aug 2015 22:14:13 +0900 Subject: [PATCH 160/173] Add vinyl-paths --- vinyl-paths/vinyl-paths-tests.ts | 26 ++++++++++++++++++++++++++ vinyl-paths/vinyl-paths.d.ts | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 vinyl-paths/vinyl-paths-tests.ts create mode 100644 vinyl-paths/vinyl-paths.d.ts diff --git a/vinyl-paths/vinyl-paths-tests.ts b/vinyl-paths/vinyl-paths-tests.ts new file mode 100644 index 000000000..e369dcb64 --- /dev/null +++ b/vinyl-paths/vinyl-paths-tests.ts @@ -0,0 +1,26 @@ +/// +/// +/// + +import gulp = require('gulp'); +import del = require('del'); +import paths = require('vinyl-paths'); + +gulp.task('delete', function () { + return gulp.src('app/*') + .pipe(paths(del)); +}); + +// or if you need to use the paths after the pipeline +gulp.task('delete2', function (cb: Function) { + var vp = paths(); + + gulp.src('app/*') + .pipe(vp) + .pipe(gulp.dest('dist')) + .on('end', function () { + del(vp.paths, cb); + }); +}); + + diff --git a/vinyl-paths/vinyl-paths.d.ts b/vinyl-paths/vinyl-paths.d.ts new file mode 100644 index 000000000..681601eb9 --- /dev/null +++ b/vinyl-paths/vinyl-paths.d.ts @@ -0,0 +1,32 @@ +// Type definitions for vinyl-paths +// Project: https://github.com/sindresorhus/vinyl-paths +// Definitions by: Qubo +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "vinyl-paths" { + + namespace paths { + interface Paths extends NodeJS.ReadWriteStream { + paths: string[]; + } + + interface PathsStatic { + /** + * Use the file paths from a gulp pipeline in vanilla node module + * @param callback The optionally supplied callback will get a file path for every file and is expected + * to call the callback when done. An array of the file paths so far is available as a paths property + * on the stream. + */ + (callback?: Callback): Paths; + } + + interface Callback { + //TODO: Function is gulp.ITaskCallback, which is currently invisible + (path: string, callback: Function): any; + } + } + + var paths: paths.PathsStatic; + export = paths; +} + From 1a4b2f0ff98d7b1071474c4ab16f2626d9a62d31 Mon Sep 17 00:00:00 2001 From: tkQubo Date: Mon, 24 Aug 2015 22:18:47 +0900 Subject: [PATCH 161/173] Add reference to node --- vinyl-buffer/vinyl-buffer.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/vinyl-buffer/vinyl-buffer.d.ts b/vinyl-buffer/vinyl-buffer.d.ts index dd868eb80..b6edbb1aa 100644 --- a/vinyl-buffer/vinyl-buffer.d.ts +++ b/vinyl-buffer/vinyl-buffer.d.ts @@ -3,6 +3,8 @@ // Definitions by: Qubo // Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + declare module "vinyl-buffer" { namespace buffer { interface Buffer { From 25b3502efc4f4750346d2d9a03667398966154b9 Mon Sep 17 00:00:00 2001 From: tkQubo Date: Mon, 24 Aug 2015 22:19:29 +0900 Subject: [PATCH 162/173] Add reference to node --- vinyl-paths/vinyl-paths.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/vinyl-paths/vinyl-paths.d.ts b/vinyl-paths/vinyl-paths.d.ts index 681601eb9..fabc2c667 100644 --- a/vinyl-paths/vinyl-paths.d.ts +++ b/vinyl-paths/vinyl-paths.d.ts @@ -3,6 +3,8 @@ // Definitions by: Qubo // Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + declare module "vinyl-paths" { namespace paths { From 9b8299ce8b34edaea16329b4e391a77c77f91071 Mon Sep 17 00:00:00 2001 From: tkQubo Date: Mon, 24 Aug 2015 22:20:09 +0900 Subject: [PATCH 163/173] Add reference to node --- gulp-coffeeify/gulp-coffeeify.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/gulp-coffeeify/gulp-coffeeify.d.ts b/gulp-coffeeify/gulp-coffeeify.d.ts index 6973b38cc..b847b8c03 100644 --- a/gulp-coffeeify/gulp-coffeeify.d.ts +++ b/gulp-coffeeify/gulp-coffeeify.d.ts @@ -3,6 +3,8 @@ // Definitions by: Qubo // Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + declare module "gulp-coffeeify" { namespace coffeeify { interface Coffeeify { From 1f964fab44772ef1c4c61fc2c2246a6775627aa5 Mon Sep 17 00:00:00 2001 From: Ben Tesser Date: Tue, 11 Aug 2015 04:36:14 -0400 Subject: [PATCH 164/173] Ui-grid: Update Version and Plugin Support Extensive plugin support added (Plugin specific API, ColumnDef, GridOptions, GridRow, Constants). Added docs for all existing interfaces Fixed a few incorrect interfaces, updated interfaces to reflect latest version. Did some cleanup... Moved all plugins into their own modules --- ui-grid/ui-grid.d.ts | 3184 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 3047 insertions(+), 137 deletions(-) diff --git a/ui-grid/ui-grid.d.ts b/ui-grid/ui-grid.d.ts index 9dbb6dac9..a6460dbd4 100644 --- a/ui-grid/ui-grid.d.ts +++ b/ui-grid/ui-grid.d.ts @@ -6,13 +6,18 @@ // These are very definitely preliminary. Please feel free to improve. // Changelog: +// 8/11/2015 ui-grid v3.0.3 +// Extensive plugin support added (Plugin specific API, ColumnDef, GridOptions, GridRow, Constants). +// Added docs for all existing interfaces. +// Fixed a few incorrect interfaces, updated interfaces to reflect latest version. +// Did some cleanup... Moved all plugins into their own modules // 7/8/2015 ui-grid v3.0.0-rc.22-482dc67 // Added primary interfaces for row, column, api, grid, columnDef, and gridOptions. Needs more tests! - +/// /// declare module uiGrid { - export interface UIGridConstants { + export interface IUiGridConstants { LOG_DEBUG_MESSAGES: boolean; LOG_WARN_MESSAGES: boolean; LOG_ERROR_MESSAGES: boolean; @@ -116,67 +121,394 @@ declare module uiGrid { } } export interface IGridInstance { - appScope?: ng.IScope; - columnFooterHeight?: number; - footerHeight?: number; - isScrollingHorizontally?: boolean; - isScrollingVertically?: boolean; - scrollDirection?: number; - addRowHeaderColumn(column: IGridColumn): void; + /** + * adds a row header column to the grid + * @param {IColumnDef} colDef The column definition + */ + addRowHeaderColumn(colDef: IColumnDef): void; + /** + * uses the first row of data to assign colDef.type for any types not defined. + */ assignTypes(): void; + /** + * Populates columnDefs from the provided data + * @param {IRowBuilder} rowBuilder function to be called + */ buildColumnDefsFromData(rowBuilder: IRowBuilder): void; + /** + * creates GridColumn objects from the columnDefinition. + * Calls each registered columnBuilder to further process the column + * @param {IBuildColumnsOptions} options An object containing options to use when building columns + * * orderByColumnDefs: defaults to false. When true, buildColumns will order existing columns + * according to the order within the column definitions + * @returns {ng.IPromise} A promise to load any needed column resources + */ buildColumns(options: IBuildColumnsOptions): ng.IPromise; + /** + * calls each styleComputation function + */ buildStyles(): void; + /** + * Calls the callbacks based on the type of data change that has occurred. + * Always calls the ALL callbacks, calls the ROW, EDIT, COLUMN and OPTIONS callbacks + * if the event type is matching, or if the type is ALL. + * @param {number} type the type of event that occurred - one of the uiGridConstants.dataChange values + * (ALL, ROW, EDIT, COLUMN, OPTIONS + */ callDataChangeCallbacks(type: number): void; - clearAllFilters(refreshRows: boolean, clearConditions: boolean, clearFlags: boolean): void; + /** + * Clears all filters and optionally refreshes the visible rows. + * @param {boolean} [refreshRows=true] Refresh the rows? + * @param {boolean} [clearConditions=true] Clear conditions? + * @param {boolean} [clearFlags=true] Clear flags? + * @returns {ng.IPromise} If refreshRows is true, returns a promise of the rows refreshing + */ + clearAllFilters(refreshRows: boolean, clearConditions: boolean, + clearFlags: boolean): ng.IPromise; + /** + * refreshes the grid when a column refresh is notified, which triggers handling of the visible flag. + * This is called on uiGridConstants.dataChange.COLUMN, and is registered as a dataChangeCallback in grid.js + * @param {string} name column name + */ columnRefreshCallback(name: string): void; + /** + * creates the left render container if it doesn't already exist + */ createLeftContainer(): void; + /** + * creates the right render container if it doesn't already exist + */ createRightContainer(): void; + /** + * sets isScrollingHorizontally to true and sets it to false in a debounced function + */ flagScrollingHorizontally(): void; + /** + * sets isScrollingVertically to true and sets it to false in a debounced function + */ flagScrollingVertically(): void; + /** + * Gets the displayed value of a cell after applying any the cellFilter + * @param {IGridRow} row Row to access + * @param {IGridColumn} col Column to access + * @returns {string} Cell display value + */ getCellDisplayValue(row: IGridRow, col: IGridColumn): string; + /** + * Gets the displayed value of a cell + * @param {IGridRow} row Row to access + * @param {IGridColumn} col Column to access + * @returns {any} Cell value + */ getCellValue(row: IGridRow, col: IGridColumn): any; + /** + * returns a grid colDef for the column name + * @param {string} name Column name + * @returns {IColumnDef} The column definition + */ getColDef(name: string): IColumnDef; + /** + * returns a grid column by name + * @param {string} name Column name + * @returns {IGridColumn} The column + */ getColumn(name: string): IGridColumn; + /** + * Return the columns that the grid is currently being sorted by + * @returns {Array} the columns that the grid is currently being sorted by + */ getColumnSorting(): Array; - getGridQualifiedColField(col: IGridColumn): any; + /** + * Returns the $parse-able accessor for a column within its $scope + * @param {IGridColumn} col Column object + * @returns {string} $parse-able accessor for a column within its $scope + */ + getGridQualifiedColField(col: IGridColumn): string; + /** + * returns all columns except for rowHeader columns + * @returns {Array} All data columns + */ getOnlyDataColumns(): Array; + /** + * returns the GridRow that contains the rowEntity + * @param {any} rowEntity the gridOptionms.data array element instance + * @param {Array} rows The rows to look in. if not provided then it looks in grid.rows + */ getRow(rowEntity: any, rows?: Array): IGridRow; - handleWindowResize(): void; + /** + * Triggered when the browser window resizes; automatically resizes the grid + * @param {ng.IAngularEvent} $event Resize event + */ + handleWindowResize($event: ng.IAngularEvent): void; + /** + * returns true if leftContainer exists + * @returns {boolean} container exists? + */ hasLeftContainer(): boolean; + /** + * returns true if rightContainer exists + * @returns {boolean} container exists? + */ hasRightContainer(): boolean; + /** + * returns true if leftContainer has columns + * @returns {boolean} container has columns + */ hasLeftContainerColumns(): boolean; + /** + * returns true if rightContainer has columns + * @returns {boolean} container has columns + */ hasRightContainerColumns(): boolean; + /** + * Is grid right to left + * @returns {boolean} true if grid is RTL + */ isRTL(): boolean; - isRowHeaderColumn(col: IGridColumn): boolean; - modifyRows(): void; + /** + * Checks if column is a row header + * @param {IGridColumn} column The column + * @returns {boolean} true if the column is a row header + */ + isRowHeaderColumn(column: IGridColumn): boolean; + /** + * creates or removes GridRow objects from the newRawData array. Calls each registered + * rowBuilder to further process the row + * + * This method aims to achieve three things: + * 1. the resulting rows array is in the same order as the newRawData, we'll call + * rowsProcessors immediately after to sort the data anyway + * 2. if we have row hashing available, we try to use the rowHash to find the row + * 3. no memory leaks - rows that are no longer in newRawData need to be garbage collected + * + * The basic logic flow makes use of the newRawData, oldRows and oldHash, and creates + * the newRows and newHash + * + * Rows are identified using the hashKey if configured. If not configured, then rows + * are identified using the gridOptions.rowEquality function + * @param {Array} newRawData The new grid data + * @return {ng.IPromise} Promise which resolves when the rows have been created or removed + */ + modifyRows(newRawData: Array): ng.IPromise; + /** + * Notify the grid that a data or config change has occurred, + * where that change isn't something the grid was otherwise noticing. This + * might be particularly relevant where you've changed values within the data + * and you'd like cell classes to be re-evaluated, or changed config within + * the columnDef and you'd like headerCellClasses to be re-evaluated. + * @param {string} type one of the uiGridConstants.dataChange values [ALL, ROW, EDIT, COLUMN], which tells + * us which refreshes to fire + */ notifyDataChange(type: string): void; + /** + * precompiles all cell templates + */ precompileCellTemplates(): void; + /** + * processes all RowBuilders for the gridRow + * @param {IGridRow} gridRow reference to gridRow + * @returns {IGridRow} the gridRow with all additional behavior added + */ processRowBuilders(gridRow: IGridRow): IGridRow; + /** + * calls the row processors, specifically + * intended to reset the sorting when an edit is called, + * registered as a dataChangeCallback on uiGridConstants.dataChange.EDIT + * @param {string} name column name + */ processRowsCallback(name: string): void; + /** + * queues a grid refresh, a way of debouncing all the refreshes we might otherwise issue + */ queueGridRefresh(): void; + /** + * queues a grid refreshCanvas, a way of debouncing all the refreshes we might otherwise issue + */ queueRefresh(): void; + /** + * Redraw the rows and columns based on our current scroll position + * @param {boolean} [rowsAdded] Optional to indicate rows are added and the scroll percentage must be + * recalculated + */ redrawCanvas(rowsAdded?: boolean): void; + /** + * Refresh the rendered grid on screen. + * The refresh method re-runs both the columnProcessors and the + * rowProcessors, as well as calling refreshCanvas to update all + * the grid sizing. In general you should prefer to use queueGridRefresh + * instead, which is basically a debounced version of refresh. + * + * If you only want to resize the grid, not regenerate all the rows + * and columns, you should consider directly calling refreshCanvas instead. + * @param {boolean} rowsAltered Optional flag for refreshing when the number of rows has changed + */ refresh(rowsAltered?: boolean): void; + /** + * Builds all styles and recalculates much of the grid sizing + * @param {boolean} buildStyles optional parameter. Use TBD + * @returns {ng.IPromise} promise that is resolved when the canvas + * has been refreshed + */ refreshCanvas(buildStyles?: boolean): ng.IPromise; + /** + * Refresh the rendered rows on screen? Note: not functional at present + * @returns {ng.IPromise} promise that is resolved when render completes? + */ refreshRows(): ng.IPromise; + /** + * When the build creates columns from column definitions, the columnbuilders will be called to add + * additional properties to the column. + * @param {IColumnBuilder} columnBuilder function to be called + */ registerColumnBuilder(columnBuilder: IColumnBuilder): void; + /** + * Register a "columns processor" function. When the columns are updated, + * the grid calls each registered "columns processor", which has a chance + * to alter the set of columns, as long as the count is not modified. + * @param {IColumnProcessor} columnProcessor column processor function, which + * is run in the context of the grid (i.e. this for the function will be the grid), and + * which must return an updated renderedColumnsToProcess which can be passed to the next processor + * in the chain + * @param {number} priority the priority of this processor. In general we try to do them in 100s to leave room + * for other people to inject columns processors at intermediate priorities. + * Lower priority columnsProcessors run earlier.priority + */ registerColumnsProcessor(columnProcessor: IColumnProcessor, priority: number): void; + /** + * When a data change occurs, the data change callbacks of the specified type + * will be called. The rules are: + * + * - when the data watch fires, that is considered a ROW change (the data watch only notices + * added or removed rows) + * - when the api is called to inform us of a change, the declared type of that change is used + * - when a cell edit completes, the EDIT callbacks are triggered + * - when the columnDef watch fires, the COLUMN callbacks are triggered + * - when the options watch fires, the OPTIONS callbacks are triggered + * + * For a given event: + * - ALL calls ROW, EDIT, COLUMN, OPTIONS and ALL callbacks + * - ROW calls ROW and ALL callbacks + * - EDIT calls EDIT and ALL callbacks + * - COLUMN calls COLUMN and ALL callbacks + * - OPTIONS calls OPTIONS and ALL callbacks + * + * @param {(grid: IGridInstance) => void} callback function to be called + * @param {Array} types the types of data change you want to be informed of. Values from + * the uiGridConstants.dataChange values ( ALL, EDIT, ROW, COLUMN, OPTIONS ). Optional and defaults to + * ALL + * @returns {Function} deregister function - a function that can be called to deregister this callback + */ registerDataChangeCallback(callback: (grid: IGridInstance) => void, types: Array): Function; + /** + * When the build creates rows from gridOptions.data, the rowBuilders will be called to add + * additional properties to the row. + * @param {IRowBuilder} rowBuilder Function to be called + */ registerRowBuilder(rowBuilder: IRowBuilder): void; + /** + * Register a "rows processor" function. When the rows are updated, + * the grid calls each registered "rows processor", which has a chance + * to alter the set of rows (sorting, etc) as long as the count is not + * modified. + * + * @param {IRowProcessor} rowProcessor rows processor function, which + * is run in the context of the grid (i.e. this for the function will be the grid), and must + * return the updated rows list, which is passed to the next processor in the chain + * @param {number} priority the priority of this processor. + * In general we try to do them in 100s to leave room for other people to inject rows processors at + * intermediate priorities. Lower priority rowsProcessors run earlier. At present all rows visible + * is running at 50, filter is running at 100, sort is at 200, grouping at 400, selectable rows at + * 500, pagination at 900 (pagination will generally want to be last) + */ registerRowsProcessor(rowProcessor: IRowProcessor, priority: number): void; + /** + * registered a styleComputation function + * + * If the function returns a value it will be appended into the grid's `